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
float64
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
float64
1
77k
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
float64
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
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
0cda2408e86a3258194a2c3882c045b4c93525bc
28,716
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/src/elastos/droid/systemui/recents/views/RecentsView.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/src/elastos/droid/systemui/recents/views/RecentsView.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/src/elastos/droid/systemui/recents/views/RecentsView.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/systemui/recents/model/RecentsTaskLoader.h" #include "elastos/droid/systemui/recents/model/TaskGrouping.h" #include "elastos/droid/systemui/recents/views/RecentsView.h" #include "elastos/droid/systemui/recents/views/TaskStackView.h" #include "elastos/droid/systemui/recents/misc/Utilities.h" #include "elastos/droid/systemui/recents/Constants.h" #include "Elastos.Droid.Net.h" #include "Elastos.Droid.Provider.h" #include <elastos/droid/view/LayoutInflater.h> using Elastos::Droid::Animation::ITimeInterpolator; using Elastos::Droid::App::CActivityOptionsHelper; using Elastos::Droid::App::IActivityOptionsHelper; using Elastos::Droid::App::CTaskStackBuilderHelper; using Elastos::Droid::App::ITaskStackBuilderHelper; using Elastos::Droid::App::ITaskStackBuilder; using Elastos::Droid::App::EIID_IActivityOptionsOnAnimationStartedListener; using Elastos::Droid::Content::IComponentName; using Elastos::Droid::Content::CIntent; using Elastos::Droid::Content::IIntent; using Elastos::Droid::Content::Pm::IPackageManager; using Elastos::Droid::Graphics::CBitmapHelper; using Elastos::Droid::Graphics::BitmapConfig_ALPHA_8; using Elastos::Droid::Graphics::BitmapConfig_ARGB_8888; using Elastos::Droid::Graphics::IBitmap; using Elastos::Droid::Graphics::IBitmapHelper; using Elastos::Droid::Graphics::CCanvas; using Elastos::Droid::Graphics::ICanvas; using Elastos::Droid::Graphics::CRect; using Elastos::Droid::Graphics::IRect; using Elastos::Droid::Net::CUriHelper; using Elastos::Droid::Net::IUriHelper; using Elastos::Droid::Net::IUri; using Elastos::Droid::Os::CUserHandle; using Elastos::Droid::Os::IUserHandle; using Elastos::Droid::Provider::ISettings; using Elastos::Droid::View::LayoutInflater; using Elastos::Droid::SystemUI::Recents::Model::EIID_IPackageCallbacks; using Elastos::Droid::SystemUI::Recents::Model::RecentsTaskLoader; using Elastos::Droid::SystemUI::Recents::Model::TaskGrouping; using Elastos::Droid::SystemUI::Recents::Misc::Utilities; namespace Elastos { namespace Droid { namespace SystemUI { namespace Recents { namespace Views { //-------------------------------------------------------------- // RecentsView::OnAnimationStartedRunnable //-------------------------------------------------------------- RecentsView::OnAnimationStartedRunnable::OnAnimationStartedRunnable( /* [in] */ SystemServicesProxy* ssp) : mSsp(ssp) {} ECode RecentsView::OnAnimationStartedRunnable::Run() { mSsp->LockCurrentTask(); return NOERROR; } //-------------------------------------------------------------- // RecentsView::OnAnimationStartedListener //-------------------------------------------------------------- CAR_INTERFACE_IMPL(RecentsView::OnAnimationStartedListener, Object, IActivityOptionsOnAnimationStartedListener) RecentsView::OnAnimationStartedListener::OnAnimationStartedListener( /* [in] */ SystemServicesProxy* ssp, /* [in] */ RecentsView* host) : mHost(host) , mTriggered(FALSE) , mSsp(ssp) {} // @Override ECode RecentsView::OnAnimationStartedListener::OnAnimationStarted() { if (!mTriggered) { AutoPtr<Runnable> runnable = new OnAnimationStartedRunnable(mSsp); Boolean res; mHost->PostDelayed(runnable, 350, &res); mTriggered = TRUE; } return NOERROR; } RecentsView::LaunchRunnable::LaunchRunnable( /* [in] */ ITask* task, /* [in] */ IActivityOptions* launchOpts, /* [in] */ Boolean lockToTask, /* [in] */ RecentsView* host) : mTask(task) , mLaunchOpts(launchOpts) , mLockToTask(lockToTask) , mHost(host) {} // @Override ECode RecentsView::LaunchRunnable::Run() { Task* task = (Task*)mTask.Get(); AutoPtr<SystemServicesProxy> ssp; RecentsTaskLoader::GetInstance()->GetSystemServicesProxy((SystemServicesProxy**)&ssp); if (task->mIsActive) { // Bring an active task to the foreground ssp->MoveTaskToFront(task->mKey->mId, mLaunchOpts); } else { AutoPtr<IContext> context; mHost->GetContext((IContext**)&context); if (ssp->StartActivityFromRecents(context, task->mKey->mId, task->mActivityLabel, mLaunchOpts)) { if (mLaunchOpts == NULL && mLockToTask) { ssp->LockCurrentTask(); } } else { // Dismiss the task and return the user to home if we fail to // launch the task mHost->OnTaskViewDismissed(task); if (mHost->mCb != NULL) { mHost->mCb->OnTaskLaunchFailed(); } } } return NOERROR; } //-------------------------------------------------------------- // RecentsView //-------------------------------------------------------------- CAR_INTERFACE_IMPL_3(RecentsView, FrameLayout, IRecentsView, ITaskStackViewCallbacks, IPackageCallbacks) RecentsView::RecentsView() : mAlreadyLaunchingTask(FALSE) { } ECode RecentsView::constructor( /* [in] */ IContext* context) { return FrameLayout::constructor(context); } ECode RecentsView::constructor( /* [in] */ IContext* context, /* [in] */ IAttributeSet* attrs) { return constructor(context, attrs, 0); } ECode RecentsView::constructor( /* [in] */ IContext* context, /* [in] */ IAttributeSet* attrs, /* [in] */ Int32 defStyleAttr) { return constructor(context, attrs, defStyleAttr, 0); } ECode RecentsView::constructor( /* [in] */ IContext* context, /* [in] */ IAttributeSet* attrs, /* [in] */ Int32 defStyleAttr, /* [in] */ Int32 defStyleRes) { FAIL_RETURN(FrameLayout::constructor(context, attrs, defStyleAttr, defStyleRes)); mConfig = RecentsConfiguration::GetInstance(); LayoutInflater::From(context, (ILayoutInflater**)&mInflater); return NOERROR; } /** Sets the callbacks */ ECode RecentsView::SetCallbacks( /* [in] */ IRecentsViewCallbacks* cb) { mCb = cb; return NOERROR; } /** Sets the debug overlay */ ECode RecentsView::SetDebugOverlay( /* [in] */ DebugOverlayView* overlay) { mDebugOverlay = overlay; return NOERROR; } /** Set/get the bsp root node */ ECode RecentsView::SetTaskStacks( /* [in] */ IList* stacks) { // Remove all TaskStackViews (but leave the search bar) Int32 childCount; GetChildCount(&childCount); for (Int32 i = childCount - 1; i >= 0; i--) { AutoPtr<IView> v; GetChildAt(i, (IView**)&v); if (v != mSearchBar) { RemoveViewAt(i); } } // Create and add all the stacks for this partition of space. mStacks = stacks; Int32 numStacks; mStacks->GetSize(&numStacks); for (Int32 i = 0; i < numStacks; i++) { AutoPtr<IInterface> item; mStacks->Get(i, (IInterface**)&item); AutoPtr<ITaskStack> stack = ITaskStack::Probe(item); AutoPtr<IContext> context; GetContext((IContext**)&context); AutoPtr<TaskStackView> stackView = new TaskStackView(); stackView->constructor(context, stack); stackView->SetCallbacks((ITaskStackViewCallbacks*)this); // Enable debug mode drawing if (mConfig->mDebugModeEnabled) { stackView->SetDebugOverlay(mDebugOverlay); } AddView(stackView); } // Reset the launched state mAlreadyLaunchingTask = FALSE; return NOERROR; } /** Removes all the task stack views from this recents view. */ ECode RecentsView::RemoveAllTaskStacks() { Int32 childCount; GetChildCount(&childCount); for (Int32 i = childCount - 1; i >= 0; i--) { AutoPtr<IView> v; GetChildAt(i, (IView**)&v); if (v != mSearchBar) { RemoveViewAt(i); } } return NOERROR; } /** Launches the focused task from the first stack if possible */ Boolean RecentsView::LaunchFocusedTask() { // Get the first stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); AutoPtr<TaskStack> stack = stackView->mStack; // Iterate the stack views and try and find the focused task Int32 taskCount; stackView->GetChildCount(&taskCount); for (Int32 j = 0; j < taskCount; j++) { AutoPtr<IView> v; stackView->GetChildAt(j, (IView**)&v); AutoPtr<TaskView> tv = (TaskView*)ITaskView::Probe(v); AutoPtr<ITask> task = tv->GetTask(); if (tv->IsFocusedTask()) { OnTaskViewClicked(stackView, tv, stack, task, FALSE); return TRUE; } } } } return FALSE; } /** Launches the task that Recents was launched from, if possible */ Boolean RecentsView::LaunchPreviousTask() { // Get the first stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); AutoPtr<TaskStack> stack = stackView->mStack; AutoPtr<IArrayList> tasks = stack->GetTasks(); // Find the launch task in the stack Boolean isEmpty; tasks->IsEmpty(&isEmpty); if (!isEmpty) { Int32 taskCount; tasks->GetSize(&taskCount); for (Int32 j = 0; j < taskCount; j++) { AutoPtr<IInterface> item; tasks->Get(j, (IInterface**)&item); AutoPtr<Task> task = (Task*)ITask::Probe(item); if (task->mIsLaunchTarget) { AutoPtr<ITaskView> tv = stackView->GetChildViewForTask(task); OnTaskViewClicked(stackView, tv, stack, task, FALSE); return TRUE; } } } } } return FALSE; } /** Requests all task stacks to start their enter-recents animation */ ECode RecentsView::StartEnterRecentsAnimation( /* [in] */ ViewAnimation::TaskViewEnterContext* ctx) { Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); stackView->StartEnterRecentsAnimation(ctx); } } return NOERROR; } /** Requests all task stacks to start their exit-recents animation */ ECode RecentsView::StartExitToHomeAnimation( /* [in] */ ViewAnimation::TaskViewExitContext* ctx) { Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); stackView->StartExitToHomeAnimation(ctx); } } // Notify of the exit animation return mCb->OnExitToHomeAnimationTriggered(); } /** Adds the search bar */ ECode RecentsView::SetSearchBar( /* [in] */ IView* searchBar) { // Create the search bar (and hide it if we have no recent tasks) if (Constants::DebugFlags::App::EnableSearchLayout) { // Remove the previous search bar if one exists Int32 index; if (mSearchBar != NULL && (IndexOfChild(mSearchBar, &index), index > -1)) { RemoveView(mSearchBar); } // Add the new search bar if (searchBar != NULL) { mSearchBar = searchBar; AddView(mSearchBar); } } return NOERROR; } /** Returns whether there is currently a search bar */ Boolean RecentsView::HasSearchBar() { return mSearchBar != NULL; } /** Sets the visibility of the search bar */ ECode RecentsView::SetSearchBarVisibility( /* [in] */ Int32 visibility) { if (mSearchBar != NULL) { mSearchBar->SetVisibility(visibility); // Always bring the search bar to the top mSearchBar->BringToFront(); } return NOERROR; } /** * This is called with the full size of the window since we are handling our own insets. */ // @Override ECode RecentsView::OnMeasure( /* [in] */ Int32 widthMeasureSpec, /* [in] */ Int32 heightMeasureSpec) { Int32 width = MeasureSpec::GetSize(widthMeasureSpec); Int32 height = MeasureSpec::GetSize(heightMeasureSpec); // Get the search bar bounds and measure the search bar layout if (mSearchBar != NULL) { AutoPtr<IRect> searchBarSpaceBounds; CRect::New((IRect**)&searchBarSpaceBounds); Int32 top; mConfig->mSystemInsets->GetTop(&top); mConfig->GetSearchBarBounds(width, height, top, searchBarSpaceBounds); Int32 width, height; searchBarSpaceBounds->GetWidth(&width); searchBarSpaceBounds->GetHeight(&height); mSearchBar->Measure(MeasureSpec::MakeMeasureSpec(width, MeasureSpec::EXACTLY), MeasureSpec::MakeMeasureSpec(height, MeasureSpec::EXACTLY)); } AutoPtr<IRect> taskStackBounds; CRect::New((IRect**)&taskStackBounds); Int32 top, right; mConfig->mSystemInsets->GetTop(&top); mConfig->mSystemInsets->GetRight(&right); mConfig->GetTaskStackBounds(width, height, top, right, taskStackBounds); // Measure each TaskStackView with the full width and height of the window since the // transition view is a child of that stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); Int32 visibility; if (child != mSearchBar && (child->GetVisibility(&visibility), visibility != GONE)) { AutoPtr<TaskStackView> tsv = (TaskStackView*)ITaskStackView::Probe(child); // Set the insets to be the top/left inset + search bounds tsv->SetStackInsetRect(taskStackBounds); tsv->Measure(widthMeasureSpec, heightMeasureSpec); } } SetMeasuredDimension(width, height); return NOERROR; } /** * This is called with the full size of the window since we are handling our own insets. */ // @Override ECode RecentsView::OnLayout( /* [in] */ Boolean changed, /* [in] */ Int32 left, /* [in] */ Int32 top, /* [in] */ Int32 right, /* [in] */ Int32 bottom) { // Get the search bar bounds so that we lay it out if (mSearchBar != NULL) { AutoPtr<IRect> searchBarSpaceBounds; CRect::New((IRect**)&searchBarSpaceBounds); Int32 top; mConfig->mSystemInsets->GetTop(&top); Int32 width, height; GetMeasuredWidth(&width); GetMeasuredHeight(&height); mConfig->GetSearchBarBounds(width, height, top, searchBarSpaceBounds); Int32 left, right, bottom; searchBarSpaceBounds->GetLeft(&left); searchBarSpaceBounds->GetRight(&right); searchBarSpaceBounds->GetTop(&top); searchBarSpaceBounds->GetBottom(&bottom); mSearchBar->Layout(left, top, right, bottom); } // Layout each TaskStackView with the full width and height of the window since the // transition view is a child of that stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); Int32 visibility; if (child != mSearchBar && (child->GetVisibility(&visibility), visibility != GONE)) { Int32 width, height; child->GetMeasuredWidth(&width); child->GetMeasuredHeight(&height); child->Layout(left, top, left + width, top + height); } } return NOERROR; } // @Override ECode RecentsView::OnApplyWindowInsets( /* [in] */ IWindowInsets* insets, /* [out] */ IWindowInsets** outInsets) { VALIDATE_NOT_NULL(outInsets); // Update the configuration with the latest system insets and trigger a relayout AutoPtr<IRect> rect; insets->GetSystemWindowInsets((IRect**)&rect); mConfig->UpdateSystemInsets(rect); RequestLayout(); return insets->ConsumeSystemWindowInsets(outInsets); } /** Notifies each task view of the user interaction. */ ECode RecentsView::OnUserInteraction() { // Get the first stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); stackView->OnUserInteraction(); } } return NOERROR; } /** Focuses the next task in the first stack view */ ECode RecentsView::FocusNextTask( /* [in] */ Boolean forward) { // Get the first stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); stackView->FocusNextTask(forward); break; } } return NOERROR; } /** Dismisses the focused task. */ ECode RecentsView::DismissFocusedTask() { // Get the first stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); stackView->DismissFocusedTask(); break; } } return NOERROR; } /** Unfilters any filtered stacks */ Boolean RecentsView::UnfilterFilteredStacks() { if (mStacks != NULL) { // Check if there are any filtered stacks and unfilter them before we back out of Recents Boolean stacksUnfiltered = FALSE; Int32 numStacks; mStacks->GetSize(&numStacks); for (Int32 i = 0; i < numStacks; i++) { AutoPtr<IInterface> item; mStacks->Get(i, (IInterface**)&item); AutoPtr<TaskStack> stack = (TaskStack*)ITaskStack::Probe(item); if (stack->HasFilteredTasks()) { stack->UnfilterTasks(); stacksUnfiltered = TRUE; } } return stacksUnfiltered; } return FALSE; } /**** TaskStackView.TaskStackCallbacks Implementation ****/ // @Override ECode RecentsView::OnTaskViewClicked( /* [in] */ ITaskStackView* _stackView, /* [in] */ ITaskView* _tv, /* [in] */ ITaskStack* stack, /* [in] */ ITask* _task, /* [in] */ Boolean lockToTask) { TaskStackView* stackView = (TaskStackView*)_stackView; TaskView* tv = (TaskView*)_tv; Task* task = (Task*)_task; // Notify any callbacks of the launching of a new task if (mCb != NULL) { mCb->OnTaskViewClicked(); } // Skip if we are already launching tasks if (mAlreadyLaunchingTask) { return NOERROR; } mAlreadyLaunchingTask = TRUE; // Upfront the processing of the thumbnail AutoPtr<TaskViewTransform> transform = new TaskViewTransform(); AutoPtr<IView> sourceView; Int32 offsetX = 0; Int32 offsetY = 0; Float stackScroll = stackView->GetScroller()->GetStackScroll(); if (tv == NULL) { // If there is no actual task view, then use the stack view as the source view // and then offset to the expected transform rect, but bound this to just // outside the display rect (to ensure we don't animate from too far away) sourceView = stackView; transform = stackView->GetStackAlgorithm()->GetStackTransform(task, stackScroll, transform, NULL); transform->mRect->GetLeft(&offsetX); mConfig->mDisplayRect->GetHeight(&offsetY); } else { sourceView = tv->mThumbnailView; transform = stackView->GetStackAlgorithm()->GetStackTransform(task, stackScroll, transform, NULL); } // Compute the thumbnail to scale up from AutoPtr<RecentsTaskLoader> rtl = RecentsTaskLoader::GetInstance(); AutoPtr<SystemServicesProxy> ssp; rtl->GetSystemServicesProxy((SystemServicesProxy**)&ssp); AutoPtr<IActivityOptions> opts; Int32 w, h; if (task->mThumbnail != NULL && (task->mThumbnail->GetWidth(&w), w > 0) && (task->mThumbnail->GetHeight(&h), h > 0)) { AutoPtr<IBitmapHelper> bHelper; CBitmapHelper::AcquireSingleton((IBitmapHelper**)&bHelper); AutoPtr<IBitmap> b; if (tv != NULL) { // Disable any focused state before we draw the header if (tv->IsFocusedTask()) { tv->UnsetFocusedTask(); } Float scale; tv->GetScaleX(&scale); tv->mHeaderView->GetMeasuredWidth(&w); tv->mHeaderView->GetMeasuredHeight(&h); Int32 fromHeaderWidth = (Int32) (w * scale); Int32 fromHeaderHeight = (Int32) (h * scale); bHelper->CreateBitmap(fromHeaderWidth, fromHeaderHeight, BitmapConfig_ARGB_8888, (IBitmap**)&b); if (Constants::DebugFlags::App::EnableTransitionThumbnailDebugMode) { b->EraseColor(0xFFff0000); } else { AutoPtr<ICanvas> c; CCanvas::New(b, (ICanvas**)&c); Float scaleX, scaleY; tv->GetScaleX(&scaleX); tv->GetScaleY(&scaleY); c->Scale(scaleX, scaleY); tv->mHeaderView->Draw(c); c->SetBitmap(NULL); } } else { // Notify the system to skip the thumbnail layer by using an ALPHA_8 bitmap bHelper->CreateBitmap(1, 1, BitmapConfig_ALPHA_8, (IBitmap**)&b); } AutoPtr<IActivityOptionsOnAnimationStartedListener> animStartedListener; if (lockToTask) { animStartedListener = new OnAnimationStartedListener(ssp, this); } AutoPtr<IActivityOptionsHelper> aoHelper; CActivityOptionsHelper::AcquireSingleton((IActivityOptionsHelper**)&aoHelper); transform->mRect->GetWidth(&w); transform->mRect->GetHeight(&h); aoHelper->MakeThumbnailAspectScaleUpAnimation( sourceView, b, offsetX, offsetY, w, h, animStartedListener, (IActivityOptions**)&opts); } AutoPtr<Runnable> launchRunnable = new LaunchRunnable(task, opts, lockToTask, this); Boolean res; // Launch the app right away if there is no task view, otherwise, animate the icon out first if (tv == NULL) { Post(launchRunnable, &res); } else { AutoPtr<TaskGrouping> tg = (TaskGrouping*)(task->mGroup).Get(); if (!tg->IsFrontMostTask(task)) { // For affiliated tasks that are behind other tasks, we must animate the front cards // out of view before starting the task transition stackView->StartLaunchTaskAnimation(tv, launchRunnable, lockToTask); } else { // Otherwise, we can start the task transition immediately stackView->StartLaunchTaskAnimation(tv, NULL, lockToTask); PostDelayed(launchRunnable, 17, &res); } } return NOERROR; } // @Override ECode RecentsView::OnTaskViewAppInfoClicked( /* [in] */ ITask* _t) { Task* t = (Task*)_t; // Create a new task stack with the application info details activity AutoPtr<IIntent> baseIntent = t->mKey->mBaseIntent; AutoPtr<IUriHelper> uriHelper; CUriHelper::AcquireSingleton((IUriHelper**)&uriHelper); AutoPtr<IComponentName> componet; baseIntent->GetComponent((IComponentName**)&componet); String pkgName; componet->GetPackageName(&pkgName); AutoPtr<IUri> uri; uriHelper->FromParts(String("package"), pkgName, String(NULL), (IUri**)&uri); AutoPtr<IIntent> intent; CIntent::New(ISettings::ACTION_APPLICATION_DETAILS_SETTINGS, uri, (IIntent**)&intent); AutoPtr<IContext> context; GetContext((IContext**)&context); AutoPtr<IPackageManager> pm; context->GetPackageManager((IPackageManager**)&pm); componet = NULL; intent->ResolveActivity(pm, (IComponentName**)&componet); intent->SetComponent(componet); AutoPtr<ITaskStackBuilderHelper> tsbHelper; CTaskStackBuilderHelper::AcquireSingleton((ITaskStackBuilderHelper**)&tsbHelper); AutoPtr<ITaskStackBuilder> taskStackBuilder; tsbHelper->Create(context, (ITaskStackBuilder**)&taskStackBuilder); taskStackBuilder->AddNextIntentWithParentStack(intent); AutoPtr<IUserHandle> userHandle; CUserHandle::New(t->mKey->mUserId, (IUserHandle**)&userHandle); taskStackBuilder->StartActivities(NULL, userHandle); return NOERROR; } // @Override ECode RecentsView::OnTaskViewDismissed( /* [in] */ ITask* taskObj) { Task* t = (Task*)taskObj; // Remove any stored data from the loader. We currently don't bother notifying the views // that the data has been unloaded because at the point we call onTaskViewDismissed(), the views // either don't need to be updated, or have already been removed. AutoPtr<RecentsTaskLoader> loader = RecentsTaskLoader::GetInstance(); loader->DeleteTaskData(t, FALSE); // Remove the old task from activity manager AutoPtr<SystemServicesProxy> ssp; loader->GetSystemServicesProxy((SystemServicesProxy**)&ssp); ssp->RemoveTask(t->mKey->mId, Utilities::IsDocument(t->mKey->mBaseIntent)); return NOERROR; } // @Override ECode RecentsView::OnAllTaskViewsDismissed() { return mCb->OnAllTaskViewsDismissed(); } // @Override ECode RecentsView::OnTaskStackFilterTriggered() { // Hide the search bar if (mSearchBar != NULL) { AutoPtr<IViewPropertyAnimator> animate; mSearchBar->Animate((IViewPropertyAnimator**)&animate); animate->Alpha(0.0f); animate->SetStartDelay(0); animate->SetInterpolator(ITimeInterpolator::Probe(mConfig->mFastOutSlowInInterpolator)); animate->SetDuration(mConfig->mFilteringCurrentViewsAnimDuration); animate->WithLayer(); animate->Start(); } return NOERROR; } // @Override ECode RecentsView::OnTaskStackUnfilterTriggered() { // Show the search bar if (mSearchBar != NULL) { AutoPtr<IViewPropertyAnimator> animate; mSearchBar->Animate((IViewPropertyAnimator**)&animate); animate->Alpha(1.0f); animate->SetStartDelay(0); animate->SetInterpolator(ITimeInterpolator::Probe(mConfig->mFastOutSlowInInterpolator)); animate->SetDuration(mConfig->mFilteringNewViewsAnimDuration); animate->WithLayer(); animate->Start(); } return NOERROR; } /**** RecentsPackageMonitor.PackageCallbacks Implementation ****/ // @Override ECode RecentsView::OnComponentRemoved( /* [in] */ IHashSet* cns) { // Propagate this event down to each task stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); stackView->OnComponentRemoved(cns); } } return NOERROR; } } // namespace Views } // namespace Recents } // namespace SystemUI } // namespace Droid } // namespace Elastos
34.555957
111
0.632296
0cda9a014ed43d1a287d252950ea53b778b22bfa
5,656
cpp
C++
src/libv/ui/component/stretch.cpp
cpplibv/libv
293e382f459f0acbc540de8ef6283782b38d2e63
[ "Zlib" ]
2
2018-04-11T03:07:03.000Z
2019-03-29T15:24:12.000Z
src/libv/ui/component/stretch.cpp
cpplibv/libv
293e382f459f0acbc540de8ef6283782b38d2e63
[ "Zlib" ]
null
null
null
src/libv/ui/component/stretch.cpp
cpplibv/libv
293e382f459f0acbc540de8ef6283782b38d2e63
[ "Zlib" ]
1
2021-06-13T06:39:06.000Z
2021-06-13T06:39:06.000Z
// Project: libv.ui, File: src/libv/ui/component/stretch.cpp, Author: Császár Mátyás [Vader] // hpp #include <libv/ui/component/stretch.hpp> // pro #include <libv/ui/context/context_layout.hpp> #include <libv/ui/context/context_render.hpp> #include <libv/ui/context/context_style.hpp> #include <libv/ui/context/context_ui.hpp> #include <libv/ui/core_component.hpp> #include <libv/ui/property_access_context.hpp> #include <libv/ui/shader/shader_image.hpp> #include <libv/ui/style.hpp> #include <libv/ui/texture_2D.hpp> namespace libv { namespace ui { // ------------------------------------------------------------------------------------------------- struct CoreStretch : CoreComponent { friend class Stretch; [[nodiscard]] inline auto handler() { return Stretch{this}; } private: template <typename T> static void access_properties(T& ctx); struct Properties { PropertyR<Color> bg_color; PropertyL<Texture2D_view> bg_image; PropertyR<ShaderImage_view> bg_shader; } property; public: using CoreComponent::CoreComponent; private: virtual void doStyle(ContextStyle& ctx) override; virtual libv::vec3f doLayout1(const ContextLayout1& environment) override; virtual void doRender(Renderer& r) override; }; // ------------------------------------------------------------------------------------------------- template <typename T> void CoreStretch::access_properties(T& ctx) { ctx.property( [](auto& c) -> auto& { return c.property.bg_color; }, Color(1, 1, 1, 1), pgr::appearance, pnm::bg_color, "Background color" ); ctx.property( [](auto& c) -> auto& { return c.property.bg_image; }, [](auto& u) { return u.fallbackTexture2D(); }, pgr::appearance, pnm::bg_image, "Background image" ); ctx.property( [](auto& c) -> auto& { return c.property.bg_shader; }, [](auto& u) { return u.shaderImage(); }, pgr::appearance, pnm::bg_shader, "Background shader" ); } // ------------------------------------------------------------------------------------------------- void CoreStretch::doStyle(ContextStyle& ctx) { PropertyAccessContext<CoreStretch> setter{*this, ctx.component, ctx.style, context()}; access_properties(setter); CoreComponent::access_properties(setter); } libv::vec3f CoreStretch::doLayout1(const ContextLayout1& environment) { (void) environment; const auto dynamic_size_image = property.bg_image()->size().cast<float>() + padding_size(); return {dynamic_size_image, 0.f}; } void CoreStretch::doRender(Renderer& r) { // y3 12--13--14--15 // | / | / | / | // y2 8---9---10--11 // | / | / | / | // y1 4---5---6---7 // | / | / | / | // y0 0---1---2---3 // // x0 x1 x2 x3 const auto border_pos = min(cast<float>(property.bg_image()->size()), layout_size2()) * 0.5f; const auto border_tex = min(layout_size2() / max(cast<float>(property.bg_image()->size()), 1.0f) * 0.5f, 0.5f); const auto p0 = libv::vec2f{0.0f, 0.0f}; const auto p1 = border_pos; const auto p2 = layout_size2() - border_pos; const auto p3 = layout_size2(); const auto t0 = libv::vec2f{0.0f, 0.0f}; const auto t1 = border_tex; const auto t2 = 1.0f - border_tex; const auto t3 = libv::vec2f{1.0f, 1.0f}; const auto color = property.bg_color(); r.begin_triangles(); r.vertex({p0.x, p0.y, 0}, {t0.x, t0.y}, color); r.vertex({p1.x, p0.y, 0}, {t1.x, t0.y}, color); r.vertex({p2.x, p0.y, 0}, {t2.x, t0.y}, color); r.vertex({p3.x, p0.y, 0}, {t3.x, t0.y}, color); r.vertex({p0.x, p1.y, 0}, {t0.x, t1.y}, color); r.vertex({p1.x, p1.y, 0}, {t1.x, t1.y}, color); r.vertex({p2.x, p1.y, 0}, {t2.x, t1.y}, color); r.vertex({p3.x, p1.y, 0}, {t3.x, t1.y}, color); r.vertex({p0.x, p2.y, 0}, {t0.x, t2.y}, color); r.vertex({p1.x, p2.y, 0}, {t1.x, t2.y}, color); r.vertex({p2.x, p2.y, 0}, {t2.x, t2.y}, color); r.vertex({p3.x, p2.y, 0}, {t3.x, t2.y}, color); r.vertex({p0.x, p3.y, 0}, {t0.x, t3.y}, color); r.vertex({p1.x, p3.y, 0}, {t1.x, t3.y}, color); r.vertex({p2.x, p3.y, 0}, {t2.x, t3.y}, color); r.vertex({p3.x, p3.y, 0}, {t3.x, t3.y}, color); r.index_strip({4, 0, 5, 1, 6, 2, 7, 3}); r.index_strip({3, 8}); // jump r.index_strip({8, 4, 9, 5, 10, 6, 11, 7}); r.index_strip({7, 12}); // jump r.index_strip({12, 8, 13, 9, 14, 10, 15, 11}); r.end(property.bg_image(), property.bg_shader()); } // ------------------------------------------------------------------------------------------------- Stretch::Stretch(std::string name) : ComponentHandler<CoreStretch, EventHostGeneral<Stretch>>(std::move(name)) { } Stretch::Stretch(GenerateName_t gen, const std::string_view type) : ComponentHandler<CoreStretch, EventHostGeneral<Stretch>>(gen, type) { } Stretch::Stretch(core_ptr core) noexcept : ComponentHandler<CoreStretch, EventHostGeneral<Stretch>>(core) { } // ------------------------------------------------------------------------------------------------- void Stretch::color(Color value) { AccessProperty::manual(self(), self().property.bg_color, value); } const Color& Stretch::color() const noexcept { return self().property.bg_color(); } void Stretch::image(Texture2D_view value) { AccessProperty::manual(self(), self().property.bg_image, std::move(value)); } const Texture2D_view& Stretch::image() const noexcept { return self().property.bg_image(); } void Stretch::shader(ShaderImage_view value) { AccessProperty::manual(self(), self().property.bg_shader, std::move(value)); } const ShaderImage_view& Stretch::shader() const noexcept { return self().property.bg_shader(); } // ------------------------------------------------------------------------------------------------- } // namespace ui } // namespace libv
31.248619
112
0.589993
0cdc4adfc3c3e4b1e3bb1b9f8b4fc7a464efd0c3
4,792
cc
C++
src/telephony/telephony_instance.cc
izaman/tizen-extensions-crosswalk
e1373788f4e4e271e39b0fee66c26210e40dd86f
[ "Apache-2.0", "BSD-3-Clause" ]
10
2015-01-16T16:14:35.000Z
2018-12-25T16:01:43.000Z
src/telephony/telephony_instance.cc
liyingzh/tizen-extensions-crosswalk
5957945effafff02a507c35a4b7b4d5ee6ca14c1
[ "Apache-2.0", "BSD-3-Clause" ]
35
2015-01-04T02:11:22.000Z
2015-09-22T08:43:45.000Z
src/telephony/telephony_instance.cc
liyingzh/tizen-extensions-crosswalk
5957945effafff02a507c35a4b7b4d5ee6ca14c1
[ "Apache-2.0", "BSD-3-Clause" ]
14
2015-02-03T04:38:19.000Z
2022-01-20T10:38:01.000Z
// Copyright (c) 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "telephony/telephony_instance.h" #include <string> #include "common/picojson.h" #include "telephony/telephony_backend_ofono.h" #include "tizen/tizen.h" namespace { const char kCmdGetServices[] = "getServices"; const char kCmdSetDefaultService[] = "setDefaultService"; const char kCmdSetServiceEnabled[] = "setServiceEnabled"; const char kCmdGetCalls[] = "getCalls"; const char kCmdDial[] = "dial"; const char kCmdAccept[] = "accept"; const char kCmdDisconnect[] = "disconnect"; const char kCmdHold[] = "hold"; const char kCmdResume[] = "resume"; const char kCmdDeflect[] = "deflect"; const char kCmdTransfer[] = "transfer"; const char kCmdSplit[] = "split"; const char kCmdSendTones[] = "sendTones"; const char kCmdStartTone[] = "startTone"; const char kCmdStopTone[] = "stopTone"; const char kCmdGetEmergencyNumbers[] = "getEmergencyNumbers"; const char kCmdEmergencyDial[] = "emergencyDial"; const char kCmdCreateConference[] = "createConference"; const char kCmdGetParticipants[] = "getParticipants"; const char kCmdEnableNotifications[] = "enableNotifications"; const char kCmdDisableNotifications[] = "disableNotifications"; } // namespace TelephonyInstance::TelephonyInstance() : backend_(new TelephonyBackend(this)) { } TelephonyInstance::~TelephonyInstance() { delete backend_; } void TelephonyInstance::HandleMessage(const char* msg) { picojson::value v; std::string err; picojson::parse(v, msg, msg + strlen(msg), &err); if (!err.empty()) { std::cerr << "Error: ignoring empty message.\n"; return; } if (!backend_) { SendErrorReply(v, NO_MODIFICATION_ALLOWED_ERR, "Telephony backend not initialized."); return; } std::string cmd = v.get("cmd").to_str(); if (cmd == kCmdGetServices) { backend_->GetServices(v); } else if (cmd == kCmdSetDefaultService) { backend_->SetDefaultService(v); } else if (cmd == kCmdSetServiceEnabled) { backend_->SetServiceEnabled(v); } else if (cmd == kCmdEnableNotifications) { backend_->EnableSignalHandlers(); } else if (cmd == kCmdDisableNotifications) { backend_->DisableSignalHandlers(); } else if (cmd == kCmdGetCalls) { backend_->GetCalls(v); } else if (cmd == kCmdDial) { backend_->DialCall(v); } else if (cmd == kCmdAccept) { backend_->AcceptCall(v); } else if (cmd == kCmdDisconnect) { backend_->DisconnectCall(v); } else if (cmd == kCmdHold) { backend_->HoldCall(v); } else if (cmd == kCmdResume) { backend_->ResumeCall(v); } else if (cmd == kCmdDeflect) { backend_->DeflectCall(v); } else if (cmd == kCmdTransfer) { backend_->TransferCall(v); } else if (cmd == kCmdSendTones) { backend_->SendTones(v); } else if (cmd == kCmdStartTone) { backend_->StartTone(v); } else if (cmd == kCmdStopTone) { backend_->StopTone(v); } else if (cmd == kCmdGetEmergencyNumbers) { backend_->GetEmergencyNumbers(v); } else if (cmd == kCmdEmergencyDial) { backend_->EmergencyDial(v); } else if (cmd == kCmdCreateConference) { backend_->CreateConference(v); } else if (cmd == kCmdGetParticipants) { backend_->GetConferenceParticipants(v); } else if (cmd == kCmdSplit) { backend_->SplitCall(v); } else { std::cout << "Ignoring unknown command: " << cmd; } } void TelephonyInstance::HandleSyncMessage(const char* message) { } void TelephonyInstance::SendErrorReply(const picojson::value& msg, const int error_code, const char* error_msg) { picojson::value::object reply; reply["promiseId"] = msg.get("promiseId"); reply["cmd"] = msg.get("cmd"); reply["isError"] = picojson::value(true); reply["errorCode"] = picojson::value(static_cast<double>(error_code)); reply["errorMessage"] = error_msg ? picojson::value(error_msg) : msg.get("cmd"); picojson::value v(reply); PostMessage(v.serialize().c_str()); } void TelephonyInstance::SendSuccessReply(const picojson::value& msg, const picojson::value& value) { picojson::value::object reply; reply["promiseId"] = msg.get("promiseId"); reply["cmd"] = msg.get("cmd"); reply["isError"] = picojson::value(false); reply["returnValue"] = value; picojson::value v(reply); PostMessage(v.serialize().c_str()); } void TelephonyInstance::SendSuccessReply(const picojson::value& msg) { picojson::value::object reply; reply["promiseId"] = msg.get("promiseId"); reply["cmd"] = msg.get("cmd"); reply["isError"] = picojson::value(false); picojson::value v(reply); PostMessage(v.serialize().c_str()); } void TelephonyInstance::SendNotification(const picojson::value& msg) { PostMessage(msg.serialize().c_str()); }
32.378378
79
0.692613
0cdf589e598c31402e68e86595e88ef22d2c8193
9,280
cpp
C++
SwapChain/Driver/OpenGL/src/Win32/SwapChain.cpp
Gpinchon/OCRA
341bb07facc616f1f8a27350054d1e86f022d7c6
[ "Apache-2.0" ]
null
null
null
SwapChain/Driver/OpenGL/src/Win32/SwapChain.cpp
Gpinchon/OCRA
341bb07facc616f1f8a27350054d1e86f022d7c6
[ "Apache-2.0" ]
null
null
null
SwapChain/Driver/OpenGL/src/Win32/SwapChain.cpp
Gpinchon/OCRA
341bb07facc616f1f8a27350054d1e86f022d7c6
[ "Apache-2.0" ]
null
null
null
#include <GL/Win32/SwapChain.hpp> #include <GL/Win32/PresentGeometry.hpp> #include <GL/Win32/PresentPixels.hpp> #include <GL/Win32/PresentShader.hpp> #include <GL/Win32/PresentTexture.hpp> #include <GL/Surface.hpp> #include <GL/Win32/Error.hpp> #include <GL/Win32/OpenGL.hpp> #include <GL/Device.hpp> #include <GL/Image/Format.hpp> #include <GL/Image/Image.hpp> #include <GL/Queue/Queue.hpp> #include <GL/Queue/Semaphore.hpp> #include <GL/Queue/Fence.hpp> #include <GL/Common/BufferOffset.hpp> #include <GL/glew.h> #include <GL/wglew.h> #include <iostream> #include <sstream> namespace OCRA::SwapChain::Win32 { void GLAPIENTRY MessageCallback( GLenum source, GLenum type, GLenum id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { if (type == GL_DEBUG_TYPE_ERROR) { std::stringstream ss{}; ss << "GL CALLBACK : **GL ERROR * *\n" << " type = " << type << "\n" << " severity = " << severity << "\n" << " message = " << message; std::cerr << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } static inline auto CreateImages(const Device::Handle& a_Device, const Info& a_Info) { std::vector<Image::Handle> images; auto win32SwapChain = std::static_pointer_cast<SwapChain::Win32::Impl>(a_Info.oldSwapchain); for (auto i = 0u; i < a_Info.imageCount; ++i) { Image::Handle image; if (win32SwapChain != nullptr) { const auto& imageInfo = win32SwapChain->images.at(i)->info; const bool canRecycle = imageInfo.extent.width == a_Info.imageExtent.width && imageInfo.extent.height == a_Info.imageExtent.height && imageInfo.arrayLayers == a_Info.imageArrayLayers && imageInfo.format == a_Info.imageFormat; if (canRecycle) image = win32SwapChain->images.at(i); } if (image == nullptr) { Image::Info imageInfo{}; imageInfo.type = Image::Type::Image2D; imageInfo.extent.width = a_Info.imageExtent.width; imageInfo.extent.height = a_Info.imageExtent.height; imageInfo.mipLevels = 1; imageInfo.arrayLayers = a_Info.imageArrayLayers; imageInfo.format = a_Info.imageFormat; image = Image::Create(a_Device, imageInfo); } images.push_back(image); } return images; } Impl::Impl(const Device::Handle& a_Device, const Info& a_Info) : SwapChain::Impl(a_Device, a_Info) , images(CreateImages(a_Device, a_Info)) { const auto pixelSize = GetPixelSize(info.imageFormat); if (info.oldSwapchain != nullptr && !info.oldSwapchain->retired) { auto win32SwapChain = std::static_pointer_cast<SwapChain::Win32::Impl>(info.oldSwapchain); win32SwapChain->workerThread.Wait(); hdc = win32SwapChain->hdc; hglrc = win32SwapChain->hglrc; presentShader.swap(win32SwapChain->presentShader); info.oldSwapchain->Retire(); info.oldSwapchain.reset(); } else { hdc = GetDC(HWND(a_Info.surface->nativeWindow)); OpenGL::Win32::Initialize(); const int attribIList[] = { WGL_DRAW_TO_WINDOW_ARB, true, WGL_SUPPORT_OPENGL_ARB, true, WGL_DOUBLE_BUFFER_ARB, true, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_COLORSPACE_EXT, WGL_COLORSPACE_SRGB_EXT, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, pixelSize, 0 }; int32_t pixelFormat = 0; uint32_t pixelFormatNbr = 0; WIN32_CHECK_ERROR(wglChoosePixelFormatARB(HDC(hdc), attribIList, nullptr, 1, &pixelFormat, &pixelFormatNbr)); WIN32_CHECK_ERROR(pixelFormat != 0); WIN32_CHECK_ERROR(pixelFormatNbr != 0); WIN32_CHECK_ERROR(SetPixelFormat(HDC(hdc), pixelFormat, nullptr)); hglrc = OpenGL::Win32::CreateContext(hdc); } workerThread.PushCommand([this, pixelSize] { WIN32_CHECK_ERROR(wglMakeCurrent(HDC(hdc), HGLRC(hglrc))); if (info.presentMode == PresentMode::Immediate) { WIN32_CHECK_ERROR(wglSwapIntervalEXT(0)); } else WIN32_CHECK_ERROR(wglSwapIntervalEXT(1)); #ifdef _DEBUG glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(MessageCallback, 0); #endif _DEBUG if (presentTexture == nullptr) { presentTexture.reset(new PresentTexture(images.front())); presentTexture->Bind(); } if (presentShader == nullptr) { presentShader.reset(new PresentShader); presentShader->Bind(); } if (presentGeometry == nullptr) { presentGeometry.reset(new PresentGeometry); presentGeometry->Bind(); } if (!WGLEW_NV_copy_image && presentPixels == nullptr) { static bool warningPrinted = false; if (!warningPrinted) { std::cerr << "SwapChain : WGL_NV_copy_image unavailable, using slower path\n"; warningPrinted = true; } const auto transferBufferSize = info.imageExtent.width * info.imageExtent.height * pixelSize / 8; presentPixels.reset(new PresentPixels(transferBufferSize)); presentPixels->Bind(); } glViewport(0, 0, presentTexture->extent.width, presentTexture->extent.height); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glActiveTexture(GL_TEXTURE0); glBindSampler(0, presentTexture->samplerHandle); }, false); } Impl::~Impl() { retired = true; workerThread.PushCommand([this] { presentTexture.reset(); presentShader.reset(); presentGeometry.reset(); presentPixels.reset(); wglMakeCurrent(nullptr, nullptr); }, true); if (hdc != nullptr) ReleaseDC(HWND(info.surface->nativeWindow), HDC(hdc)); if (hglrc != nullptr) wglDeleteContext(HGLRC(hglrc)); } void Impl::Retire() { SwapChain::Impl::Retire(); workerThread.PushCommand([this] { presentShader.reset(); presentTexture.reset(); presentGeometry.reset(); presentPixels.reset(); wglMakeCurrent(nullptr, nullptr); }, true); images.clear(); hdc = nullptr; hglrc = nullptr; } void Impl::Present(const Queue::Handle& a_Queue) { assert(!retired); if (WGLEW_NV_copy_image) { PresentNV(a_Queue); } else { PresentGL(a_Queue); } } void Impl::PresentNV(const Queue::Handle& a_Queue) { const auto& image = images.at(backBufferIndex); const auto extent = image->info.extent; a_Queue->PushCommand([this, extent] { const auto& image = images.at(backBufferIndex); auto sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); glClientWaitSync(sync, 0, 1000); glDeleteSync(sync); WIN32_CHECK_ERROR(wglCopyImageSubDataNV( nullptr, image->handle, image->target, //use current context 0, 0, 0, 0, HGLRC(hglrc), presentTexture->handle, presentTexture->target, 0, 0, 0, 0, extent.width, extent.height, 1)); }, true); workerThread.PushCommand([this, extent] { presentGeometry->Draw(); WIN32_CHECK_ERROR(SwapBuffers(HDC(hdc))); }, info.presentMode != PresentMode::Immediate); backBufferIndex = (backBufferIndex + 1) % info.imageCount; } void Impl::PresentGL(const Queue::Handle& a_Queue) { const auto& image = images.at(backBufferIndex); const auto extent = image->info.extent; a_Queue->PushCommand([this, extent] { const auto& image = images.at(backBufferIndex); glBindTexture(image->target, image->handle); glGetTexImage( image->target, 0, image->dataFormat, image->dataType, presentPixels->GetPtr()); glBindTexture(image->target, 0); }, true); workerThread.PushCommand([this, extent] { presentPixels->Flush(); glTexSubImage2D( presentTexture->target, 0, 0, 0, extent.width, extent.height, presentTexture->dataFormat, presentTexture->dataType, BUFFER_OFFSET(presentPixels->offset)); presentGeometry->Draw(); WIN32_CHECK_ERROR(SwapBuffers(HDC(hdc))); }, info.presentMode != PresentMode::Immediate); backBufferIndex = (backBufferIndex + 1) % info.imageCount; } //TODO: implement a timeout Image::Handle Impl::AcquireNextImage( const std::chrono::nanoseconds& a_Timeout, const Queue::Semaphore::Handle& a_Semaphore, const Queue::Fence::Handle& a_Fence) { workerThread.Wait(); //We do not need to synchronize with the GPU for real here if (a_Semaphore != nullptr) { if (a_Semaphore->type == Queue::Semaphore::Type::Binary) std::static_pointer_cast<Queue::Semaphore::Binary>(a_Semaphore)->SignalNoSync(); else throw std::runtime_error("Cannot wait on Timeline Semaphores when presenting"); } if (a_Fence != nullptr) a_Fence->SignalNoSync(); return images.at(backBufferIndex); } }
35.968992
117
0.628017
0ce1fd51fe99bd2aef16c916c6ba9c7326bd2b23
521
cpp
C++
codeforces/1475A.cpp
LordRonz/cp-solutions
d95eabbdbf6a04fba912f4e8be203b180af7f46d
[ "WTFPL" ]
2
2021-04-19T06:20:11.000Z
2021-05-04T14:30:00.000Z
codeforces/1475A.cpp
LordRonz/cp-solutions
d95eabbdbf6a04fba912f4e8be203b180af7f46d
[ "WTFPL" ]
2
2022-03-01T09:28:46.000Z
2022-03-02T09:52:33.000Z
codeforces/1475A.cpp
LordRonz/cp-solutions
d95eabbdbf6a04fba912f4e8be203b180af7f46d
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define MAX(a,b,c) max(a,max(b,c)) #define MIN(a,b,c) min(a,min(b,c)) #define MP make_pair #define FOR(x, a, b) for(int x = a; x < b; ++x) typedef pair<int, int> pii; //0xACCE97ED; int main() { long long unsigned n, t; scanf("%lld", &t); while(t--) { scanf("%lld", &n); if(n & 1) { puts("YES"); continue; } long long unsigned div = 3; while(n > 1) { if(n & 1) { puts("YES"); break; } n >>= 1; } if(n == 1) puts("NO"); } return 0; }
16.806452
47
0.527831
0ce83d17e36b56392ae66bdda1e9e462aede0061
865
cpp
C++
PAT/Advanced Level/Simulation_Math/1148 Werewolf.cpp
MuZi-lh/AlgorithmExecise
88411f52ad65ef002ed8bcbcffc402f64985958f
[ "MulanPSL-1.0" ]
null
null
null
PAT/Advanced Level/Simulation_Math/1148 Werewolf.cpp
MuZi-lh/AlgorithmExecise
88411f52ad65ef002ed8bcbcffc402f64985958f
[ "MulanPSL-1.0" ]
null
null
null
PAT/Advanced Level/Simulation_Math/1148 Werewolf.cpp
MuZi-lh/AlgorithmExecise
88411f52ad65ef002ed8bcbcffc402f64985958f
[ "MulanPSL-1.0" ]
null
null
null
#include<iostream> #include<vector> using namespace std; int N; vector<int> p(100); bool tellingTruth(int a, int b, int t) { return (abs(p[t]) != a && abs(p[t]) != b && p[t] > 0) || (p[t] == -a || p[t] == -b); } // a, b are wolf, // assume a, b don't point at themselves // a tell a truth, b tell a lie bool legal(int a, int b) { int cnt = 0; if (tellingTruth(a, b, a) && !tellingTruth(a, b, b)) { for (int k = 1;k <= N;k++) { if (k != b && !tellingTruth(a, b, k)) { cnt++; } } if (cnt == 1) return true; } return false; } // positive for human and negtive for wolf int main() { cin >> N; for (int i = 1; i <= N; i++) { cin >> p[i]; } for (int i = 1; i <= N - 1; i++) { for (int j = i + 1;j <= N;j++) { if (legal(i, j) || legal(j, i)) { cout << i << ' ' << j; return 0; } } } cout << "No Solution"; return 0; }
18.804348
85
0.491329
0ce92d47507b7639fa18ea1fb22e4d36ef08339a
9,890
cpp
C++
Source/Game/GameState/IntroState/IntroState.cpp
Crazykingjammy/bkbotz
6cdaa4164ff02e40f2909982f6dacad161c7d6cf
[ "Unlicense" ]
null
null
null
Source/Game/GameState/IntroState/IntroState.cpp
Crazykingjammy/bkbotz
6cdaa4164ff02e40f2909982f6dacad161c7d6cf
[ "Unlicense" ]
null
null
null
Source/Game/GameState/IntroState/IntroState.cpp
Crazykingjammy/bkbotz
6cdaa4164ff02e40f2909982f6dacad161c7d6cf
[ "Unlicense" ]
null
null
null
#include "../GameState.h" CIntroGameState* CIntroGameState::pInstance = 0; void CIntroGameState::Initalize(Game* game) { //Get the Pointer to the game. pGame = game; ////////////////////////////////////////////////////////////////////////// // Lights Setup ////////////////////////////////////////////////////////////////////////// //Set up Lights here pRenderInterface->Light[0].m_Active = true; pRenderInterface->Light[0].m_MyBody.centerPosition.y = 10.0f; pRenderInterface->Light[0].m_Specular = 0.0f; pRenderInterface->Light[0].m_Diffuse = EXColor(0.6f,0.65f,0.65f,1.0f); pRenderInterface->Light[0].m_Ambient = EXColor(0.1f,0.1f,0.1f,1.0f); pRenderInterface->Light[0].m_Attenuation2 = 0.0000002f; ////////////////////////////////////////////////////////////////////////// // Lights Setup ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Camera Setup ////////////////////////////////////////////////////////////////////////// Camera0 = new CFreeCamera; Camera1 = new CFreeCamera; Camera0->m_LinearSpeed = 5.0f; Camera0->m_MyBody.centerPosition.y += 24.035156f; Camera0->m_MyBody.centerPosition.x -= 35.638084f; Camera0->m_MyBody.centerPosition.z -= 26.376434f; Camera1->m_MyBody.centerPosition.z = -10.0f; pRenderInterface->SetActiveCamera(Camera0); //pRenderInterface-> ////////////////////////////////////////////////////////////////////////// // Camera Setup ////////////////////////////////////////////////////////////////////////// m_2DScene.Set2DWorld((float)pGame->Window.WindowWidth,(float)pGame->Window.WindowHeight); m_2DScene.sceneGravity.MakeZero(); ////////////////////////////////////////////////////////////////////////// // Object Setup ////////////////////////////////////////////////////////////////////////// pRenderInterface->SetWorld("Models/MenuWorld.X"); Ship = new CBall; strcpy(Ship->m_ModelName,"Models/MenuShip.X"); Ship->m_MyBody.centerPosition.y += 7.0f; //pRenderInterface->AddObject(Ship); //Ship->m_MyBodyIndex = m_Scene.AddBody(&Ship->m_MyBody); Battle = new CLabel("Textures/MenuIcon_1.bmp"); pRenderInterface->AddLabel(Battle); Battle->m_MyBody.centerPosition.x += (float)(pGame->Window.WindowWidth / 3); Battle->m_MyBody.centerPosition.y += (float) (pGame->Window.WindowHeight / 3); Battle->m_MyBody.radius = 10.0f; Battle->m_MyBody.mass = 1.0f; Battle->m_MyBodyIndex = m_2DScene.AddBody(&Battle->m_MyBody); Credits = new CLabel("Textures/MenuIcon_3.bmp"); pRenderInterface->AddLabel(Credits); Credits->m_MyBody.centerPosition.x += 300.0f; Credits->m_MyBody.centerPosition.y += 450.0f; Credits->m_MyBody.radius = 10.0f; Credits->m_MyBody.mass = 1.0f; Credits->m_MyBodyIndex = m_2DScene.AddBody(&Credits->m_MyBody); Exit = new CLabel("Textures/MenuIcon_4.bmp"); pRenderInterface->AddLabel(Exit); Exit->m_MyBody.centerPosition.x += 600.0f; Exit->m_MyBody.centerPosition.y += 450.0f; Exit->m_MyBody.radius = 10.0f;; Exit->m_MyBody.mass = 1.0f; Exit->m_MyBodyIndex = m_2DScene.AddBody(&Exit->m_MyBody); Soccer = new CLabel("Textures/MenuIcon_2.bmp"); pRenderInterface->AddLabel(Soccer); Soccer->m_MyBody.centerPosition.x += 600.0f; Soccer->m_MyBody.centerPosition.y += 150.0f; Soccer->m_MyBody.radius = 10.0f;; Soccer->m_MyBodyIndex = m_2DScene.AddBody(&Soccer->m_MyBody); Soccer->m_MyBody.mass = 1.0f; Me = new CLabel("Textures/MenuIcon_0.bmp"); pRenderInterface->AddLabel(Me); Me->m_MyBody.isNapping = false; Me->m_MyBody.centerPosition.x += (float)(pGame->Window.WindowWidth/2); Me->m_MyBody.centerPosition.y += (float)(pGame->Window.WindowHeight/2); Me->m_MyBody.mass = 10.0f; Me->m_MyBody.radius = 64.0f;; Me->m_MyBodyIndex = m_2DScene.AddBody(&Me->m_MyBody); //strcpy(Me->m_Text, "B"); GameText = new CLabel("Textures/jamtext.bmp"); pRenderInterface->AddLabel(GameText); GameText->m_MyBody.centerPosition.x = 280.0f; GameText->m_MyBody.centerPosition.y = 30.0f; ////////////////////////////////////////////////////////////////////////// // Object Setup ////////////////////////////////////////////////////////////////////////// //Numbers MeForce = 27000.0f * 4.0f; m_InputFreq = 0.05f; CurrentSelection = 0; //Create the Scene pRenderInterface->CreateScene(); } void CIntroGameState::Update(float timeDelta) { //m_Scene.Simulate(); m_2DScene.Simulate(); Camera0->LookAt(pRenderInterface->m_World); cout << Me->m_MyBody.centerPosition.x << ' ' << Me->m_MyBody.centerPosition.y << ' ' << Me->m_MyBody.centerPosition.z<< endl; //Pull toward the middle. Battle->m_MyBody.gravityForce = CVector3f(400.0f, 300.0f, 0.0f) - Battle->m_MyBody.centerPosition; Battle->m_MyBody.gravityForce.Normalize(); Battle->m_MyBody.gravityForce *= 5.8f; Credits->m_MyBody.gravityForce = CVector3f(400.0f, 300.0f, 0.0f) - Credits->m_MyBody.centerPosition; Credits->m_MyBody.gravityForce.Normalize(); Credits->m_MyBody.gravityForce *= 5.8f; Soccer->m_MyBody.gravityForce = CVector3f(400.0f, 300.0f, 0.0f) - Soccer->m_MyBody.centerPosition; Soccer->m_MyBody.gravityForce.Normalize(); Soccer->m_MyBody.gravityForce *= 5.8f; Exit->m_MyBody.gravityForce = CVector3f(400.0f, 300.0f, 0.0f) - Exit->m_MyBody.centerPosition; Exit->m_MyBody.gravityForce.Normalize(); Exit->m_MyBody.gravityForce *= 5.8f; //Check for controls. if (m_InputTimer.GetElapsedSeconds() >= m_InputFreq) { Controls(); Me->m_Rotation += 0.01f; // Me->m_MyBody.velocityVec.Magnitude(); Me->m_MyBody.Add2Force( (CVector3f((float)(pGame->Window.WindowWidth/2), (float)(pGame->Window.WindowHeight/2), 0.0f) - Me->m_MyBody.centerPosition) * 750.0f ); m_InputTimer.Reset(); } CollisionDetection(); //attach cam to the player. Camera1->m_MyBody.centerPosition = Ship->m_MyBody.centerPosition; //Move camera Camera1->m_MyBody.centerPosition.y += 4.51f; Camera1->m_MyBody.centerPosition.x -= 0.51f; Camera1->m_MyBody.centerPosition.z -= 3.3f; switch(CurrentSelection) { char test[128]; case BATTLE: { sprintf(test, "Battle Game"); strcpy(GameText->m_Text,test); if (pInput->Controller1JoyPress(0)) { ChangeState(pGame,CBattleGameState::GetInstance()); return; } break; } case SOCCER: { sprintf(test, "Soccer Game"); strcpy(GameText->m_Text,test); if (pInput->Controller1JoyPress(0)) { ChangeState(pGame, CSoccerGameState::GetInstance()); return; } break; } case EXIT: { sprintf(test, "Exit Game"); strcpy(GameText->m_Text,test); if (pInput->Controller1JoyPress(0)) { //Only place this should be getting called :_D PostQuitMessage(0); } break; } case CREDITS: { sprintf(test, "Game Credits"); strcpy(GameText->m_Text,test); if (pInput->Controller1JoyPress(0)) { ChangeState(pGame, CJukeBoxState::GetInstance()); return; } break; } } } void CIntroGameState::Shutdown() { //Destroy teh modles and reset the scene. pRenderInterface->DestroyScene(); m_Scene.ClearScene(); m_2DScene.ClearScene(); delete Camera0; delete Camera1; delete Ship; delete Exit; delete Soccer; delete Battle; delete Credits; //Clean Me Up. if(pInstance) delete pInstance; pInstance = 0; } void CIntroGameState::Controls() { //Get input States. pInput->SetAllStates(); if (pInput->Controller1JoyPress(1)) { Me->m_MyBody.velocityVec.MakeZero(); } // timer >= inpout time // do this if(GetAsyncKeyState('W')) pRenderInterface->m_ActiveCamera->MoveUp(); if(GetAsyncKeyState('S')) pRenderInterface->m_ActiveCamera->MoveDown(); if(GetAsyncKeyState('A')) pRenderInterface->m_ActiveCamera->MoveLeft(); if(GetAsyncKeyState('D')) pRenderInterface->m_ActiveCamera->MoveRight(); if(GetAsyncKeyState('C')) pRenderInterface->m_ActiveCamera->MoveFoward(); if(GetAsyncKeyState('V')) pRenderInterface->m_ActiveCamera->MoveBackward(); if(GetAsyncKeyState('F')) pRenderInterface->m_ActiveCamera->LookLeft(); if(GetAsyncKeyState('H')) pRenderInterface->m_ActiveCamera->LookRight(); if(GetAsyncKeyState('T')) pRenderInterface->m_ActiveCamera->LookUp(); if(GetAsyncKeyState('G')) pRenderInterface->m_ActiveCamera->LookDown(); if(pInput->Controller1JoyY() < -200) { Me->m_MyBody.Add2Force( CVector3f(0.0f,-1.0f,0.0f) * (MeForce ) ); } if(pInput->Controller1JoyY() > 200) { Me->m_MyBody.Add2Force( CVector3f(0.0f,1.0f,0.0f) * MeForce ); } if(pInput->Controller1JoyX() < -200) { Me->m_MyBody.Add2Force( CVector3f(-1.0f,0.0f,0.0f) * MeForce ); } if(pInput->Controller1JoyX() > 200) { Me->m_MyBody.Add2Force( CVector3f(1.0f,0.0f,0.0f) * MeForce ); } if(GetAsyncKeyState('P')) pRenderInterface->SetActiveCamera(Camera1); if(GetAsyncKeyState('L')) pRenderInterface->SetActiveCamera(Camera0); } void CIntroGameState::CollisionDetection() { if(m_2DScene.HaveTheTwoBodiesCollided(Battle->m_MyBodyIndex,Me->m_MyBodyIndex)) { CurrentSelection = BATTLE; Camera0->m_MyBody.centerPosition.y = 24.035156f; Camera0->m_MyBody.centerPosition.x = -35.638084f; Camera0->m_MyBody.centerPosition.z = -26.376434f; } if(m_2DScene.HaveTheTwoBodiesCollided(Soccer->m_MyBodyIndex,Me->m_MyBodyIndex)) { CurrentSelection = SOCCER; } if(m_2DScene.HaveTheTwoBodiesCollided(Exit->m_MyBodyIndex,Me->m_MyBodyIndex)) { CurrentSelection = EXIT; Camera0->m_MyBody.centerPosition.y = 23.254128f; Camera0->m_MyBody.centerPosition.x = -58.199429f; Camera0->m_MyBody.centerPosition.z = 19.165016f; } if(m_2DScene.HaveTheTwoBodiesCollided(Credits->m_MyBodyIndex,Me->m_MyBodyIndex)) { CurrentSelection = CREDITS; } } CIntroGameState* CIntroGameState::GetInstance() { //If there is no instance if(pInstance == 0) pInstance = new CIntroGameState; //We Create One return pInstance; //Return the Instance. }
25.101523
163
0.649848
0ceb7006ab85f69b90b7333e5938e9e2b3c84aab
126
cpp
C++
ZF/ZFUIKit/zfsrc/ZFUIKit/protocol/ZFProtocolZFUIView.cpp
ZFFrameworkDist/ZFFramework
6b498e7b95ee6d6aaa28d8369eef8c2ff94daaf7
[ "MIT" ]
57
2016-06-12T11:05:55.000Z
2021-05-22T13:12:17.000Z
ZF/ZFUIKit/zfsrc/ZFUIKit/protocol/ZFProtocolZFUIView.cpp
ZFFrameworkDist/ZFFramework
6b498e7b95ee6d6aaa28d8369eef8c2ff94daaf7
[ "MIT" ]
null
null
null
ZF/ZFUIKit/zfsrc/ZFUIKit/protocol/ZFProtocolZFUIView.cpp
ZFFrameworkDist/ZFFramework
6b498e7b95ee6d6aaa28d8369eef8c2ff94daaf7
[ "MIT" ]
20
2016-05-26T04:47:37.000Z
2020-12-13T01:39:39.000Z
#include "ZFProtocolZFUIView.h" ZF_NAMESPACE_GLOBAL_BEGIN ZFPROTOCOL_INTERFACE_REGISTER(ZFUIView) ZF_NAMESPACE_GLOBAL_END
14
39
0.880952
0ced71d029ec7f52b67c86ddfcffcb90d56d756d
9,437
cpp
C++
C++/vbHmmModel_GaussDiffusion.cpp
okamoto-kenji/varBayes-HMM
77afe3c336c9e1ebeb115ca4f0b2bc25060556bd
[ "MIT" ]
7
2016-03-31T06:59:00.000Z
2019-11-01T06:35:57.000Z
C++/vbHmmModel_GaussDiffusion.cpp
okamoto-kenji/varBayes-HMM
77afe3c336c9e1ebeb115ca4f0b2bc25060556bd
[ "MIT" ]
null
null
null
C++/vbHmmModel_GaussDiffusion.cpp
okamoto-kenji/varBayes-HMM
77afe3c336c9e1ebeb115ca4f0b2bc25060556bd
[ "MIT" ]
null
null
null
/* * vbHmmModel_GaussDiffusion.c * Model-specific functions for VB-HMM-GAUSS-DIFFUSION. * * Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN * Copyright 2011-2018 * Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan. * All rights reserved. * * Ver. 1.0.0 * Last modified on 2018.11.26 */ #include <iostream> #include <cstdlib> #include <fstream> #include <string> #include "vbHmm_GaussDiffusion.h" ////////// conditions vbHmmCond_GaussDiff::vbHmmCond_GaussDiff() : vbHmmCond() { } vbHmmCond_GaussDiff::vbHmmCond_GaussDiff(const vbHmmCond_GaussDiff &other) : vbHmmCond( other ) { // do not copy } vbHmmCond_GaussDiff::~vbHmmCond_GaussDiff() { } ////////// model vbHmmModel_GaussDiff::vbHmmModel_GaussDiff() : vbHmmModel() { avgDlt = NULL; avgLnDlt = NULL; uAArr = NULL; uBArr = NULL; aDlt = NULL; bDlt = NULL; NiR = NULL; RiR = NULL; } vbHmmModel_GaussDiff::vbHmmModel_GaussDiff(const vbHmmModel_GaussDiff &other) : vbHmmModel(other) { // do not copy avgDlt = NULL; avgLnDlt = NULL; uAArr = NULL; uBArr = NULL; aDlt = NULL; bDlt = NULL; NiR = NULL; RiR = NULL; } vbHmmModel_GaussDiff::~vbHmmModel_GaussDiff(){ delete avgDlt; delete avgLnDlt; delete uAArr; delete uBArr; delete aDlt; delete bDlt; delete NiR; delete RiR; } vbHmmModel *vbHmmModel_GaussDiff::newInstance(){ return new vbHmmModel_GaussDiff(); } void vbHmmModel_GaussDiff::setSNo( int _sNo ){ vbHmmModel::setSNo( _sNo ); avgDlt = new Vec1D( sNo ); avgLnDlt = new Vec1D( sNo ); uAArr = new Vec1D( sNo ); uBArr = new Vec1D( sNo ); aDlt = new Vec1D( sNo ); bDlt = new Vec1D( sNo ); NiR = new Vec1D( sNo ); RiR = new Vec1D( sNo ); } void vbHmmModel_GaussDiff::initialize_modelParams( vbHmmCond *c, vbHmmData *d ){ // hyper parameter for p( delta(k) ) int i; for( i = 0 ; i < sNo ; i++ ){ uAArr->p[i] = 1.0; uBArr->p[i] = 0.0005; } } double vbHmmModel_GaussDiff::pTilde_xn_zn( vbHmmTrace *_t, int n, int i ){ double val; vbHmmTrace_GaussDiff *t = (vbHmmTrace_GaussDiff*)_t; val = avgLnDlt->p[i] - log(2.0); val -= log( t->xn->p[n] ) + avgDlt->p[i] * pow( t->xn->p[n], 2.0) / 4.0; return exp(val); } void vbHmmModel_GaussDiff::calcStatsVars( vbHmmData *d ){ int i, j, r, n; double *NiRp = NiR->p, *RiRp = RiR->p, *NiiRp = NiiR->p, **NijRp = NijR->p, *z1iRp = z1iR->p; double **gmMat, ***xiMat; vbHmmTrace_GaussDiff *t; for( i = 0 ; i < sNo ; i++ ){ NiRp[i] = 1e-10; RiRp[i] = 1e-10; NiiRp[i] = 1e-10; for( j = 0 ; j < sNo ; j++ ){ NijRp[i][j] = 1e-10; } // j z1iRp[i] = 1e-10; } // i for( r = 0 ; r < R ; r++ ){ t = (vbHmmTrace_GaussDiff*)d->traces[r]; gmMat = ivs[r]->gmMat->p; xiMat = ivs[r]->xiMat->p; for( i = 0 ; i < sNo ; i++ ){ z1iRp[i] += gmMat[0][i]; for( n = 0 ; n < t->N ; n++ ){ NiRp[i] += gmMat[n][i]; RiRp[i] += gmMat[n][i] * pow( t->xn->p[n], 2.0 ); for( j = 0 ; j < sNo ; j++ ){ NiiRp[i] += xiMat[n][i][j]; NijRp[i][j] += xiMat[n][i][j]; } // j } // n } // i } // r } int vbHmmModel_GaussDiff::maximization_modelVars( int s ){ aDlt->p[s] = uAArr->p[s] + NiR->p[s]; bDlt->p[s] = uBArr->p[s] + RiR->p[s] / 4.0; avgDlt->p[s] = aDlt->p[s] / bDlt->p[s]; try{ avgLnDlt->p[s] = psi( aDlt->p[s] ) - log( bDlt->p[s] ); }catch (int status){ return status; } return 0; } double vbHmmModel_GaussDiff::varLowerBound_modelTerm( vbHmmData *d ){ int s; double lnp = 0.0; double lnq = - sNo / 2.0; for( s = 0 ; s < sNo ; s++ ){ try{ lnp += - lnGamma(uAArr->p[s]) + uAArr->p[s] * log(uBArr->p[s]); }catch (int status){ return numeric_limits<float>::quiet_NaN(); } lnp += (uAArr->p[s] - 1.0) * avgLnDlt->p[s] - uBArr->p[s] * avgDlt->p[s]; try{ lnq = - lnGamma(aDlt->p[s]) + aDlt->p[s] * log(bDlt->p[s]); }catch (int status){ return numeric_limits<float>::quiet_NaN(); } lnq += (aDlt->p[s] - 1.0) * avgLnDlt->p[s] - aDlt->p[s]; } return lnp - lnq; } void vbHmmModel_GaussDiff::reorderParameters( vbHmmData *d ){ int r, n; int i, j; Vec1I index( sNo ); Vec1D store( sNo ); Mat2D s2D( sNo, sNo ); // index indicates order of avgDlt values (0=biggest avgDlt -- sNo=smallest avgDlt). for( i = 0 ; i < sNo ; i++ ){ index.p[i] = sNo - 1; for( j = 0 ; j < sNo ; j++ ){ if( j != i ){ if( avgDlt->p[i] < avgDlt->p[j] ){ index.p[i]--; } else if( avgDlt->p[i] == avgDlt->p[j] ){ if( j > i ) { index.p[i]--; } } } } } for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = avgPi->p[i]; } for( i = 0 ; i < sNo ; i++ ){ avgPi->p[i] = store.p[i]; } for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = avgLnPi->p[i]; } for( i = 0 ; i < sNo ; i++ ){ avgLnPi->p[i] = store.p[i]; } for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = avgDlt->p[i]; } for( i = 0 ; i < sNo ; i++ ){ avgDlt->p[i] = store.p[i]; } for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = avgLnDlt->p[i]; } for( i = 0 ; i < sNo ; i++ ){ avgLnDlt->p[i] = store.p[i]; } for( j = 0 ; j < sNo ; j++ ){ for( i = 0 ; i < sNo ; i++ ){ s2D.p[index.p[i]][index.p[j]] = avgA->p[i][j]; } } for( j = 0 ; j < sNo ; j++ ){ for( i = 0 ; i < sNo ; i++ ){ avgA->p[i][j] = s2D.p[i][j]; } } for( j = 0 ; j < sNo ; j++ ){ for( i = 0 ; i < sNo ; i++ ){ s2D.p[index.p[i]][index.p[j]] = avgLnA->p[i][j]; } } for( j = 0 ; j < sNo ; j++ ){ for( i = 0 ; i < sNo ; i++ ){ avgLnA->p[i][j] = s2D.p[i][j]; } } for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = NiR->p[i]; } for( i = 0 ; i < sNo ; i++ ){ NiR->p[i] = store.p[i]; } for( r = 0 ; r < R ; r++ ){ for( n = 0 ; n < ivs[r]->N ; n++ ){ for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = ivs[r]->gmMat->p[n][i]; } for( i = 0 ; i < sNo ; i++ ){ ivs[r]->gmMat->p[n][i] = store.p[i]; } } } for( r = 0 ; r < R ; r++ ){ for( n = 0 ; n < ivs[r]->N ; n++ ){ for( j = 0 ; j < sNo ; j++ ){ for( i = 0 ; i < sNo ; i++ ){ s2D.p[index.p[i]][index.p[j]] = ivs[r]->xiMat->p[n][i][j]; } } for( j = 0 ; j < sNo ; j++ ){ for( i = 0 ; i < sNo ; i++ ){ ivs[r]->xiMat->p[n][i][j] = s2D.p[i][j]; } } } } } void vbHmmModel_GaussDiff::outputResults( vbHmmData *d, fstream *logFS ){ int i, j; char str[1024]; *logFS << " results: K = " << sNo << endl; *logFS << " delta: ( " << avgDlt->p[0]; for( i = 1 ; i < sNo ; i++ ){ sprintf(str, ", %g", avgDlt->p[i]); *logFS << str; } *logFS << " )" << endl; *logFS << " pi: ( " << avgPi->p[0]; for( i = 1 ; i < sNo ; i++ ){ sprintf(str, ", %g", avgPi->p[i]); *logFS << str; } *logFS << " )" << endl; *logFS << " A_matrix: ["; for( i = 0 ; i < sNo ; i++ ){ sprintf(str, " ( %g", avgA->p[i][0]); *logFS << str; for( j = 1 ; j < sNo ; j++ ){ sprintf(str, ", %g", avgA->p[i][j]); *logFS << str; } *logFS << ")"; } *logFS << " ]" << endl << endl; char fn[1024]; fstream fs; int n; sprintf( fn, "%s.param%03d", d->name.c_str(), sNo ); fs.open( fn, ios::out ); if( fs.is_open() ){ fs << "delta, pi"; for( i = 0 ; i < sNo ; i++ ){ sprintf(str, ", A%dx", i); fs << str; } fs << endl; for( i = 0 ; i < sNo ; i++ ){ sprintf(str, "%g, %g", avgDlt->p[i], avgPi->p[i]); fs << str; for( j = 0 ; j < sNo ; j++ ){ sprintf(str, ", %g", avgA->p[j][i]); fs << str; } fs << endl; } fs.close(); } sprintf( fn, "%s.Lq%03d", d->name.c_str(), sNo ); fs.open( fn, ios::out ); if( fs.is_open() ){ for( n = 0 ; n < iteration ; n++ ){ sprintf( str, "%24.20e", LqArr->p[n] ); fs << str << endl; } fs.close(); } int r; sprintf( fn, "%s.maxS%03d", d->name.c_str(), sNo ); int flag = 0; fs.open( fn, ios::out ); if( fs.is_open() ){ n = 0; do{ flag = 1; for( r = 0 ; r < R ; r++ ){ if( r > 0 ){ fs << ","; } if( n < d->traces[r]->N ){ sprintf( str, "%d", ivs[r]->stateTraj->p[n] ); fs << str; } flag &= (n >= (d->traces[r]->N - 1)); } fs << endl; n++; }while( !flag ); fs.close(); } } //
27.51312
115
0.431175
0ceec0ab0c087f9fc39b6c4401450aa24901d4d8
16,362
cpp
C++
fkie_iop_client_global_waypoint_driver/src/urn_jaus_jss_mobility_GlobalWaypointDriverClient/GlobalWaypointDriverClient_ReceiveFSM.cpp
fkie/iop_jaus_mobility_clients
acad91e9a525ac40be64865a11c8d6b702a0a9f3
[ "BSD-3-Clause" ]
1
2018-07-29T10:13:55.000Z
2018-07-29T10:13:55.000Z
fkie_iop_client_global_waypoint_driver/src/urn_jaus_jss_mobility_GlobalWaypointDriverClient/GlobalWaypointDriverClient_ReceiveFSM.cpp
fkie/iop_jaus_mobility_clients
acad91e9a525ac40be64865a11c8d6b702a0a9f3
[ "BSD-3-Clause" ]
1
2019-11-20T14:32:31.000Z
2019-11-21T11:00:20.000Z
fkie_iop_client_global_waypoint_driver/src/urn_jaus_jss_mobility_GlobalWaypointDriverClient/GlobalWaypointDriverClient_ReceiveFSM.cpp
fkie/iop_jaus_mobility_clients
acad91e9a525ac40be64865a11c8d6b702a0a9f3
[ "BSD-3-Clause" ]
null
null
null
#include <fkie_iop_ocu_slavelib/Slave.h> #include <fkie_iop_component/iop_config.h> #include "urn_jaus_jss_mobility_GlobalWaypointDriverClient/GlobalWaypointDriverClient_ReceiveFSM.h" #include <gps_common/conversions.h> using namespace JTS; using namespace iop::ocu; namespace urn_jaus_jss_mobility_GlobalWaypointDriverClient { GlobalWaypointDriverClient_ReceiveFSM::GlobalWaypointDriverClient_ReceiveFSM(urn_jaus_jss_core_Transport::Transport_ReceiveFSM* pTransport_ReceiveFSM, urn_jaus_jss_core_EventsClient::EventsClient_ReceiveFSM* pEventsClient_ReceiveFSM, urn_jaus_jss_core_AccessControlClient::AccessControlClient_ReceiveFSM* pAccessControlClient_ReceiveFSM, urn_jaus_jss_core_ManagementClient::ManagementClient_ReceiveFSM* pManagementClient_ReceiveFSM) { /* * If there are other variables, context must be constructed last so that all * class variables are available if an EntryAction of the InitialState of the * statemachine needs them. */ context = new GlobalWaypointDriverClient_ReceiveFSMContext(*this); this->pTransport_ReceiveFSM = pTransport_ReceiveFSM; this->pEventsClient_ReceiveFSM = pEventsClient_ReceiveFSM; this->pAccessControlClient_ReceiveFSM = pAccessControlClient_ReceiveFSM; this->pManagementClient_ReceiveFSM = pManagementClient_ReceiveFSM; p_travel_speed = 1.0; p_tf_frame_world = "/world"; p_utm_zone = "32U"; p_wp_tolerance = 1.0; p_has_access = false; p_hz = 0.0; } GlobalWaypointDriverClient_ReceiveFSM::~GlobalWaypointDriverClient_ReceiveFSM() { delete context; } void GlobalWaypointDriverClient_ReceiveFSM::setupNotifications() { pManagementClient_ReceiveFSM->registerNotification("Receiving_Ready", ieHandler, "InternalStateChange_To_GlobalWaypointDriverClient_ReceiveFSM_Receiving_Ready", "ManagementClient_ReceiveFSM"); pManagementClient_ReceiveFSM->registerNotification("Receiving", ieHandler, "InternalStateChange_To_GlobalWaypointDriverClient_ReceiveFSM_Receiving_Ready", "ManagementClient_ReceiveFSM"); registerNotification("Receiving_Ready", pManagementClient_ReceiveFSM->getHandler(), "InternalStateChange_To_ManagementClient_ReceiveFSM_Receiving_Ready", "GlobalWaypointDriverClient_ReceiveFSM"); registerNotification("Receiving", pManagementClient_ReceiveFSM->getHandler(), "InternalStateChange_To_ManagementClient_ReceiveFSM_Receiving", "GlobalWaypointDriverClient_ReceiveFSM"); iop::Config cfg("~GlobalWaypointDriverClient"); cfg.param("travel_speed", p_travel_speed, p_travel_speed); cfg.param("tf_frame_world", p_tf_frame_world, p_tf_frame_world); cfg.param("utm_zone", p_utm_zone, p_utm_zone); cfg.param("waypoint_tolerance", p_wp_tolerance, p_wp_tolerance); cfg.param("hz", p_hz, p_hz, false, false); //ROS_INFO_NAMED("GlobalWaypointDriverClient", " waypoint_tolerance: %.2f", p_wp_tolerance); //create ROS subscriber // p_sub_path = cfg.subscribe<nav_msgs::Path>("cmd_path", 1, &GlobalWaypointDriverClient_ReceiveFSM::pCmdPath, this); p_sub_pose = cfg.subscribe<geometry_msgs::PoseStamped>("cmd_pose", 1, &GlobalWaypointDriverClient_ReceiveFSM::pCmdPose, this); p_sub_fix = cfg.subscribe<sensor_msgs::NavSatFix>("cmd_fix", 1, &GlobalWaypointDriverClient_ReceiveFSM::pCmdFix, this); p_sub_speed = cfg.subscribe<std_msgs::Float32>("cmd_speed", 1, &GlobalWaypointDriverClient_ReceiveFSM::pCmdSpeed, this); p_pub_path = cfg.advertise<nav_msgs::Path>("global_waypoint", 5, true); p_sub_geopose = cfg.subscribe<geographic_msgs::GeoPoseStamped>("cmd_geopose", 1, &GlobalWaypointDriverClient_ReceiveFSM::pCmdGeoPose, this); // initialize the control layer, which handles the access control staff Slave &slave = Slave::get_instance(*(jausRouter->getJausAddress())); slave.add_supported_service(*this, "urn:jaus:jss:mobility:GlobalWaypointDriver", 1, 0); } void GlobalWaypointDriverClient_ReceiveFSM::control_allowed(std::string service_uri, JausAddress component, unsigned char authority) { if (service_uri.compare("urn:jaus:jss:mobility:GlobalWaypointDriver") == 0) { p_remote_addr = component; p_has_access = true; } else { ROS_WARN_STREAM("[GlobalWaypointDriverClient] unexpected control allowed for " << service_uri << " received, ignored!"); } } void GlobalWaypointDriverClient_ReceiveFSM::enable_monitoring_only(std::string service_uri, JausAddress component) { p_remote_addr = component; } void GlobalWaypointDriverClient_ReceiveFSM::access_deactivated(std::string service_uri, JausAddress component) { p_has_access = false; p_remote_addr = JausAddress(0); } void GlobalWaypointDriverClient_ReceiveFSM::create_events(std::string service_uri, JausAddress component, bool by_query) { if (by_query) { if (p_hz > 0) { ROS_INFO_NAMED("GlobalWaypointDriverClient", "create QUERY timer to get global waypoint from %s with %.2fHz", component.str().c_str(), p_hz); p_query_timer = p_nh.createTimer(ros::Duration(1.0 / p_hz), &GlobalWaypointDriverClient_ReceiveFSM::pQueryCallback, this); } else { ROS_WARN_NAMED("GlobalWaypointDriverClient", "invalid hz %.2f for QUERY timer to get global waypoint from %s", p_hz, component.str().c_str()); } } else { ROS_INFO_NAMED("GlobalWaypointDriverClient", "create EVENT to get global waypoint from %s with %.2fHz", component.str().c_str(), p_hz); pEventsClient_ReceiveFSM->create_event(*this, component, p_query_global_waypoint_msg, p_hz); sendJausMessage(p_query_global_waypoint_msg, component); } } void GlobalWaypointDriverClient_ReceiveFSM::cancel_events(std::string service_uri, JausAddress component, bool by_query) { if (by_query) { p_query_timer.stop(); } else { ROS_INFO_NAMED("GlobalWaypointDriverClient", "cancel EVENT for global waypoint by %s", component.str().c_str()); pEventsClient_ReceiveFSM->cancel_event(*this, component, p_query_global_waypoint_msg); } } void GlobalWaypointDriverClient_ReceiveFSM::pQueryCallback(const ros::TimerEvent& event) { if (p_remote_addr.get() != 0) { sendJausMessage(p_query_global_waypoint_msg, p_remote_addr); } } void GlobalWaypointDriverClient_ReceiveFSM::event(JausAddress sender, unsigned short query_msg_id, unsigned int reportlen, const unsigned char* reportdata) { ReportGlobalWaypoint report; report.decode(reportdata); Receive::Body::ReceiveRec transport_data; transport_data.setSrcSubsystemID(sender.getSubsystemID()); transport_data.setSrcNodeID(sender.getNodeID()); transport_data.setSrcComponentID(sender.getComponentID()); handleReportGlobalWaypointAction(report, transport_data); } void GlobalWaypointDriverClient_ReceiveFSM::handleReportGlobalWaypointAction(ReportGlobalWaypoint msg, Receive::Body::ReceiveRec transportData) { JausAddress sender = transportData.getAddress(); double lat, lon, alt = 0.0; double roll, pitch, yaw = 0.0; ReportGlobalWaypoint::Body::GlobalWaypointRec *wprec = msg.getBody()->getGlobalWaypointRec(); lat = wprec->getLatitude(); lon = wprec->getLongitude(); if (wprec->isAltitudeValid()) { alt = wprec->getAltitude(); } if (wprec->isRollValid()) { roll = wprec->getRoll(); } if (wprec->isPitchValid()) { pitch = wprec->getPitch(); } if (wprec->isYawValid()) { yaw = wprec->getYaw(); } if (wprec->isWaypointToleranceValid()) { } ROS_DEBUG_NAMED("GlobalWaypointDriverClient", "globalWaypointAction from %s - lat: %.2f, lon: %.2f", sender.str().c_str(), lat, lon); ROS_DEBUG_NAMED("GlobalWaypointDriverClient", " alt: %.2f, roll: %.2f, pitch: %.2f, yaw: %.2f", alt, roll, pitch, yaw); nav_msgs::Path path; path.header.stamp = ros::Time::now(); path.header.frame_id = this->p_tf_frame_world; if (lat > -90.0 && lon > -180.0 && lat < 90.0 && lon < 180.0) { double northing, easting; std::string zone; gps_common::LLtoUTM(lat, lon, northing, easting, zone); tf::Quaternion quat = tf::createQuaternionFromRPY(roll, pitch, yaw); geometry_msgs::PoseStamped pose; pose.header = path.header; pose.pose.position.x = easting; pose.pose.position.y = northing; pose.pose.position.z = alt; pose.pose.orientation.x = quat.x(); pose.pose.orientation.y = quat.y(); pose.pose.orientation.z = quat.z(); pose.pose.orientation.w = quat.w(); path.poses.push_back(pose); } this->p_pub_path.publish(path); } void GlobalWaypointDriverClient_ReceiveFSM::handleReportTravelSpeedAction(ReportTravelSpeed msg, Receive::Body::ReceiveRec transportData) { JausAddress sender = transportData.getAddress(); p_travel_speed = msg.getBody()->getTravelSpeedRec()->getSpeed(); ROS_DEBUG_NAMED("GlobalWaypointDriverClient", "currentReportTravelSpeedAction from %s, speed: %.2f", sender.str().c_str(), p_travel_speed); } void GlobalWaypointDriverClient_ReceiveFSM::pCmdPath(const nav_msgs::Path::ConstPtr& msg) { if (p_has_access) { SetGlobalWaypoint cmd; geometry_msgs::PointStamped point_out; bool transformed = false; float speed = p_travel_speed; if (msg->poses.size() > 0) { try { geometry_msgs::PoseStamped pose_in = msg->poses[0]; if (pose_in.header.frame_id.empty()) { pose_in.header = msg->header; } tfListener.waitForTransform(p_tf_frame_world, pose_in.header.frame_id, pose_in.header.stamp, ros::Duration(0.3)); geometry_msgs::PoseStamped pose_out; tfListener.transformPose(p_tf_frame_world, pose_in, pose_out); double lat, lon = 0; gps_common::UTMtoLL(pose_out.pose.position.y, pose_out.pose.position.x, p_utm_zone.c_str(), lat, lon); cmd.getBody()->getGlobalWaypointRec()->setLatitude(lat); cmd.getBody()->getGlobalWaypointRec()->setLongitude(lon); cmd.getBody()->getGlobalWaypointRec()->setAltitude(pose_out.pose.position.z); double roll, pitch, yaw; tf::Quaternion quat(pose_out.pose.orientation.x, pose_out.pose.orientation.y, pose_out.pose.orientation.z, pose_out.pose.orientation.w); tf::Matrix3x3(quat).getRPY(roll, pitch, yaw); if (!isnan(yaw)) { cmd.getBody()->getGlobalWaypointRec()->setRoll(roll); cmd.getBody()->getGlobalWaypointRec()->setPitch(pitch); cmd.getBody()->getGlobalWaypointRec()->setYaw(yaw); } transformed = true; } catch (tf::TransformException &ex) { printf ("Failure %s\n", ex.what()); //Print exception which was caught speed = 0.0; } } else { speed = 0.0; } SetTravelSpeed cmd_speed; ROS_INFO_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", speed, p_remote_addr.str().c_str()); cmd_speed.getBody()->getTravelSpeedRec()->setSpeed(speed); sendJausMessage(cmd_speed, p_remote_addr); if (transformed || msg->poses.size() == 0) { ROS_INFO_NAMED("GlobalWaypointDriverClient", "send Waypoint from Path [lat: %.2f, lon: %.2f] to %s", cmd.getBody()->getGlobalWaypointRec()->getLatitude(), cmd.getBody()->getGlobalWaypointRec()->getLongitude(), p_remote_addr.str().c_str()); sendJausMessage(cmd, p_remote_addr); } } } void GlobalWaypointDriverClient_ReceiveFSM::pCmdPose(const geometry_msgs::PoseStamped::ConstPtr& msg) { if (p_has_access) { SetGlobalWaypoint cmd; geometry_msgs::PointStamped point_out; SetTravelSpeed cmd_speed; float speed = p_travel_speed; try { geometry_msgs::PoseStamped pose_in = *msg; tfListener.waitForTransform(p_tf_frame_world, pose_in.header.frame_id, pose_in.header.stamp, ros::Duration(0.3)); geometry_msgs::PoseStamped pose_out; tfListener.transformPose(p_tf_frame_world, pose_in, pose_out); double lat, lon = 0; gps_common::UTMtoLL(pose_out.pose.position.y, pose_out.pose.position.x, p_utm_zone.c_str(), lat, lon); cmd.getBody()->getGlobalWaypointRec()->setLatitude(lat); cmd.getBody()->getGlobalWaypointRec()->setLongitude(lon); cmd.getBody()->getGlobalWaypointRec()->setAltitude(pose_out.pose.position.z); double roll, pitch, yaw; tf::Quaternion quat(pose_out.pose.orientation.x, pose_out.pose.orientation.y, pose_out.pose.orientation.z, pose_out.pose.orientation.w); tf::Matrix3x3(quat).getRPY(roll, pitch, yaw); if (!isnan(yaw)) { cmd.getBody()->getGlobalWaypointRec()->setRoll(roll); cmd.getBody()->getGlobalWaypointRec()->setPitch(pitch); cmd.getBody()->getGlobalWaypointRec()->setYaw(yaw); } ROS_INFO_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", speed, p_remote_addr.str().c_str()); cmd_speed.getBody()->getTravelSpeedRec()->setSpeed(speed); sendJausMessage(cmd_speed, p_remote_addr); ROS_INFO_NAMED("GlobalWaypointDriverClient", "send Waypoint from Pose [lat: %.2f, lon: %.2f] to %s", cmd.getBody()->getGlobalWaypointRec()->getLatitude(), cmd.getBody()->getGlobalWaypointRec()->getLongitude(), p_remote_addr.str().c_str()); sendJausMessage(cmd, p_remote_addr); } catch (tf::TransformException &ex) { printf ("Failure %s\n", ex.what()); //Print exception which was caught speed = 0.0; ROS_INFO_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", speed, p_remote_addr.str().c_str()); cmd_speed.getBody()->getTravelSpeedRec()->setSpeed(speed); sendJausMessage(cmd_speed, p_remote_addr); } } } void GlobalWaypointDriverClient_ReceiveFSM::pCmdFix(const sensor_msgs::NavSatFix::ConstPtr& msg) { if (p_has_access) { SetGlobalWaypoint cmd; SetTravelSpeed cmd_speed; float speed = p_travel_speed; try { cmd.getBody()->getGlobalWaypointRec()->setLatitude(msg->latitude); cmd.getBody()->getGlobalWaypointRec()->setLongitude(msg->longitude); cmd.getBody()->getGlobalWaypointRec()->setAltitude(msg->altitude); ROS_INFO_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", speed, p_remote_addr.str().c_str()); cmd_speed.getBody()->getTravelSpeedRec()->setSpeed(speed); sendJausMessage(cmd_speed, p_remote_addr); ROS_INFO_NAMED("GlobalWaypointDriverClient", "send Waypoint from NavSatFix [lat: %.2f, lon: %.2f] to %s", cmd.getBody()->getGlobalWaypointRec()->getLatitude(), cmd.getBody()->getGlobalWaypointRec()->getLongitude(), p_remote_addr.str().c_str()); sendJausMessage(cmd, p_remote_addr); } catch (tf::TransformException &ex) { printf ("Failure %s\n", ex.what()); //Print exception which was caught speed = 0.0; ROS_INFO_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", speed, p_remote_addr.str().c_str()); cmd_speed.getBody()->getTravelSpeedRec()->setSpeed(speed); sendJausMessage(cmd_speed, p_remote_addr); } } } void GlobalWaypointDriverClient_ReceiveFSM::pCmdGeoPose(const geographic_msgs::GeoPoseStamped::ConstPtr& msg) { if (p_has_access) { SetGlobalWaypoint cmd; SetTravelSpeed cmd_speed; float speed = p_travel_speed; try { cmd.getBody()->getGlobalWaypointRec()->setLatitude(msg->pose.position.latitude); cmd.getBody()->getGlobalWaypointRec()->setLongitude(msg->pose.position.longitude); cmd.getBody()->getGlobalWaypointRec()->setAltitude(msg->pose.position.altitude); double roll, pitch, yaw; tf::Quaternion quat(msg->pose.orientation.x, msg->pose.orientation.y, msg->pose.orientation.z, msg->pose.orientation.w); tf::Matrix3x3(quat).getRPY(roll, pitch, yaw); if (!isnan(yaw)) { cmd.getBody()->getGlobalWaypointRec()->setRoll(roll); cmd.getBody()->getGlobalWaypointRec()->setPitch(pitch); cmd.getBody()->getGlobalWaypointRec()->setYaw(yaw); } ROS_INFO_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", speed, p_remote_addr.str().c_str()); cmd_speed.getBody()->getTravelSpeedRec()->setSpeed(speed); sendJausMessage(cmd_speed, p_remote_addr); ROS_INFO_NAMED("GlobalWaypointDriverClient", "send Waypoint from Pose [lat: %.2f, lon: %.2f] to %s", cmd.getBody()->getGlobalWaypointRec()->getLatitude(), cmd.getBody()->getGlobalWaypointRec()->getLongitude(), p_remote_addr.str().c_str()); sendJausMessage(cmd, p_remote_addr); } catch (tf::TransformException &ex) { printf ("Failure %s\n", ex.what()); //Print exception which was caught speed = 0.0; ROS_INFO_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", speed, p_remote_addr.str().c_str()); cmd_speed.getBody()->getTravelSpeedRec()->setSpeed(speed); sendJausMessage(cmd_speed, p_remote_addr); } } } void GlobalWaypointDriverClient_ReceiveFSM::pCmdSpeed(const std_msgs::Float32::ConstPtr& msg) { if (p_has_access) { p_travel_speed = msg->data; SetTravelSpeed cmd; ROS_DEBUG_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", p_travel_speed, p_remote_addr.str().c_str()); cmd.getBody()->getTravelSpeedRec()->setSpeed(p_travel_speed); sendJausMessage(cmd, p_remote_addr); } } };
44.827397
432
0.758159
0cef17fdf29ff342913dc7ee4c7eed5b7ee51f26
26,760
cc
C++
test/SudokuGridPointTest.cc
KroneckerDeIta/Sudoku
d14d501178e0744f998444b58c991be3aed296ef
[ "MIT" ]
null
null
null
test/SudokuGridPointTest.cc
KroneckerDeIta/Sudoku
d14d501178e0744f998444b58c991be3aed296ef
[ "MIT" ]
null
null
null
test/SudokuGridPointTest.cc
KroneckerDeIta/Sudoku
d14d501178e0744f998444b58c991be3aed296ef
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Implementation of tests for SudokuGridPoint. /// \author anon //////////////////////////////////////////////////////////////////////////////////////////////////// #include <boost/shared_ptr.hpp> #include "src/SudokuGridPoint.h" #include "SudokuGridPointTest.h" #include "utilities/src/CheckIfVectorsEqual.h" CPPUNIT_TEST_SUITE_REGISTRATION( sudoku::SudokuGridPointTest ); // Define some ordinates. const short negativeX(-1); const short negativeY(-1); const short validX(1); const short validY(2); const short tooLargeX(9); const short tooLargeY(9); // Define some values. const short zeroValue(0); const short validValue(3); const short tooLargeValue(10); namespace sudoku { //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfXNegative() { testFields_.x = negativeX; try { (void)createSubject(); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify a negative x ordinate.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfYNegative() { testFields_.y = negativeY; try { (void)createSubject(); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify a negative y ordinate.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfXTooLarge() { testFields_.x = tooLargeX; try { (void)createSubject(); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify an x ordinate > 8.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfYTooLarge() { testFields_.y = tooLargeY; try { (void)createSubject(); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify an y ordinate > 8.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfValueZero() { testFields_.value = zeroValue; try { (void)createSubject(); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify value <= 0.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfValueTooLarge() { testFields_.value = tooLargeValue; try { (void)createSubject(); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify a value > 9.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGetX() { CPPUNIT_ASSERT_EQUAL( validX, subject_->getX() ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGetY() { CPPUNIT_ASSERT_EQUAL( validY, subject_->getY() ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGetValue() { CPPUNIT_ASSERT_EQUAL( validValue, subject_->getValue() ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfValueInPossibleValuesZero() { std::vector<short> possibleValues = {8, 9, 0}; try { (void)createSubject(possibleValues); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify a possible value <= 0.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfValueInPossibleValuesTooLarge() { std::vector<short> possibleValues = {8, 9, 10}; try { (void)createSubject(possibleValues); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify a possible value > 9.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfValueInPossibleValuesRepeated() { std::vector<short> possibleValues = {1, 3, 3}; try { (void)createSubject(possibleValues); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Possible values has repeated values.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfPossibleValuesEmpty() { std::vector<short> possibleValues = {}; try { (void)createSubject(possibleValues); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Possible values cannot be empty.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGetPossibleValues() { std::vector<short> possibleValues = {1, 2, 3}; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); CPPUNIT_ASSERT( std::equal(possibleValues.begin(), possibleValues.end(), s->getPossibleValues().begin() ) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRemoveValueFromPossibleValuesForSameXY() { std::vector<short> possibleValues = {1, 2, 3}; std::vector<short> possibleValuesRemoved = {1, 3}; const short testX = 1; const short testY = 2; const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // First check method returns that value could be removed, but it wasn't the last one. CPPUNIT_ASSERT_EQUAL( static_cast<short>(1), s->removePossibleValue(testX, testY, testValue) ); // Now check values. CPPUNIT_ASSERT( std::equal(possibleValuesRemoved.begin(), possibleValuesRemoved.end(), s->getPossibleValues().begin() ) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRemoveValueFromPossibleValuesFailedDueToXYNotInRowColOrBox() { std::vector<short> possibleValues = {1, 2, 3}; const short testX = 2; const short testY = 3; const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // First check method returns that value could not be removed. CPPUNIT_ASSERT_EQUAL( static_cast<short>(2), s->removePossibleValue(testX, testY, testValue) ); // Now check values to make sure nothing was removed. CPPUNIT_ASSERT( std::equal(possibleValues.begin(), possibleValues.end(), s->getPossibleValues().begin() ) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRemoveOneValueFromTwoFromPossibleValues() { std::vector<short> possibleValues = {1, 2}; std::vector<short> removedPossibleValues = {1}; const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Test that value returned is zero. CPPUNIT_ASSERT_EQUAL( static_cast<short>(0), s->getValue() ); // First check method returns that value could be removed, but it wasn't the last possible value. CPPUNIT_ASSERT_EQUAL( static_cast<short>(1), s->removePossibleValue(testFields_.x, testFields_.y, testValue) ); // Check there is one value left in the possible values. CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(removedPossibleValues, s->getPossibleValues())); // Then check the value, it should be 0 still. CPPUNIT_ASSERT_EQUAL( static_cast<short>(0), s->getValue() ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRemoveOneValueFromOneFromPossibleValues() { std::vector<short> possibleValues = {2}; std::vector<short> emptyVector; const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Test that value returned is zero. It has not been guessed yet. CPPUNIT_ASSERT_EQUAL( static_cast<short>(0), s->getValue() ); // First check method returns that value could be removed, and that it was the last one. CPPUNIT_ASSERT_EQUAL( static_cast<short>(0), s->removePossibleValue(testFields_.x, testFields_.y, testValue) ); // Check there is are no values left. CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(emptyVector, s->getPossibleValues())); // Then check the value, it should be a guess - 2 in our case. CPPUNIT_ASSERT_EQUAL( static_cast<short>(2), s->getValue() ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRemoveValueWhenInitialValueWasGiven() { // Give some values inside the same box. const short testX = 0; const short testY = 0; const short testValue = 2; // Check that method returns that no value was removed. CPPUNIT_ASSERT_EQUAL( static_cast<short>(2), subject_->removePossibleValue(testX, testY, testValue) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRestorePossibleValue() { std::vector<short> possibleValues = {1, 2, 3}; const short testX = 2; const short testY = 1; const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Remove value. s->removePossibleValue(testX, testY, testValue); // Restore the value that was just removed. CPPUNIT_ASSERT( s->restorePossibleValue(testX, testY, testValue) ); std::vector<short> returnValues(s->getPossibleValues()); CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(possibleValues, returnValues) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRestorePossibleValueFailsIfXDifferentFromOneRecorded() { std::vector<short> possibleValues = {1, 2, 3}; std::vector<short> removedPossibleValues = {1, 3}; const short testX = 2; const short otherX = 3; const short testY = 1; const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Remove value. s->removePossibleValue(testX, testY, testValue); // Test that restoring not possible as input x is different. CPPUNIT_ASSERT( ! s->restorePossibleValue(otherX, testY, testValue) ); std::vector<short> returnValues(s->getPossibleValues()); CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(removedPossibleValues, returnValues) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRestorePossibleValueFailsIfYDifferentFromOneRecorded() { std::vector<short> possibleValues = {1, 2, 3}; std::vector<short> removedPossibleValues = {1, 3}; const short testX = 2; const short testY = 1; const short otherY = 2; const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Remove value. s->removePossibleValue(testX, testY, testValue); // Test that restoring not possible as input x is different. CPPUNIT_ASSERT( ! s->restorePossibleValue(testX, otherY, testValue) ); std::vector<short> returnValues(s->getPossibleValues()); CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(removedPossibleValues, returnValues) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRestorePossibleValueThatIsAlreadyInPossibleValues() { std::vector<short> possibleValues = {1, 2, 3}; const short testX = 2; const short testY = 1; const short testValue = 1; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Check restoring a value that was not removed before returns false. CPPUNIT_ASSERT( ! s->restorePossibleValue(testX, testY, testValue) ); std::vector<short> returnValues(s->getPossibleValues()); CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(possibleValues, returnValues) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRestorePossibleValueWhenInitialValueWasGiven() { const short testX = 2; const short testY = 1; const short testValue = 1; CPPUNIT_ASSERT( ! subject_->restorePossibleValue(testX, testY, testValue) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRestorePossibleValueThatWasAddedToGuessedValues() { std::vector<short> possibleValues = {1, 2}; std::vector<short> removedPossibleValues = {1}; const short testX(2); const short testY(2); const short testValue1 = 1; const short testValue2 = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Remove a value that is still in the possible values. s->removePossibleValue(testX, testY, testValue1); s->removePossibleValue(testFields_.x, testFields_.y, testValue2); // Make sure 2 has been added as a guess. CPPUNIT_ASSERT_EQUAL( static_cast<short>(2), s->getValue() ); // Restore the value 1 now though. s->restorePossibleValue(testX, testY , testValue1); // Should return 0 as the value, if 1 has been restored. CPPUNIT_ASSERT_EQUAL( static_cast<short>(0), s->getValue() ); std::vector<short> returnValues(s->getPossibleValues()); CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(removedPossibleValues, returnValues) ); // Finally restore 2 as well. s->restorePossibleValue(testFields_.x, testFields_.y, testValue2); returnValues = s->getPossibleValues(); // Check we have what we originally had. CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(possibleValues, returnValues) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGetValueWhenOneValuePassedToConstructor() { std::vector<short> possibleValues = {1}; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Check value is set. CPPUNIT_ASSERT_EQUAL( static_cast<short>(0), s->getValue() ); // Check possible values vector is empty. CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(possibleValues, s->getPossibleValues()) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testEqualityOfTwoSudokuGridPointObjects() { boost::shared_ptr<SudokuGridPoint> sInitial(createSubject()); std::vector<short> possibleValuesOne1 = {1}; boost::shared_ptr<SudokuGridPoint> sOnePossible1(createSubject(possibleValuesOne1)); std::vector<short> possibleValuesOne2 = {2}; boost::shared_ptr<SudokuGridPoint> sOnePossible2(createSubject(possibleValuesOne2)); std::vector<short> possibleValuesTwo = {1, 2}; boost::shared_ptr<SudokuGridPoint> sTwoPossibles(createSubject(possibleValuesTwo)); CPPUNIT_ASSERT( *sInitial == *subject_ ); CPPUNIT_ASSERT( ! (*sOnePossible1 == *subject_) ); CPPUNIT_ASSERT( *sOnePossible1 == *sOnePossible2 ); CPPUNIT_ASSERT( ! (*sOnePossible1 == *sTwoPossibles) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testLessThanOfSudokuGridPointObjects() { boost::shared_ptr<SudokuGridPoint> sInitial(createSubject()); std::vector<short> possibleValuesOne1 = {1}; boost::shared_ptr<SudokuGridPoint> sOnePossible1(createSubject(possibleValuesOne1)); std::vector<short> possibleValuesOne2 = {2}; boost::shared_ptr<SudokuGridPoint> sOnePossible2(createSubject(possibleValuesOne2)); std::vector<short> possibleValuesTwo = {1, 2}; boost::shared_ptr<SudokuGridPoint> sTwoPossibles(createSubject(possibleValuesTwo)); CPPUNIT_ASSERT( ! (*sInitial < *subject_) ); CPPUNIT_ASSERT( *subject_ < *sOnePossible1 ); CPPUNIT_ASSERT( ! (*sOnePossible1 < *subject_) ); CPPUNIT_ASSERT( ! (*sOnePossible1 < *sOnePossible2) ); CPPUNIT_ASSERT( *sOnePossible1 < *sTwoPossibles ); CPPUNIT_ASSERT( ! (*sTwoPossibles < *sOnePossible1) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testNotEqualOperatorSudokuGridPointObjects() { boost::shared_ptr<SudokuGridPoint> sInitial(createSubject()); std::vector<short> possibleValuesOne1 = {1}; boost::shared_ptr<SudokuGridPoint> sOnePossible1(createSubject(possibleValuesOne1)); std::vector<short> possibleValuesOne2 = {2}; boost::shared_ptr<SudokuGridPoint> sOnePossible2(createSubject(possibleValuesOne2)); std::vector<short> possibleValuesTwo = {1, 2}; boost::shared_ptr<SudokuGridPoint> sTwoPossibles(createSubject(possibleValuesTwo)); CPPUNIT_ASSERT( ! (*sInitial != *subject_) ); CPPUNIT_ASSERT( *subject_ != *sOnePossible1 ); CPPUNIT_ASSERT( ! (*sOnePossible1 != *sOnePossible2) ); CPPUNIT_ASSERT( *sOnePossible1 != *sTwoPossibles ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testLessThanOrEqualToOperatorSudokuGridPointObjects() { boost::shared_ptr<SudokuGridPoint> sInitial(createSubject()); std::vector<short> possibleValuesOne1 = {1}; boost::shared_ptr<SudokuGridPoint> sOnePossible1(createSubject(possibleValuesOne1)); std::vector<short> possibleValuesOne2 = {2}; boost::shared_ptr<SudokuGridPoint> sOnePossible2(createSubject(possibleValuesOne2)); std::vector<short> possibleValuesTwo = {1, 2}; boost::shared_ptr<SudokuGridPoint> sTwoPossibles(createSubject(possibleValuesTwo)); CPPUNIT_ASSERT( *sInitial <= *subject_ ); CPPUNIT_ASSERT( *subject_ <= *sOnePossible1 ); CPPUNIT_ASSERT( ! (*sOnePossible1 <= *subject_) ); CPPUNIT_ASSERT( *sOnePossible1 <= *sOnePossible2 ); CPPUNIT_ASSERT( *sOnePossible1 <= *sTwoPossibles ); CPPUNIT_ASSERT( ! (*sTwoPossibles <= *sOnePossible1) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGreaterThanOperatorSudokuGridPointObjects() { boost::shared_ptr<SudokuGridPoint> sInitial(createSubject()); std::vector<short> possibleValuesOne1 = {1}; boost::shared_ptr<SudokuGridPoint> sOnePossible1(createSubject(possibleValuesOne1)); std::vector<short> possibleValuesOne2 = {2}; boost::shared_ptr<SudokuGridPoint> sOnePossible2(createSubject(possibleValuesOne2)); std::vector<short> possibleValuesTwo = {1, 2}; boost::shared_ptr<SudokuGridPoint> sTwoPossibles(createSubject(possibleValuesTwo)); CPPUNIT_ASSERT( ! (*sInitial > *subject_) ); CPPUNIT_ASSERT( ! (*subject_ > *sOnePossible1) ); CPPUNIT_ASSERT( *sOnePossible1 > *subject_ ); CPPUNIT_ASSERT( ! (*sOnePossible1 > *sOnePossible2) ); CPPUNIT_ASSERT( ! (*sOnePossible1 > *sTwoPossibles) ); CPPUNIT_ASSERT( *sTwoPossibles > *sOnePossible1 ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGreaterThanOrEqualToOperatorSudokuGridPointObjects() { boost::shared_ptr<SudokuGridPoint> sInitial(createSubject()); std::vector<short> possibleValuesOne1 = {1}; boost::shared_ptr<SudokuGridPoint> sOnePossible1(createSubject(possibleValuesOne1)); std::vector<short> possibleValuesOne2 = {2}; boost::shared_ptr<SudokuGridPoint> sOnePossible2(createSubject(possibleValuesOne2)); std::vector<short> possibleValuesTwo = {1, 2}; boost::shared_ptr<SudokuGridPoint> sTwoPossibles(createSubject(possibleValuesTwo)); CPPUNIT_ASSERT( *sInitial >= *subject_ ); CPPUNIT_ASSERT( ! (*subject_ >= *sOnePossible1) ); CPPUNIT_ASSERT( *sOnePossible1 >= *subject_ ); CPPUNIT_ASSERT( *sOnePossible1 >= *sOnePossible2 ); CPPUNIT_ASSERT( ! (*sOnePossible1 >= *sTwoPossibles) ); CPPUNIT_ASSERT( *sTwoPossibles >= *sOnePossible1 ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGetAffectedGridPoints() { std::vector<std::pair<short, short> > myVecX1Y2 = { {1, 0}, {1, 1}, {1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 8}, {0, 2}, {2, 2}, {3, 2}, {4, 2}, {5, 2}, {6, 2}, {7, 2}, {8, 2}, {0, 0}, {0, 1}, {2, 0}, {2, 1} }; testFields_.x = 1; testFields_.y = 2; boost::shared_ptr<SudokuGridPoint> subjectX1Y2(createSubject()); std::vector<std::pair<short, short> > myVecX4Y4 = { {4, 0}, {4, 1}, {4, 2}, {4, 3}, {4, 5}, {4, 6}, {4, 7}, {4, 8}, {0, 4}, {1, 4}, {2, 4}, {3, 4}, {5, 4}, {6, 4}, {7, 4}, {8, 4}, {3, 3}, {3, 5}, {5, 3}, {5, 5} }; testFields_.x = 4; testFields_.y = 4; boost::shared_ptr<SudokuGridPoint> subjectX4Y4(createSubject()); std::vector<std::pair<short, short> > myVecX6Y5 = { {6, 0}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 6}, {6, 7}, {6, 8}, {0, 5}, {1, 5}, {2, 5}, {3, 5}, {4, 5}, {5, 5}, {7, 5}, {8, 5}, {7, 3}, {7, 4}, {8, 3}, {8, 4} }; testFields_.x = 6; testFields_.y = 5; boost::shared_ptr<SudokuGridPoint> subjectX6Y5(createSubject()); CPPUNIT_ASSERT( (utilities::checkIfVectorsEqual<std::pair<short, short> >( subjectX1Y2->getAffectedGridPoints(), myVecX1Y2 ))); CPPUNIT_ASSERT( (utilities::checkIfVectorsEqual<std::pair<short, short> >( subjectX4Y4->getAffectedGridPoints(), myVecX4Y4 ))); CPPUNIT_ASSERT( (utilities::checkIfVectorsEqual<std::pair<short, short> >( subjectX6Y5->getAffectedGridPoints(), myVecX6Y5 ))); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testSudokuGridPointsShallowEqualsMethod() { std::vector<short> testPossibleValues1 = {1, 2}; std::vector<short> testPossibleValues2 = {1, 3}; const short testX1(5); const short testX2(6); const short testY1(6); const short testY2(7); const short testValue1(8); const short testValue2(4); testFields_.x = testX1; testFields_.y = testY1; testFields_.value = testValue1; boost::shared_ptr<SudokuGridPoint> s1(createSubject()); boost::shared_ptr<SudokuGridPoint> s2(createSubject()); boost::shared_ptr<SudokuGridPoint> s3(createSubject(testPossibleValues1)); boost::shared_ptr<SudokuGridPoint> s4(createSubject(testPossibleValues1)); boost::shared_ptr<SudokuGridPoint> s5(createSubject(testPossibleValues2)); testFields_.x = testX2; testFields_.y = testY1; testFields_.value = testValue1; boost::shared_ptr<SudokuGridPoint> s6(createSubject()); testFields_.x = testX1; testFields_.y = testY2; testFields_.value = testValue1; boost::shared_ptr<SudokuGridPoint> s7(createSubject()); testFields_.x = testX1; testFields_.y = testY1; testFields_.value = testValue2; boost::shared_ptr<SudokuGridPoint> s8(createSubject()); // Not all possible combinations. But enough for TDD. CPPUNIT_ASSERT(s1->shallowEquals(*s2)); CPPUNIT_ASSERT(s3->shallowEquals(*s4)); CPPUNIT_ASSERT(! s1->shallowEquals(*s3)); CPPUNIT_ASSERT(! s3->shallowEquals(*s5)); CPPUNIT_ASSERT(! s1->shallowEquals(*s6)); CPPUNIT_ASSERT(! s1->shallowEquals(*s7)); CPPUNIT_ASSERT(! s1->shallowEquals(*s8)); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRemoveFromOnePossibleValueButNotSameGridPoint() { std::vector<short> possibleValues = {2}; // Same box as SudokuGridPoint's. const short testX(0); const short testY(0); const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // First check method returns that value could not be removed, since it was the last value and // the x and y are not the same as the SudokuGridPoint's. CPPUNIT_ASSERT_EQUAL( static_cast<short>(3), s->removePossibleValue(testX, testY, testValue) ); // Check the possible values are the same. CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(possibleValues, s->getPossibleValues())); // Then check the value, it should be the same, i.e. 0. CPPUNIT_ASSERT_EQUAL( static_cast<short>(0), s->getValue() ); } //////////////////////////////////////////////////////////////////////////////////////////////////// boost::shared_ptr<SudokuGridPoint> SudokuGridPointTest::createSubject() { boost::shared_ptr<SudokuGridPoint> subject(new SudokuGridPoint( testFields_.x, testFields_.y, testFields_.value )); return subject; } //////////////////////////////////////////////////////////////////////////////////////////////////// boost::shared_ptr<SudokuGridPoint> SudokuGridPointTest::createSubject( const std::vector<short>& possibleValues) { boost::shared_ptr<SudokuGridPoint> subject(new SudokuGridPoint( testFields_.x, testFields_.y, possibleValues )); return subject; } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::setUp() { testFields_.x = validX; testFields_.y = validY; testFields_.value = validValue; subject_ = createSubject(); } } // End of namespace sudoku.
35.775401
100
0.600673
0cf2f397849efc524d2c82873c589cc900e91101
14,286
cpp
C++
src/ui/screens/viewfilescreen.cpp
hrxcodes/cbftp
bf2784007dcc4cc42775a2d40157c51b80383f81
[ "MIT" ]
8
2019-04-30T00:37:00.000Z
2022-02-03T13:35:31.000Z
src/ui/screens/viewfilescreen.cpp
Xtravaganz/cbftp
31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5
[ "MIT" ]
2
2019-11-19T12:46:13.000Z
2019-12-20T22:13:57.000Z
src/ui/screens/viewfilescreen.cpp
Xtravaganz/cbftp
31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5
[ "MIT" ]
9
2020-01-15T02:38:36.000Z
2022-02-15T20:05:20.000Z
#include "viewfilescreen.h" #include "transfersscreen.h" #include "../ui.h" #include "../menuselectoption.h" #include "../resizableelement.h" #include "../menuselectadjustableline.h" #include "../menuselectoptiontextbutton.h" #include "../termint.h" #include "../misc.h" #include "../../transferstatus.h" #include "../../globalcontext.h" #include "../../sitelogicmanager.h" #include "../../sitelogic.h" #include "../../transfermanager.h" #include "../../localstorage.h" #include "../../localfilelist.h" #include "../../filelist.h" #include "../../file.h" #include "../../externalfileviewing.h" #include "../../core/types.h" class CommandOwner; namespace ViewFileState { enum { NO_SLOTS_AVAILABLE, TOO_LARGE_FOR_INTERNAL, NO_DISPLAY, CONNECTING, DOWNLOADING, LOADING_VIEWER, VIEWING_EXTERNAL, VIEWING_INTERNAL }; } namespace { enum KeyScopes { KEYSCOPE_VIEWING_INTERNAL, KEYSCOPE_VIEWING_EXTERNAL }; enum KeyAction { KEYACTION_ENCODING, KEYACTION_KILL, KEYACTION_KILL_ALL }; } ViewFileScreen::ViewFileScreen(Ui* ui) : UIWindow(ui, "ViewFileScreen") { keybinds.addScope(KEYSCOPE_VIEWING_INTERNAL, "During internal viewing"); keybinds.addScope(KEYSCOPE_VIEWING_EXTERNAL, "During external viewing"); keybinds.addBind('c', KEYACTION_BACK_CANCEL, "Return"); keybinds.addBind(KEY_UP, KEYACTION_UP, "Navigate up", KEYSCOPE_VIEWING_INTERNAL); keybinds.addBind(KEY_DOWN, KEYACTION_DOWN, "Navigate down", KEYSCOPE_VIEWING_INTERNAL); keybinds.addBind(KEY_PPAGE, KEYACTION_PREVIOUS_PAGE, "Next page", KEYSCOPE_VIEWING_INTERNAL); keybinds.addBind(KEY_NPAGE, KEYACTION_NEXT_PAGE, "Previous page", KEYSCOPE_VIEWING_INTERNAL); keybinds.addBind('e', KEYACTION_ENCODING, "Switch encoding", KEYSCOPE_VIEWING_INTERNAL); keybinds.addBind('k', KEYACTION_KILL, "Kill external viewer", KEYSCOPE_VIEWING_EXTERNAL); } ViewFileScreen::~ViewFileScreen() { } void ViewFileScreen::initialize() { rawcontents.clear(); x = 0; y = 0; ymax = 0; xmax = 0; externallyviewable = false; legendupdated = false; pid = 0; autoupdate = true; ts.reset(); } void ViewFileScreen::initialize(unsigned int row, unsigned int col, const std::string & site, const std::string & file, const std::shared_ptr<FileList>& fl) { initialize(); deleteafter = true; this->site = site; this->file = file; filelist = fl; sitelogic = global->getSiteLogicManager()->getSiteLogic(site); size = filelist->getFile(file)->getSize(); state = ViewFileState::CONNECTING; if (global->getExternalFileViewing()->isViewable(file)) { if (!global->getExternalFileViewing()->hasDisplay()) { state = ViewFileState::NO_DISPLAY; } externallyviewable = true; } else { if (size > MAXOPENSIZE) { state = ViewFileState::TOO_LARGE_FOR_INTERNAL; } } if (state == ViewFileState::CONNECTING) { requestid = sitelogic->requestOneIdle(ui); } if (state == ViewFileState::DOWNLOADING) { if (!ts) { state = ViewFileState::NO_SLOTS_AVAILABLE; } else { } } init(row, col); } void ViewFileScreen::initialize(unsigned int row, unsigned int col, const Path & dir, const std::string & file) { initialize(); deleteafter = false; path = dir / file; this->file = file; size = global->getLocalStorage()->getFileSize(path); state = ViewFileState::LOADING_VIEWER; if (global->getExternalFileViewing()->isViewable(file)) { if (!global->getExternalFileViewing()->hasDisplay()) { state = ViewFileState::NO_DISPLAY; } externallyviewable = true; } else { if (size > MAXOPENSIZE) { state = ViewFileState::TOO_LARGE_FOR_INTERNAL; } } init(row, col); } void ViewFileScreen::redraw() { ui->erase(); switch (state) { case ViewFileState::NO_SLOTS_AVAILABLE: ui->printStr(1, 1, "No download slots available at " + site + "."); break; case ViewFileState::TOO_LARGE_FOR_INTERNAL: ui->printStr(1, 1, file + " is too large to download and open in the internal viewer."); ui->printStr(2, 1, "The maximum file size for internal viewing is set to " + std::to_string(MAXOPENSIZE) + " bytes."); break; case ViewFileState::NO_DISPLAY: ui->printStr(1, 1, file + " cannot be opened in an external viewer."); ui->printStr(2, 1, "The DISPLAY environment variable is not set."); break; case ViewFileState::CONNECTING: if (sitelogic->requestReady(requestid)) { sitelogic->finishRequest(requestid); const Path & temppath = global->getLocalStorage()->getTempPath(); std::shared_ptr<LocalFileList> localfl = global->getLocalStorage()->getLocalFileList(temppath); ts = global->getTransferManager()->suggestDownload(file, sitelogic, filelist, localfl); if (!!ts) { state = ViewFileState::DOWNLOADING; ts->setAwaited(true); path = temppath / file; expectbackendpush = true; } else { state = ViewFileState::NO_SLOTS_AVAILABLE; redraw(); } } else { ui->printStr(1, 1, "Awaiting slot..."); } break; case ViewFileState::DOWNLOADING: switch(ts->getState()) { case TRANSFERSTATUS_STATE_IN_PROGRESS: ui->printStr(1, 1, "Downloading from " + site + "..."); printTransferInfo(); break; case TRANSFERSTATUS_STATE_FAILED: ui->printStr(1, 1, "Download of " + file + " from " + site + " failed."); autoupdate = false; break; case TRANSFERSTATUS_STATE_SUCCESSFUL: loadViewer(); break; } break; case ViewFileState::LOADING_VIEWER: loadViewer(); break; case ViewFileState::VIEWING_EXTERNAL: viewExternal(); break; case ViewFileState::VIEWING_INTERNAL: viewInternal(); break; } } void ViewFileScreen::update() { if (pid) { if (!global->getExternalFileViewing()->stillViewing(pid)) { ui->returnToLast(); } else if (!legendupdated) { legendupdated = true; ui->update(); ui->setLegend(); } } else { redraw(); if ((state == ViewFileState::VIEWING_INTERNAL || state == ViewFileState::VIEWING_EXTERNAL) && !legendupdated) { legendupdated = true; ui->update(); ui->setLegend(); } } } bool ViewFileScreen::keyPressed(unsigned int ch) { int scope = getCurrentScope(); int action = keybinds.getKeyAction(ch, scope); switch(action) { case KEYACTION_BACK_CANCEL: ui->returnToLast(); return true; case KEYACTION_DOWN: if (goDown()) { goDown(); ui->setInfo(); ui->redraw(); } return true; case KEYACTION_UP: if (goUp()) { goUp(); ui->setInfo(); ui->redraw(); } return true; case KEYACTION_NEXT_PAGE: for (unsigned int i = 0; i < row / 2; i++) { goDown(); } ui->setInfo(); ui->redraw(); return true; case KEYACTION_PREVIOUS_PAGE: for (unsigned int i = 0; i < row / 2; i++) { goUp(); } ui->setInfo(); ui->redraw(); return true; case KEYACTION_KILL: if (pid) { global->getExternalFileViewing()->killProcess(pid); } return true; case KEYACTION_ENCODING: if (state == ViewFileState::VIEWING_INTERNAL) { if (encoding == encoding::ENCODING_CP437) { encoding = encoding::ENCODING_CP437_DOUBLE; } else if (encoding == encoding::ENCODING_CP437_DOUBLE) { encoding = encoding::ENCODING_ISO88591; } else if (encoding == encoding::ENCODING_ISO88591) { encoding = encoding::ENCODING_UTF8; } else { encoding = encoding::ENCODING_CP437; } translate(); ui->redraw(); ui->setInfo(); } return true; } return false; } void ViewFileScreen::loadViewer() { if (externallyviewable) { if (!pid) { if (deleteafter) { pid = global->getExternalFileViewing()->viewThenDelete(path); } else { pid = global->getExternalFileViewing()->view(path); } } state = ViewFileState::VIEWING_EXTERNAL; viewExternal(); } else { Core::BinaryData tmpdata = global->getLocalStorage()->getFileContent(path); if (deleteafter) { global->getLocalStorage()->requestDelete(path); } std::string extension = File::getExtension(file); encoding = encoding::guessEncoding(tmpdata); unsigned int tmpdatalen = tmpdata.size(); if (tmpdatalen > 0) { std::string current; for (unsigned int i = 0; i < tmpdatalen; i++) { if (tmpdata[i] == '\n') { rawcontents.push_back(current); current.clear(); } else { current += tmpdata[i]; } } if (current.length() > 0) { rawcontents.push_back(current); } translate(); } autoupdate = false; state = ViewFileState::VIEWING_INTERNAL; viewInternal(); } } void ViewFileScreen::viewExternal() { ui->printStr(1, 1, "Opening " + file + " with: " + global->getExternalFileViewing()->getViewApplication(file)); ui->printStr(3, 1, "Press 'k' to kill this external viewer instance."); ui->printStr(4, 1, "You can always press 'K' to kill ALL external viewers."); } void ViewFileScreen::viewInternal() { if (ymax <= row) { y = 0; } while (ymax > row && y + row > ymax) { --y; } ymax = rawcontents.size(); for (unsigned int i = 0; i < ymax; i++) { if (translatedcontents[i].length() > xmax) { xmax = translatedcontents[i].length(); } } for (unsigned int i = 0; i < row && i < ymax; i++) { std::basic_string<unsigned int> & line = translatedcontents[y + i]; for (unsigned int j = 0; j < line.length() && j < col - 2; j++) { ui->printChar(i, j + 1, line[j]); } } printSlider(ui, row, col - 1, ymax, y); } std::string ViewFileScreen::getLegendText() const { return keybinds.getLegendSummary(getCurrentScope()); } std::string ViewFileScreen::getInfoLabel() const { return "VIEW FILE: " + file; } std::string ViewFileScreen::getInfoText() const { if (state == ViewFileState::VIEWING_INTERNAL) { std::string enc; switch (encoding) { case encoding::ENCODING_CP437: enc = "CP437"; break; case encoding::ENCODING_CP437_DOUBLE: enc = "Double CP437"; break; case encoding::ENCODING_ISO88591: enc = "ISO-8859-1"; break; case encoding::ENCODING_UTF8: enc = "UTF-8"; break; } unsigned int end = ymax < y + row ? ymax : y + row; return "Line " + std::to_string(y) + "-" + std::to_string(end) + "/" + std::to_string(ymax) + " Encoding: " + enc; } else { return ""; } } void ViewFileScreen::translate() { translatedcontents.clear(); for (unsigned int i = 0; i < rawcontents.size(); i++) { std::basic_string<unsigned int> current; if (encoding == encoding::ENCODING_CP437_DOUBLE) { current = encoding::doublecp437toUnicode(rawcontents[i]); } else if (encoding == encoding::ENCODING_CP437) { current = encoding::cp437toUnicode(rawcontents[i]); } else if (encoding == encoding::ENCODING_ISO88591) { current = encoding::toUnicode(rawcontents[i]); } else { current = encoding::utf8toUnicode(rawcontents[i]); } translatedcontents.push_back(current); } } bool ViewFileScreen::goDown() { if (y + row < ymax) { y++; return true; } return false; } bool ViewFileScreen::goUp() { if (y > 0) { y--; return true; } return false; } void ViewFileScreen::printTransferInfo() { TransferDetails td = TransfersScreen::formatTransferDetails(ts); unsigned int y = 3; MenuSelectOption table; std::shared_ptr<MenuSelectAdjustableLine> msal = table.addAdjustableLine(); std::shared_ptr<MenuSelectOptionTextButton> msotb; msotb = table.addTextButtonNoContent(y, 1, "transferred", "TRANSFERRED"); msal->addElement(msotb, 4, RESIZE_CUTEND); msotb = table.addTextButtonNoContent(y, 3, "filename", "FILENAME"); msal->addElement(msotb, 2, RESIZE_CUTEND); msotb = table.addTextButtonNoContent(y, 6, "remaining", "LEFT"); msal->addElement(msotb, 5, RESIZE_REMOVE); msotb = table.addTextButtonNoContent(y, 7, "speed", "SPEED"); msal->addElement(msotb, 6, RESIZE_REMOVE); msotb = table.addTextButtonNoContent(y, 8, "progress", "DONE"); msal->addElement(msotb, 7, RESIZE_REMOVE); y++; msal = table.addAdjustableLine(); msotb = table.addTextButtonNoContent(y, 1, "transferred", td.transferred); msal->addElement(msotb, 4, RESIZE_CUTEND); msotb = table.addTextButtonNoContent(y, 10, "filename", ts->getFile()); msal->addElement(msotb, 2, RESIZE_WITHLAST3); msotb = table.addTextButtonNoContent(y, 60, "remaining", td.timeremaining); msal->addElement(msotb, 5, RESIZE_REMOVE); msotb = table.addTextButtonNoContent(y, 40, "speed", td.speed); msal->addElement(msotb, 6, RESIZE_REMOVE); msotb = table.addTextButtonNoContent(y, 50, "progress", td.progress); msal->addElement(msotb, 7, RESIZE_REMOVE); table.adjustLines(col - 3); for (unsigned int i = 0; i < table.size(); i++) { std::shared_ptr<ResizableElement> re = std::static_pointer_cast<ResizableElement>(table.getElement(i)); if (re->isVisible()) { if (re->getIdentifier() == "transferred") { std::string labeltext = re->getLabelText(); bool highlight = table.getLineIndex(table.getAdjustableLine(re)) == 1; int charswithhighlight = highlight ? labeltext.length() * ts->getProgress() / 100 : 0; ui->printStr(re->getRow(), re->getCol(), labeltext.substr(0, charswithhighlight), true); ui->printStr(re->getRow(), re->getCol() + charswithhighlight, labeltext.substr(charswithhighlight)); } else { ui->printStr(re->getRow(), re->getCol(), re->getLabelText()); } } } } int ViewFileScreen::getCurrentScope() const { if (state == ViewFileState::VIEWING_EXTERNAL) { return KEYSCOPE_VIEWING_EXTERNAL; } if (state == ViewFileState::VIEWING_INTERNAL) { return KEYSCOPE_VIEWING_INTERNAL; } return KEYSCOPE_ALL; }
29.395062
158
0.635167
0cf47a1d8c1d0f3b8941f22a174d4530afc93b7d
1,063
hpp
C++
alignment/files/ReaderAgglomerateImpl.hpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
4
2015-07-03T11:59:54.000Z
2018-05-17T00:03:22.000Z
alignment/files/ReaderAgglomerateImpl.hpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
79
2015-06-29T18:07:21.000Z
2018-09-19T13:38:39.000Z
alignment/files/ReaderAgglomerateImpl.hpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
19
2015-06-23T08:43:29.000Z
2021-04-28T18:37:47.000Z
#ifndef _BLASR_READER_AGGLOMERATE_IMPL_HPP_ #define _BLASR_READER_AGGLOMERATE_IMPL_HPP_ template <typename T_Sequence> int ReaderAgglomerate::GetNext(T_Sequence &seq, int &randNum) { randNum = rand(); return GetNext(seq); } template <typename T_Sequence> int ReadChunkByNReads(ReaderAgglomerate &reader, std::vector<T_Sequence> &reads, int maxNReads) { T_Sequence seq; int nReads = 0; while (nReads < maxNReads) { if (reader.GetNext(seq)) { reads.push_back(seq); ++nReads; } else { break; } } return nReads; } template <typename T_Sequence> int ReadChunkBySize(ReaderAgglomerate &reader, std::vector<T_Sequence> &reads, int maxMemorySize) { T_Sequence seq; int nReads = 0; int totalStorage = 0; while (totalStorage < maxMemorySize) { if (reader.GetNext(seq)) { reads.push_back(seq); totalStorage += seq.GetStorageSize(); nReads++; } else { break; } } return nReads; } #endif
23.108696
97
0.627469
0cf54ce58b46f3ba5654eef039f7fb86939d2e7e
375
cpp
C++
GameEngine/CoreEngine/CoreEngine/src/DrawSceneOperation.cpp
mettaursp/SuddenlyGames
e2ff1c2771d4ca54824650e4f1a33a527536ca61
[ "Apache-2.0" ]
1
2021-01-17T13:05:20.000Z
2021-01-17T13:05:20.000Z
GameEngine/CoreEngine/CoreEngine/src/DrawSceneOperation.cpp
suddenly-games/SuddenlyGames
e2ff1c2771d4ca54824650e4f1a33a527536ca61
[ "Apache-2.0" ]
null
null
null
GameEngine/CoreEngine/CoreEngine/src/DrawSceneOperation.cpp
suddenly-games/SuddenlyGames
e2ff1c2771d4ca54824650e4f1a33a527536ca61
[ "Apache-2.0" ]
null
null
null
#include "DrawSceneOperation.h" #include "Graphics.h" namespace GraphicsEngine { void DrawSceneOperation::Configure(const std::shared_ptr<Scene>& scene) { CurrentScene = scene; } void DrawSceneOperation::Render() { Graphics::SetClearColor(RGBA(0x000000FF)); Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CurrentScene.lock()->Draw(); } }
18.75
72
0.749333
0cf5ce639d384338dff908e988df159507695c82
1,062
cc
C++
src/MsPhy.cc
CN-UPB/koi-simulator
ca4ddc5019f423a8e901ebed25b44dc5fa165cf0
[ "Apache-2.0" ]
null
null
null
src/MsPhy.cc
CN-UPB/koi-simulator
ca4ddc5019f423a8e901ebed25b44dc5fa165cf0
[ "Apache-2.0" ]
null
null
null
src/MsPhy.cc
CN-UPB/koi-simulator
ca4ddc5019f423a8e901ebed25b44dc5fa165cf0
[ "Apache-2.0" ]
null
null
null
/* * MsPhy.cc * * Created on: Jul 1, 2013 * Author: Sascha Schmerling */ #include "MsPhy.h" #include "KoiData_m.h" #include "MessageTypes.h" Define_Module(MsPhy); void MsPhy::initialize() { } void MsPhy::handleMessage(omnetpp::cMessage *msg) { //currently it only forward the packets if(msg->arrivedOn("fromMac")) { switch(msg->getKind()){ case MessageType::transInfo: send(msg,"toMsChannel"); break; case MessageType::koidata:{ KoiData *packet = dynamic_cast<KoiData*>(msg); switch(packet->getMessageDirection()){ case MessageDirection::up: send(msg, "toChannel"); break; case MessageDirection::d2dDown: case MessageDirection::d2dUp: send(msg,"toMs",packet->getDest()); break; } } break; case MessageType::longTermSinrEst: send(msg,"toMsChannel"); break; } if(msg->isName("MCS_FILE")){ send(msg,"toMsChannel"); } } else if(msg->arrivedOn("fromChannel")) { //ev << "Forwarding packet/packets to the mac layer" << endl; send(msg, "toMac"); } }
21.673469
63
0.63936
0cf7d3785efe69b943c01dc937f7f1bc78493d04
625
cpp
C++
Framework/Sources/o2/Utils/Memory/Allocators/StackAllocator.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
181
2015-12-09T08:53:36.000Z
2022-03-26T20:48:39.000Z
Framework/Sources/o2/Utils/Memory/Allocators/StackAllocator.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
29
2016-04-22T08:24:04.000Z
2022-03-06T07:06:28.000Z
Framework/Sources/o2/Utils/Memory/Allocators/StackAllocator.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
13
2018-04-24T17:12:04.000Z
2021-11-12T23:49:53.000Z
#include "o2/stdafx.h" #include "StackAllocator.h" namespace o2 { StackAllocator::StackAllocator(size_t capacity, IAllocator* baseAllocator /*= DefaultAllocator::GetInstance()*/): mBaseAllocator(baseAllocator) { mInitialCapacity = capacity; Initialize(); } StackAllocator::~StackAllocator() { Clear(); } void StackAllocator::Clear() { mBaseAllocator->Deallocate(mStack); mStack = nullptr; mStackEnd = nullptr; mTop = nullptr; } void StackAllocator::Initialize() { mStack = (std::byte*)mBaseAllocator->Allocate(mInitialCapacity); mTop = mStack; mStackEnd = mStack + mInitialCapacity; } }
18.939394
114
0.7168
0cf8c2b80d2677099864c77f7693963551133504
11,450
cpp
C++
back-end/llvm-translator/llvm-translator-qemu-2.3/tcg-llvm-offline/tcg-llvm-offline.cpp
zheli-1/crete-dev
a226c245f51347b88ba9a95448a694bf1997a080
[ "BSD-2-Clause-FreeBSD" ]
52
2016-11-03T06:48:16.000Z
2021-03-30T07:22:41.000Z
back-end/llvm-translator/llvm-translator-qemu-2.3/tcg-llvm-offline/tcg-llvm-offline.cpp
zheli-1/crete-dev
a226c245f51347b88ba9a95448a694bf1997a080
[ "BSD-2-Clause-FreeBSD" ]
46
2016-11-16T02:07:38.000Z
2020-04-01T06:17:33.000Z
back-end/llvm-translator/llvm-translator-qemu-2.3/tcg-llvm-offline/tcg-llvm-offline.cpp
zheli-1/crete-dev
a226c245f51347b88ba9a95448a694bf1997a080
[ "BSD-2-Clause-FreeBSD" ]
13
2016-11-06T00:41:27.000Z
2020-06-01T07:18:48.000Z
#include "tcg-llvm-offline.h" #include <boost/archive/binary_iarchive.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <string> #include <stdlib.h> #include <iostream> #include <fstream> #include "tcg.h" #if defined(TCG_LLVM_OFFLINE) #include "tcg-llvm.h" #endif // defined(TCG_LLVM_OFFLINE) using namespace std; extern "C" { #if !defined(TCG_LLVM_OFFLINE) struct TCGHelperInfo; extern const TCGHelperInfo all_helpers[]; extern TCGOpDef tcg_op_defs[]; uint64_t helpers_size = 0; uint64_t opc_defs_size = 0; #endif // !defined(TCG_LLVM_OFFLINE) } #if !defined(TCG_LLVM_OFFLINE) void TCGLLVMOfflineContext::dump_tlo_tb_pc(const uint64_t pc) { m_tlo_tb_pc.push_back(pc); } void TCGLLVMOfflineContext::dump_tcg_ctx(const TCGContext& tcg_ctx) { m_tcg_ctx.push_back(tcg_ctx); } void TCGLLVMOfflineContext::dump_tcg_temp(const vector<TCGTemp>& tcg_temp) { m_tcg_temps.push_back(tcg_temp); } void TCGLLVMOfflineContext::dump_tcg_helper_name(const TCGContext &tcg_ctx) { for (uint64_t i = 0; i < helpers_size; ++i) { uint64_t helper_addr = (uint64_t)all_helpers[i].func; string helper_name(all_helpers[i].name); assert(helper_addr); assert(!helper_name.empty()); m_helper_names.insert(make_pair(helper_addr, helper_name)); } } void TCGLLVMOfflineContext::dump_tlo_tb_inst_count(const uint64_t inst_count) { m_tlo_tb_inst_count.push_back(inst_count); } void TCGLLVMOfflineContext::dump_tbExecSequ(uint64_t pc, uint64_t unique_tb_num) { m_tbExecSequ.push_back(make_pair(pc, unique_tb_num)); } void TCGLLVMOfflineContext::dump_cpuState_size(uint64_t cpuState_size) { m_cpuState_size = cpuState_size; } #endif // #if !defined(TCG_LLVM_OFFLINE) uint64_t TCGLLVMOfflineContext::get_tlo_tb_pc(const uint64_t tb_index) const { return m_tlo_tb_pc[tb_index]; } const TCGContext& TCGLLVMOfflineContext::get_tcg_ctx(const uint64_t tb_index) const { return m_tcg_ctx[tb_index]; } const vector<TCGTemp>& TCGLLVMOfflineContext::get_tcg_temp(const uint64_t tb_index) const { return m_tcg_temps[tb_index]; } const map<uint64_t, string> TCGLLVMOfflineContext::get_helper_names() const { return m_helper_names; } uint64_t TCGLLVMOfflineContext::get_tlo_tb_inst_count(const uint64_t tb_index) const { return m_tlo_tb_inst_count[tb_index]; } vector<pair<uint64_t, uint64_t> > TCGLLVMOfflineContext::get_tbExecSequ() const { return m_tbExecSequ; } uint64_t TCGLLVMOfflineContext::get_cpuState_size() const { return m_cpuState_size; } void TCGLLVMOfflineContext::print_info() { cout << dec << "m_tlo_tb_pc.size() = " << m_tlo_tb_pc.size() << endl << "m_helper_names.size() = " << m_helper_names.size() << endl << endl; cout << dec << "sizeof (m_tlo_tb_pc) = " << sizeof(m_tlo_tb_pc)<< endl << "sizeof(m_helper_names) = " << sizeof(m_tcg_ctx) << "sizeof(m_tcg_temps) = " << sizeof(m_tcg_temps) << "sizeof(m_helper_names) = " << sizeof(m_helper_names) << endl << endl; cout << "pc values: "; uint64_t j = 0; for(vector<uint64_t>::iterator it = m_tlo_tb_pc.begin(); it != m_tlo_tb_pc.end(); ++it) { cout << "tb-" << dec << j++ << ": pc = 0x" << hex << (*it) << endl; } } void TCGLLVMOfflineContext::dump_verify() { assert(m_tlo_tb_pc.size() == m_tcg_ctx.size()); assert(m_tlo_tb_pc.size() == m_tcg_temps.size()); } uint64_t TCGLLVMOfflineContext::get_size() { return (uint64_t)m_tlo_tb_pc.size(); } #if defined(TCG_LLVM_OFFLINE) extern "C" { #include "config.h" #include "exec-all.h" } #include <boost/exception/all.hpp> #include <boost/filesystem.hpp> #include <sstream> #include <stdio.h> #define CRETE_DEBUG FILE *logfile; int loglevel; TCGContext tcg_ctx; uint16_t gen_opc_buf[OPC_BUF_SIZE]; TCGArg gen_opparam_buf[OPPARAM_BUF_SIZE]; target_ulong gen_opc_pc[OPC_BUF_SIZE]; uint16_t gen_opc_icount[OPC_BUF_SIZE]; uint8_t gen_opc_instr_start[OPC_BUF_SIZE]; std::string crete_data_dir; enum CreteFileType { CRETE_FILE_TYPE_LLVM_LIB, CRETE_FILE_TYPE_LLVM_TEMPLATE, }; static void crete_set_data_dir(const char* data_dir) { namespace fs = boost::filesystem; fs::path dpath(data_dir); if(!fs::exists(dpath)) { throw std::runtime_error("failed to find data directory: " + dpath.string()); } crete_data_dir = dpath.parent_path().string(); // crete_data_dir = "."; } static std::string crete_find_file(CreteFileType type, const char *name) { namespace fs = boost::filesystem; fs::path fpath = crete_data_dir; switch(type) { case CRETE_FILE_TYPE_LLVM_LIB: //#if defined(TARGET_X86_64) // fpath /= "../x86_64-softmmu/"; //#else // fpath /= "../i386-softmmu/"; //#endif // defined(TARGET_X86_64) break; case CRETE_FILE_TYPE_LLVM_TEMPLATE: // fpath /= "../runtime-dump/"; break; } fpath /= name; if(!fs::exists(fpath)) { throw std::runtime_error("failed to find file: " + fpath.string()); } return fpath.string(); } static void dump_tcg_op_defs() { char file_name[] = "translator-op-def.txt"; FILE *f = fopen(file_name, "w"); assert(f); for(uint32_t i = 0; i < tcg_op_defs_max; ++i) { fprintf(f, "opc = %d, name = %s\n", i, tcg_op_defs[i].name); } fclose(f); } const char * get_helper_name(uint64_t func_addr) { assert(tcg_llvm_ctx); string func_name = tcg_llvm_ctx->get_crete_helper_name(func_addr); char * ret = (char *) malloc(func_name.length() + 1); strcpy(ret, func_name.c_str()); cerr << "func_name = " << ret << ", func_addr = 0x" << hex << func_addr << ", ret = 0x" << (uint64_t) ret << endl; return ret; } void x86_llvm_translator() { namespace fs = boost::filesystem; #if defined(CRETE_DEBUG) cerr<< "this is the new main function from tcg-llvm-offline.\n" << endl; cerr<< "sizeof(TCGContext_temp) = 0x" << hex << sizeof(TCGContext_temp) << "sizeof(TCGArg) = 0x" << sizeof(TCGArg) << endl << ", OPPARAM_BUF_SIZE = 0x" << OPPARAM_BUF_SIZE << ", OPC_BUF_SIZE = 0x" << OPC_BUF_SIZE << ", MAX_OPC_PARAM = 0x" << MAX_OPC_PARAM << endl; dump_tcg_op_defs(); #endif //1. initialize llvm dependencies tcg_llvm_ctx = tcg_llvm_initialize(); assert(tcg_llvm_ctx); tcg_linkWithLibrary(tcg_llvm_ctx, crete_find_file(CRETE_FILE_TYPE_LLVM_LIB, "bc_crete_ops.bc").c_str()); #if defined(TARGET_X86_64) tcg_linkWithLibrary(tcg_llvm_ctx, crete_find_file(CRETE_FILE_TYPE_LLVM_LIB, "crete-qemu-2.3-op-helper-x86_64.bc").c_str()); #elif defined(TARGET_I386) tcg_linkWithLibrary(tcg_llvm_ctx, crete_find_file(CRETE_FILE_TYPE_LLVM_LIB, "crete-qemu-2.3-op-helper-i386.bc").c_str()); #else #error CRETE: Only I386 and x64 supported! #endif // defined(TARGET_X86_64) || defined(TARGET_I386) stringstream ss; uint64_t streamed_count = 0; for(;;) { ss.str(string()); ss << "dump_tcg_llvm_offline." << streamed_count++ << ".bin"; if(!fs::exists(ss.str())){ cerr << ss.str() << " not found\n"; break; } cerr << ss.str() << " being found\n"; //2. initialize tcg_llvm_ctx_offline TCGLLVMOfflineContext temp_tcg_llvm_offline_ctx; ifstream ifs(ss.str().c_str()); boost::archive::binary_iarchive ia(ifs); ia >> temp_tcg_llvm_offline_ctx; temp_tcg_llvm_offline_ctx.dump_verify(); #if defined(CRETE_DEBUG) temp_tcg_llvm_offline_ctx.print_info(); #endif if(streamed_count == 1){ tcg_llvm_ctx->crete_init_helper_names(temp_tcg_llvm_offline_ctx.get_helper_names()); tcg_llvm_ctx->crete_set_cpuState_size(temp_tcg_llvm_offline_ctx.get_cpuState_size()); } tcg_llvm_ctx->crete_add_tbExecSequ(temp_tcg_llvm_offline_ctx.get_tbExecSequ()); //3. Translate TranslationBlock temp_tb = {}; TCGContext *s = &tcg_ctx; for(uint64_t i = 0; i < temp_tcg_llvm_offline_ctx.get_size(); ++i) { //3.1 update temp_tb temp_tb.pc = (target_long)temp_tcg_llvm_offline_ctx.get_tlo_tb_pc(i); //3.2 update tcg_ctx const TCGContext temp_tcg_ctx = temp_tcg_llvm_offline_ctx.get_tcg_ctx(i); memcpy((void *)s, (void *)&temp_tcg_ctx, sizeof(TCGContext)); //3.3 update gen_opc_buf and gen_opparam_buf for(uint64_t j = 0; j < OPC_BUF_SIZE; ++j) { gen_opc_buf[j] = (uint16_t)temp_tcg_ctx.gen_op_buf[j].opc; } for(uint64_t j = 0; j < OPPARAM_BUF_SIZE; ++j) { gen_opparam_buf[j] = (TCGArg)temp_tcg_ctx.gen_opparam_buf[j]; } // 3.4 update tcg-temp const vector<TCGTemp> temp_tcg_temp = temp_tcg_llvm_offline_ctx.get_tcg_temp(i); assert( temp_tcg_temp.size() == s->nb_temps); for(uint64_t j = 0; j < s->nb_temps; ++j) s->temps[j].assign(temp_tcg_temp[j]); // generate offline-tbir.txt uint64_t tb_inst_count = temp_tcg_llvm_offline_ctx.get_tlo_tb_inst_count(i); static unsigned long long tbir_count = 0; char file_name[] = "offline-tbir.txt"; FILE *f = fopen(file_name, "a"); assert(f); fprintf(f, "qemu-ir-tb-%llu-%llu: tb_inst_count = %llu\n", tbir_count++, temp_tb.pc, tb_inst_count); tcg_dump_ops_file(s, f); fprintf(f, "\n"); fclose(f); //3.5 generate llvm bitcode cerr << "tcg_llvm_ctx->generateCode(s, &temp_tb) will be invoked." << endl; temp_tb.tcg_llvm_context = NULL; temp_tb.llvm_function = NULL; tcg_llvm_ctx->generateCode(s, &temp_tb); cerr<< "tcg_llvm_ctx->generateCode(s, &temp_tb) is done." << endl; assert(temp_tb.tcg_llvm_context != NULL); assert(temp_tb.llvm_function != NULL); } { //process crete_CPUStateSynctable(); ss.str(string()); ss << "dump_sync_cpu_states." << streamed_count-1 << ".bin"; tcg_llvm_ctx->generate_llvm_cpuStateSyncTables(ss.str()); } { //process dump_new_sync_memos(); ss.str(string()); ss << "dump_new_sync_memos." << streamed_count-1 << ".bin"; tcg_llvm_ctx->generate_llvm_MemorySyncTables(ss.str()); } } //4. generate main function tcg_llvm_ctx->generate_crete_main(); //5. Write out the translated llvm bitcode to file in the current folder fs::path bitcode_path = fs::current_path() / "dump_llvm_offline.bc"; tcg_llvm_ctx->writeBitCodeToFile(bitcode_path.string()); cerr << "offline translator is done.\n" << endl; //6. cleanup // delete tcg_llvm_offline_ctx; } int main(int argc, char **argv) { crete_set_data_dir(argv[0]); try { x86_llvm_translator(); } catch(...) { cerr << "Exception Info: \n" << boost::current_exception_diagnostic_information() << endl; return -1; } return 0; } #endif // defined(TCG_LLVM_OFFLINE)
27.261905
101
0.645764
0cfbaf0a959029b4d8b6049e04f2cde0db0e6df7
9,803
cpp
C++
C++GP16/final/client/Client.cpp
dhanak/competitive-coding
9e28298f8c646f169b7389d0ef20f99c5ef68f00
[ "MIT" ]
null
null
null
C++GP16/final/client/Client.cpp
dhanak/competitive-coding
9e28298f8c646f169b7389d0ef20f99c5ef68f00
[ "MIT" ]
null
null
null
C++GP16/final/client/Client.cpp
dhanak/competitive-coding
9e28298f8c646f169b7389d0ef20f99c5ef68f00
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Client.h" #include <sstream> #define SERVER_PORT 4242 CLIENT::CLIENT() { #ifdef WIN32 mConnectionSocket = INVALID_SOCKET; #else mConnectionSocket = -1; #endif mDistCache.LoadFromFile("distcache.bin"); } CLIENT::~CLIENT() { #ifdef WIN32 if( mConnectionSocket != INVALID_SOCKET ) { closesocket( mConnectionSocket ); } WSACleanup(); #else if (mConnectionSocket!=-1) { close(mConnectionSocket); } #endif } bool CLIENT::LinkDead() { #ifdef WIN32 return mConnectionSocket==INVALID_SOCKET; #else return mConnectionSocket == -1; #endif } bool CLIENT::Init() { #ifdef WIN32 static int wsa_startup_done = 0; if (!wsa_startup_done) { wsa_startup_done = 1; WSADATA WSAData; if( WSAStartup( 0x101,&WSAData ) != 0 ) { std::cout << "Error: Cannot start windows sockets!" << std::endl; return false; } } #endif #pragma warning(push) #pragma warning(disable:4996) unsigned long addr = inet_addr( strIPAddress.c_str() ); #pragma warning(pop) sockaddr_in ServerSocketAddress; ServerSocketAddress.sin_addr.s_addr = addr; ServerSocketAddress.sin_family = AF_INET; ServerSocketAddress.sin_port = htons( SERVER_PORT ); mConnectionSocket = socket( AF_INET, SOCK_STREAM, 0 ); #ifdef WIN32 if( mConnectionSocket == INVALID_SOCKET ) #else if (mConnectionSocket == -1 ) #endif { std::cout << "Error: Cannot open a socket!" << std::endl; return false; } if ( connect( mConnectionSocket,(struct sockaddr*)&ServerSocketAddress, sizeof( ServerSocketAddress ) ) ) { std::cout << "Error: Cannot connect to " << strIPAddress << "!" << std::endl; #ifdef WIN32 closesocket( mConnectionSocket ); #else close( mConnectionSocket ); #endif return false; } SendMessage("login " + GetPassword()); bReceivedFirstPing = false; return true; } void CLIENT::ConnectionClosed() { std::cout<<"Connection closed"<<std::endl; #ifdef WIN32 mConnectionSocket = INVALID_SOCKET; #else mConnectionSocket = -1; #endif } void CLIENT::SendMessage( std::string aMessage ) { if (LinkDead()) return; if (aMessage.length()==0) return; if (aMessage[aMessage.length()-1]!='\n') aMessage+="\n"; if (NeedDebugLog() && mDebugLog.is_open()) { mDebugLog<<"Sent: "<<aMessage; } int SentBytes = send( mConnectionSocket, aMessage.c_str(), int(aMessage.size()), 0 ); if (SentBytes!=aMessage.size()) { #ifdef WIN32 closesocket( mConnectionSocket ); #else close( mConnectionSocket ); #endif ConnectionClosed(); } } void CLIENT::ParsePlayers(std::vector<std::string> &ServerResponse) { Players.clear(); if (ServerResponse[0].substr(0, 7)=="players") { int count = atoi(ServerResponse[0].substr(8).c_str()); Players.resize(count); int r; for(r=0;r<count;r++) { std::stringstream ss; ss<<ServerResponse[r+1]; ss>>Players[r].id; ss>>Players[r].match_wins; ss>>Players[r].elo_points; char str[31]; ss.getline(str, 30); str[30]=0; Players[r].name = str; } } } void CLIENT::Run() { if (NeedDebugLog()) { mDebugLog.open("debug.log", std::ofstream::out | std::ofstream::app); } std::string strLastLineRemaining; std::vector<std::string> LastServerResponse; int last_connect_try_time = GetTickCount(); for(;;) { if (LinkDead()) { LastServerResponse.clear(); strLastLineRemaining = ""; Init(); } if (LinkDead()) { #ifdef WIN32 Sleep(1000); #else sleep(1); #endif continue; } const size_t ReceiveBufferSize = 1<<16; char ReceiveBuffer[ ReceiveBufferSize+1 ] = {0}; int ReceivedBytesCount = recv( mConnectionSocket, ReceiveBuffer, ReceiveBufferSize, 0 ); if( ReceivedBytesCount == 0 || ReceivedBytesCount == -1) { // connection is closed or failed #ifdef WIN32 closesocket( mConnectionSocket ); #else close( mConnectionSocket ); #endif ConnectionClosed(); continue; } ReceiveBuffer[ReceivedBytesCount]=0; char *line_start = ReceiveBuffer; for(;;) { char *s = strchr(line_start, '\n'); if (!s) { strLastLineRemaining = line_start; break; } else { std::string alma=strLastLineRemaining; *s=0; alma+=line_start; line_start = s+1; strLastLineRemaining = ""; if (alma=="fail") { std::cout<<"Login failed :("<<std::endl; } else if (alma=="ping") { SendMessage(std::string("pong")); if (!bReceivedFirstPing) { std::cout<<"Login OK"<<std::endl; SendMessage(std::string("opponent ")+GetPreferredOpponents()); bReceivedFirstPing = true; } else { time_t tt; time(&tt); struct tm *tm = localtime(&tt); char str[20]; sprintf(str, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec); std::cout<<"PING "<<str<<std::endl; } } else { LastServerResponse.push_back(alma); if (alma==".") { if (LastServerResponse.front().substr(0, 7)=="players") { ParsePlayers(LastServerResponse); } else { if (NeedDebugLog() && mDebugLog.is_open()) { for(unsigned int i=0;i<LastServerResponse.size();i++) mDebugLog<<LastServerResponse[i]<<std::endl; } std::string strResponse = HandleServerResponse(LastServerResponse); if (!strResponse.empty()) { SendMessage(strResponse); } } LastServerResponse.clear(); } } } } } } std::string CLIENT::HandleServerResponse(std::vector<std::string> &ServerResponse) { mParser.Parse(ServerResponse); if (mParser.w!=0 && mDistCache.mDistMap.empty()) { mDistCache.CreateFromParser(mParser); mDistCache.SaveToFile("distcache.bin"); } std::stringstream ss; if (mParser.match_result==PARSER::ONGOING) { ss << "tick "<<mParser.tick<<"\n"; Process(); ss<<command_buffer.str(); for(std::map<int, CLIENT::CMD>::iterator it=mUnitTarget.begin();it!=mUnitTarget.end();) { bool cmd_done = false; MAP_OBJECT *q = NULL; for(std::vector<MAP_OBJECT>::iterator p=mParser.Units.begin(); p!=mParser.Units.end();p++) { if (p->id==it->first) { q=&*p; break; } } if (q==NULL) { cmd_done = true; } else if (it->second.c == CLIENT::CMD_MOVE) { if (q->pos==it->second.pos) cmd_done = true; else { POS t = mDistCache.GetNextTowards(q->pos, it->second.pos); if (!t.IsValid()) { cmd_done = true; } else { if (t==it->second.pos) cmd_done = true; ss<<"queen_move "<<it->first<<" "<<t.x<<" "<<t.y<<"\n"; } } } else if (it->second.c == CLIENT::CMD_SPAWN) { bool do_spawn = false; if (q->pos==it->second.pos) do_spawn = true; else { POS t = mDistCache.GetNextTowards(q->pos, it->second.pos); if (!t.IsValid()) cmd_done = true; else if (t==it->second.pos) do_spawn = true; else { ss<<"queen_move "<<it->first<<" "<<t.x<<" "<<t.y<<"\n"; } } if (do_spawn) { ss<<"queen_spawn "<<it->first<<" "<<it->second.pos.x<<" "<<it->second.pos.y<<"\n"; cmd_done = true; } } else if (it->second.c == CLIENT::CMD_ATTACK) { MAP_OBJECT *t = NULL; POS t_pos; std::vector<MAP_OBJECT>::iterator p; for(p=mParser.Units.begin(); p!=mParser.Units.end();p++) { if (p->id==it->second.target_id) { t=&*p; t_pos = p->pos; break; } } if (t==NULL) for(p=mParser.CreepTumors.begin();p!=mParser.CreepTumors.end();p++) { if (p->id==it->second.target_id) { t=&*p; t_pos=p->pos; break; } } if (t==NULL) { if (mParser.EnemyHatchery.id==it->second.target_id) { t=&mParser.EnemyHatchery; t_pos=mParser.EnemyHatchery.pos; // find closest point of hatchery: int i; for (i = 0; i<HATCHERY_SIZE - 1; i++) if (q->pos.y>t_pos.y) t_pos.y++; for (i = 0; i<HATCHERY_SIZE - 1; i++) if (q->pos.x>t_pos.x) t_pos.x++; } } if (t==NULL) cmd_done = true; else { bool do_attack = false; if (q->pos==t_pos) do_attack = true; else { POS next_pos = mDistCache.GetNextTowards(q->pos, t_pos); if (!next_pos.IsValid()) { cmd_done=true; } else if (next_pos==t_pos) do_attack = true; else { ss<<"queen_move "<<it->first<<" "<<next_pos.x<<" "<<next_pos.y<<"\n"; } } if (do_attack) ss<<"queen_attack "<<it->first<<" "<<it->second.target_id<<"\n"; } } std::map<int, CLIENT::CMD>::iterator it2=it; it2++; if (cmd_done) { mUnitTarget.erase(it); } it=it2; } command_buffer.str(std::string()); ss<<"."; } else { mUnitTarget.clear(); MatchEnd(); ss<<"."; } return ss.str(); } int main(int argc, char* argv[]) { std::cout.sync_with_stdio(false); std::string server_address; if (argc<2) { server_address = "10.112.1.185"; std::cout<<"using default server address: " + server_address <<std::endl; } else { server_address = argv[1]; } CLIENT *pClient = CreateClient(); /* for debugging: */ std::ifstream debug_file("test.txt"); if (debug_file.is_open()) { std::string line; std::vector<std::string> full; while (std::getline(debug_file, line)) { full.push_back(line); } std::string resp = pClient->DebugResponse(full); std::cout<<"response: "<<resp <<std::endl; } /**/ pClient->strIPAddress = server_address; if (!pClient->Init()) { std::cout<<"Connection failed"<<std::endl; } else { pClient->Run(); } delete pClient; return 0; }
23.678744
154
0.590227
0cfccad6f6a10830ec180e7329b70e016084a9ec
241
hpp
C++
corex/src/corex/core/events/game_events.hpp
seanballais/gwo-visualization
470561c603236d6a858b78a8585fd0bae71612a5
[ "MIT" ]
null
null
null
corex/src/corex/core/events/game_events.hpp
seanballais/gwo-visualization
470561c603236d6a858b78a8585fd0bae71612a5
[ "MIT" ]
null
null
null
corex/src/corex/core/events/game_events.hpp
seanballais/gwo-visualization
470561c603236d6a858b78a8585fd0bae71612a5
[ "MIT" ]
null
null
null
#ifndef COREX_CORE_EVENTS_GAME_EVENTS_HPP #define COREX_CORE_EVENTS_GAME_EVENTS_HPP namespace corex::core { struct GameTimeWarpEvent { float timeWarpFactor; }; struct GameTimerStatusEvent { bool isPlaying; }; } #endif
13.388889
41
0.755187
0cfee70cd62e13b50b5c0a5ed9446c6efa6825b6
490
cpp
C++
cec2019comp100digit/eval_func.cpp
dmolina/cec2019comp100digit
460ac41b273878e2c798522d161b58ee2ed0278f
[ "MIT" ]
12
2019-04-10T15:12:46.000Z
2022-03-03T09:34:38.000Z
cec2019comp100digit/eval_func.cpp
dmolina/cec2019comp100digit
460ac41b273878e2c798522d161b58ee2ed0278f
[ "MIT" ]
3
2018-12-21T08:39:26.000Z
2022-01-10T11:50:09.000Z
cec2019comp100digit/eval_func.cpp
dmolina/cec2019comp100digit
460ac41b273878e2c798522d161b58ee2ed0278f
[ "MIT" ]
2
2020-12-18T11:40:01.000Z
2021-07-15T14:07:03.000Z
#define _MAIN #include "cec19_func.h" #include <stdlib.h> static int _funcID; static int _dim; void set_func(int funcID, int dim) { _funcID = funcID; _dim = dim; ini_flag = 0; } double eval_sol(double *x) { double fit; cec19_test_func(x, &fit, _dim, 1, _funcID); return fit; } void free_func(void) { free(z); free(M); free(OShift); free(x_bound); // Init to allow set_func again z = nullptr; M = nullptr; OShift = nullptr; x_bound = nullptr; ini_flag = 0; }
15.3125
45
0.657143
490922b8449248ae20f988401452233f96ebe02d
922
hpp
C++
src/app/validator-manager.hpp
mimo31/fluid-sim
481c3e5a5456350bccb8795aa119a3487dff3021
[ "MIT" ]
1
2020-11-26T17:20:28.000Z
2020-11-26T17:20:28.000Z
src/app/validator-manager.hpp
mimo31/brandy0
481c3e5a5456350bccb8795aa119a3487dff3021
[ "MIT" ]
null
null
null
src/app/validator-manager.hpp
mimo31/brandy0
481c3e5a5456350bccb8795aa119a3487dff3021
[ "MIT" ]
null
null
null
/** * validator-manager.hpp * * Author: Viktor Fukala * Created on 2021/01/16 */ #ifndef VALIDATOR_MANAGER_HPP #define VALIDATOR_MANAGER_HPP #include "func.hpp" #include "vec.hpp" namespace brandy0 { /** * Container for arbitrarily many bool(void) callbacks. * Callbacks (a.k.a. validators) can be dynamically added and it can be queries whether they all evaluate to true. * Meant primarily for user input validation -- each entry can have its validator and the form can be submitted only if all validators evaluate to true. */ class ValidatorManager { private: /// Vector of all registered validators vec<BoolFunc> validators; public: /** * Registers a new validator * @param validator validator to register */ void plug(const BoolFunc& validator); /** * @return true iff all currently registered validators evaluate to true */ bool isAllValid() const; }; } #endif // VALIDATOR_MANAGER_HPP
22.487805
152
0.736443
490a0b2c5d3f200f97d3a3bb3d45a66064b53d8d
2,408
cpp
C++
utilities/Socket.cpp
JKowalsky/ftp-client
daa81b546b399907cdd77bc639ad61a3b17b5939
[ "MIT" ]
null
null
null
utilities/Socket.cpp
JKowalsky/ftp-client
daa81b546b399907cdd77bc639ad61a3b17b5939
[ "MIT" ]
null
null
null
utilities/Socket.cpp
JKowalsky/ftp-client
daa81b546b399907cdd77bc639ad61a3b17b5939
[ "MIT" ]
null
null
null
/* * File: Socket.cpp * Author: kowalsky * * Created on November 30, 2014, 4:49 PM */ #include "Socket.h" Socket::Socket(int port) : port(port), clientFd(NULL_FD), serverFd(NULL_FD) { } Socket::~Socket() { if (clientFd != NULL_FD) close(clientFd); if (serverFd != NULL_FD) close(serverFd); } int Socket::getClientSocket(char ipName[]) { return getClientSocket(ipName, 0, false); } int Socket::getClientSocket(char ipName[], int sndbufsize, bool nodelay) { // Get the host entry corresponding to ipName struct hostent* host = gethostbyname(ipName); if (host == NULL) { perror("Cannot find hostname."); return NULL_FD; } // Fill in the structure "sendSockAddr" with the address of the server. sockaddr_in sendSockAddr; bzero((char*) &sendSockAddr, sizeof ( sendSockAddr)); sendSockAddr.sin_family = AF_INET; // Address Family Internet sendSockAddr.sin_addr.s_addr = inet_addr(inet_ntoa(*(struct in_addr*) *host->h_addr_list)); sendSockAddr.sin_port = htons(port); // Open a TCP socket (an Internet strem socket). if ((clientFd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("Cannot open a client TCP socket."); return NULL_FD; } // Set the rcvbuf option if (sndbufsize > 0) { cout << sndbufsize << endl; if (setsockopt(clientFd, SOL_SOCKET, SO_SNDBUF, (char *) &sndbufsize, sizeof ( sndbufsize)) < 0) { perror("setsockopt SO_SNDBUF failed"); return NULL_FD; } } // Set the nodelay option if (nodelay == true) { int on = 1; if (setsockopt(clientFd, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof ( int)) < 0) { perror("setsockopt TCP_NODELAY failed"); return NULL_FD; } } // Connect to the server. while (connect(clientFd, (sockaddr*) & sendSockAddr, sizeof ( sendSockAddr)) < 0); // Connected return clientFd; } int Socket::pollRecvFrom() { struct pollfd pfd[1]; pfd[0].fd = clientFd; // declare I'll check the data availability of sd pfd[0].events = POLLRDNORM; // declare I'm interested in only reading from sd // check it for 2 seconds and return a positive number if sd is readable, // otherwise return 0 or a negative number return poll( pfd, 1, 1000 ); }
27.678161
79
0.616694
490b9fb710f1e9195b51c1e5af31415cecfc6a0f
1,996
cpp
C++
test/test_crossentropyloss_layer.cpp
sdadia/deep-learning-and-optimization
b44be79de116e2d4b203452a161641519f18f580
[ "MIT" ]
1
2018-10-02T15:29:14.000Z
2018-10-02T15:29:14.000Z
test/test_crossentropyloss_layer.cpp
sdadia/deep-learning-and-optimization
b44be79de116e2d4b203452a161641519f18f580
[ "MIT" ]
null
null
null
test/test_crossentropyloss_layer.cpp
sdadia/deep-learning-and-optimization
b44be79de116e2d4b203452a161641519f18f580
[ "MIT" ]
null
null
null
#include "crossentropyloss_layer.hpp" #include "common.hpp" #include "gtest/gtest.h" #include "gmock/gmock.h" #include <glog/logging.h> TEST(CrossEntropyLossLayer, CheckNumInputs) { // if zero inputs, then a problem will occour std::vector<dtensor_t> input(2); std::vector<dtensor_t> labels(2); dpl::CrossEntropyLossLayer p; p.setUp(input, labels); } TEST(CrossEntropyLossLayer, forward) { // input, label, and true value dtensor_t p1{123, 456, 789}, p2{1, -2, 0}, p3 {0.5,-1, 0}; dtensor_t l1{1,0,0}, l2{0,1,0}, l3{0,0,1}; dtensor_t t1{0.0,0.0,1.0}, t2{0.705384,0.035119, 0.259496}, t3{0.546549,0.121951,0.331498}; std::vector<dtensor_t> input{p1,p2,p3}, labels{l1,l2,l3}, true_values{t1,t2,t3}; dpl::CrossEntropyLossLayer p; p.setUp(input, labels); auto output = p.forward(); for(uint_t i=0; i<output.size(); i++) { auto output_raw_data = output[i].raw_data(); auto true_value_raw_data = true_values[i].raw_data(); EXPECT_TRUE(AreFloatingPointArraysEqual(output_raw_data, true_value_raw_data, output[i].size())); } } TEST(CrossEntropyLossLayer, backward) { // input, label, and true value dtensor_t p1{123, 456, 789}, p2{1, -2, 0}, p3 {0.5,-1, 0}; dtensor_t l1{1,0,0}, l2{0,1,0}, l3{0,0,1}; dtensor_t t1{0.0,0.0,1.0}, t2{0.705384,0.035119, 0.259496}, t3{0.546549,0.121951,0.331498}; //dtensor_t g1{} std::vector<dtensor_t> input{p1,p2,p3}, labels{l1,l2,l3}, true_values{t1,t2,t3}; dpl::CrossEntropyLossLayer p; p.setUp(input, labels); auto output = p.forward(); for(uint_t i=0; i<output.size(); i++) { auto output_raw_data = output[i].raw_data(); auto true_value_raw_data = true_values[i].raw_data(); EXPECT_TRUE(AreFloatingPointArraysEqual(output_raw_data, true_value_raw_data, output[i].size())); } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
25.922078
105
0.648798
490c04aea1c0d4220a42e522bea93931f368310e
8,164
cpp
C++
src/windows/SQLite3-WinRT/SQLite3/Statement.cpp
Crodaycat/react-native-sqlcipher-storage
9d321a9c88a7fa373a2cb954b0bd85a8e7c590da
[ "MIT" ]
29
2016-11-15T10:29:06.000Z
2021-10-09T08:20:26.000Z
src/windows/SQLite3-WinRT/SQLite3/Statement.cpp
Crodaycat/react-native-sqlcipher-storage
9d321a9c88a7fa373a2cb954b0bd85a8e7c590da
[ "MIT" ]
16
2015-01-27T21:45:38.000Z
2018-10-19T09:47:31.000Z
src/windows/SQLite3-WinRT/SQLite3/Statement.cpp
Crodaycat/react-native-sqlcipher-storage
9d321a9c88a7fa373a2cb954b0bd85a8e7c590da
[ "MIT" ]
29
2016-06-13T19:15:18.000Z
2021-02-24T14:29:27.000Z
#include <assert.h> #include <collection.h> #include <sstream> #include <iomanip> #include <ppl.h> #include <ppltasks.h> #include <windows.storage.h> #include <robuffer.h> #include "Statement.h" #include "Database.h" namespace SQLite3 { StatementPtr Statement::Prepare(sqlite3* sqlite, Platform::String^ sql) { sqlite3_stmt* statement; int ret = sqlite3_prepare16(sqlite, sql->Data(), -1, &statement, 0); if (ret != SQLITE_OK) { sqlite3_finalize(statement); throwSQLiteError(ret, sql); } return StatementPtr(new Statement(statement)); } Statement::Statement(sqlite3_stmt* statement) : statement(statement) { } Statement::~Statement() { sqlite3_finalize(statement); } void Statement::Bind(const SafeParameterVector& params) { for (SafeParameterVector::size_type i = 0; i < params.size(); ++i) { BindParameter(static_cast<int>(i + 1), params[i]); } } void Statement::Bind(ParameterMap^ params) { if (!params) { return; } for (int i = 0; i < BindParameterCount(); ++i) { int index = i + 1; auto nameWithoutPrefix = BindParameterName(index).substr(1); auto name = ref new Platform::String(nameWithoutPrefix.data()); if (params->HasKey(name)) { BindParameter(index, params->Lookup(name)); } } } static inline uint64 FoundationTimeToUnixCompatible(Windows::Foundation::DateTime foundationTime) { return (foundationTime.UniversalTime / 10000) - 11644473600000; } void Statement::BindParameter(int index, Platform::Object^ value) { int result; if (value == nullptr) { result = sqlite3_bind_null(statement, index); } else { auto typeCode = Platform::Type::GetTypeCode(value->GetType()); switch (typeCode) { case Platform::TypeCode::DateTime: result = sqlite3_bind_int64(statement, index, FoundationTimeToUnixCompatible(static_cast<Windows::Foundation::DateTime>(value))); break; case Platform::TypeCode::Double: result = sqlite3_bind_double(statement, index, static_cast<double>(value)); break; case Platform::TypeCode::String: result = sqlite3_bind_text16(statement, index, static_cast<Platform::String^>(value)->Data(), -1, SQLITE_TRANSIENT); break; case Platform::TypeCode::Boolean: result = sqlite3_bind_int(statement, index, static_cast<Platform::Boolean>(value) ? 1 : 0); break; case Platform::TypeCode::Int8: case Platform::TypeCode::Int16: case Platform::TypeCode::Int32: case Platform::TypeCode::UInt8: case Platform::TypeCode::UInt16: case Platform::TypeCode::UInt32: result = sqlite3_bind_int(statement, index, static_cast<int>(value)); break; case Platform::TypeCode::Int64: case Platform::TypeCode::UInt64: result = sqlite3_bind_int64(statement, index, static_cast<int64>(value)); break; case Platform::TypeCode::Object: { auto buffer= winrt_as<ABI::Windows::Storage::Streams::IBuffer>(value); if (buffer) { auto byteBuffer= winrt_as<Windows::Storage::Streams::IBufferByteAccess>(value); byte* blob; byteBuffer->Buffer(&blob); uint32 length; buffer->get_Length(&length); result = sqlite3_bind_blob(statement, index, blob, length, 0); } else { result = SQLITE_MISMATCH; } } break; default: result = SQLITE_MISMATCH; } } if (result != SQLITE_OK) { std::wostringstream message; message << L"Could not bind parameter " << index << L" to " << value->ToString()->Data() << L" because it has a wrong type " << value->GetType()->FullName->Data(); throwSQLiteError(result, ref new Platform::String(message.str().c_str())); } } int Statement::BindParameterCount() { return sqlite3_bind_parameter_count(statement); } std::wstring Statement::BindParameterName(int index) { return ToWString(sqlite3_bind_parameter_name(statement, index)); } void Statement::Run() { Step(); } Platform::String^ Statement::One() { std::wostringstream result; if (Step() == SQLITE_ROW) { GetRow(result); return ref new Platform::String(result.str().c_str()); } else { return nullptr; } } Platform::String^ Statement::All() { std::wostringstream result; result << L"["; auto stepResult = Step(); bool hasData = (stepResult == SQLITE_ROW); while (stepResult == SQLITE_ROW) { GetRow(result); result << L","; stepResult = Step(); } if (hasData) { std::streamoff pos = result.tellp(); result.seekp(pos-1); } result << L"]"; return ref new Platform::String(result.str().c_str()); } void Statement::Each(EachCallback^ callback, Windows::UI::Core::CoreDispatcher^ dispatcher) { while (Step() == SQLITE_ROW) { std::wostringstream output; GetRow(output); auto row = ref new Platform::String(output.str().c_str()); auto callbackTask = Concurrency::task<void>( dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([row, callback]() { callback(row); })) ); callbackTask.get(); } } int Statement::Step() { int ret = sqlite3_step(statement); if (ret != SQLITE_ROW && ret != SQLITE_DONE) { throwSQLiteError(ret, ref new Platform::String(L"Could not step statement")); } return ret; } bool Statement::ReadOnly() const { return sqlite3_stmt_readonly(statement) != 0; } void writeEscaped(const std::wstring& s, std::wostringstream& out) { out << L'"'; for (std::wstring::const_iterator i = s.begin(), end = s.end(); i != end; ++i) { wchar_t c = *i; if (L' ' <= c && c <= L'~' && c != L'\\' && c != L'"') { out << *i; } else { out << L'\\'; switch(c) { case L'"': out << L'"'; break; case L'\\': out << L'\\'; break; case L'\t': out << L't'; break; case L'\r': out << L'r'; break; case L'\n': out << L'n'; break; default: out << L'u'; out << std::setw(4) << std::setfill(L'0') << std::hex << (WORD)c; } } } out << L'"'; } void Statement::GetRow(std::wostringstream& outstream) { outstream << L'{'; int columnCount = ColumnCount(); for (int i = 0; i < columnCount; ++i) { auto colName = static_cast<const wchar_t*>(sqlite3_column_name16(statement, i)); auto colType = ColumnType(i); outstream << L'"' << colName << L"\":"; switch (colType) { case SQLITE_TEXT: { auto colValue = static_cast<const wchar_t*>(sqlite3_column_text16(statement, i)); writeEscaped(colValue, outstream); } break; case SQLITE_INTEGER: case SQLITE_FLOAT: { auto colValue = static_cast<const wchar_t*>(sqlite3_column_text16(statement, i)); outstream << colValue; } break; case SQLITE_BLOB: { auto blob = (byte*)sqlite3_column_blob(statement, i); const int blobSize = sqlite3_column_bytes(statement, i); Platform::ArrayReference<uint8> blobArray(blob, blobSize); using Windows::Security::Cryptography::CryptographicBuffer; auto base64Text = CryptographicBuffer::EncodeToBase64String(CryptographicBuffer::CreateFromByteArray(blobArray)); outstream << L'"' << base64Text->Data() << L'"'; } break; case SQLITE_NULL: outstream << L"null"; break; } outstream << L','; } std::streamoff pos = outstream.tellp(); outstream.seekp(pos - 1l); outstream << L'}'; } int Statement::ColumnCount() { return sqlite3_column_count(statement); } int Statement::ColumnType(int index) { return sqlite3_column_type(statement, index); } }
31.041825
137
0.599584
490ead04603ff489afc8802626c59b089b8e5a47
2,791
cpp
C++
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_RobotoCondensed_Bold_42_4bpp.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_RobotoCondensed_Bold_42_4bpp.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_RobotoCondensed_Bold_42_4bpp.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
#include <touchgfx/Font.hpp> #ifndef NO_USING_NAMESPACE_TOUCHGFX using namespace touchgfx; #endif FONT_LOCATION_FLASH_PRAGMA KEEP extern const touchgfx::GlyphNode glyphs_RobotoCondensed_Bold_42_4bpp[] FONT_LOCATION_FLASH_ATTRIBUTE = { { 0, 2, 0, 0, 0, 0, 1, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 0, 48, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 300, 49, 12, 30, 30, 3, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 480, 50, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 780, 51, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 1080, 52, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 1380, 53, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 1680, 54, 18, 30, 30, 2, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 1950, 55, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 2250, 56, 18, 30, 30, 2, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 2520, 57, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 2820, 65, 25, 30, 30, 0, 25, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 3210, 66, 20, 30, 30, 2, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 3510, 67, 22, 30, 30, 1, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 3840, 68, 20, 30, 30, 2, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 4140, 69, 18, 30, 30, 2, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 4410, 70, 17, 30, 30, 2, 20, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 4680, 71, 22, 30, 30, 1, 25, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 5010, 74, 19, 30, 30, 0, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 5310, 76, 18, 30, 30, 2, 20, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 5580, 77, 28, 30, 30, 2, 32, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 6000, 78, 22, 30, 30, 2, 26, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 6330, 79, 23, 30, 30, 1, 25, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 6690, 80, 21, 30, 30, 2, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 7020, 82, 21, 30, 30, 2, 23, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 7350, 83, 21, 30, 30, 1, 23, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 7680, 84, 21, 30, 30, 1, 23, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 8010, 85, 20, 30, 30, 2, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 8310, 86, 24, 30, 30, 0, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 8670, 89, 23, 30, 30, 0, 23, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0} };
66.452381
109
0.58402
490fbeba6c6750fd5f4936f931923bec5b4fc099
1,940
hpp
C++
caffe/include/caffe/layers/sparse_hypercolumn_extractor_layer.hpp
gustavla/autocolorizer
79d4ce1054d35c06bdfcc93236b71e161e082ebb
[ "BSD-3-Clause" ]
234
2016-04-04T15:12:24.000Z
2022-03-14T12:55:09.000Z
caffe/include/caffe/layers/sparse_hypercolumn_extractor_layer.hpp
TrinhQuocNguyen/autocolorize
79d4ce1054d35c06bdfcc93236b71e161e082ebb
[ "BSD-3-Clause" ]
20
2016-04-05T12:44:04.000Z
2022-02-22T06:02:17.000Z
caffe/include/caffe/layers/sparse_hypercolumn_extractor_layer.hpp
TrinhQuocNguyen/autocolorize
79d4ce1054d35c06bdfcc93236b71e161e082ebb
[ "BSD-3-Clause" ]
71
2016-07-12T15:28:16.000Z
2021-12-16T12:22:57.000Z
#ifndef CAFFE_SPARSE_HYPERCOLUMN_LAYER_HPP #define CAFFE_SPARSE_HYPERCOLUMN_LAYER_HPP #include <string> #include <utility> #include <vector> #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/layer.hpp" namespace caffe { /** * \ingroup ttic * @brief This extracts locations of hypercolumns. It should be faster, and * more importantly use less memory, than the original, since you do not need * separate upscaling layers. It does the bilinear upscaling by itself. * * @author Gustav Larsson */ template <typename Dtype> class SparseHypercolumnExtractorLayer : public Layer<Dtype> { public: explicit SparseHypercolumnExtractorLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "SparseHypercolumnExtractor"; } virtual inline int MinBottomBlobs() const { return 2; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); int num_layers_; int num_channels_; // in the entire hypercolumn int num_locations_; vector<Dtype> offsets_h_; vector<Dtype> offsets_w_; vector<Dtype> scales_; vector<Dtype> activation_mults_; vector<int> channel_offsets_; }; } // namespace caffe #endif // CAFFE_SPARSE_HYPERCOLUMN_LAYER_HPP
32.333333
82
0.737629
49108ddf6d4c6c7194aeb7664774efa5285a70e3
2,316
cpp
C++
src/level/button/pressureButton.cpp
kirbyUK/duo
85155fcce81086ea39593750f042a8f518f09804
[ "MIT" ]
null
null
null
src/level/button/pressureButton.cpp
kirbyUK/duo
85155fcce81086ea39593750f042a8f518f09804
[ "MIT" ]
null
null
null
src/level/button/pressureButton.cpp
kirbyUK/duo
85155fcce81086ea39593750f042a8f518f09804
[ "MIT" ]
null
null
null
/* Copyright (c) 2014, Alex Kerr * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "pressureButton.h" #include <iostream> #ifndef ASSETS #define ASSETS "./assets" #endif #ifdef _WIN32 const std::string PressureButton::BUTTON_PATHS[2] = { (((std::string)ASSETS) + ((std::string)"\\sprites\\p_button.png")), (((std::string)ASSETS) + ((std::string)"\\sprites\\p_button2.png")) }; #else const std::string PressureButton::BUTTON_PATHS[2] = { (((std::string)ASSETS) + ((std::string)"/sprites/p_button.png")), (((std::string)ASSETS) + ((std::string)"/sprites/p_button2.png")) }; #endif sf::Image PressureButton::_images[2]; //The colour to remove in the images and replace with transparency: const sf::Color PressureButton::COLOUR_MASK(0, 255, 0); bool PressureButton::init() { for(unsigned int i = 0; i < 2; i++) { if(! _images[i].loadFromFile(BUTTON_PATHS[i])) { std::cerr << "Unable to load '" << BUTTON_PATHS[i] << "'.\n"; return false; } else //If it loads fine, remove the green background: _images[i].createMaskFromColor(COLOUR_MASK); } return true; } PressureButton::PressureButton(sf::Vector2f buttonPos, sf::Vector2f blockPos, Block* block) { _texture.loadFromImage(_images[0]); _sprite.setTexture(_texture); _sprite.setPosition(buttonPos); _block = block; _blockPos[0] = _block->_shape.getPosition(); _blockPos[1] = blockPos; } void PressureButton::_handlePressed(bool isPlayerOnTop) { if(isPlayerOnTop) { _block->_shape.setPosition(_blockPos[1]); _texture.update(_images[1]); } else { _block->_shape.setPosition(_blockPos[0]); _texture.update(_images[0]); } }
28.592593
78
0.71848
491093ebf494376d05903c57abe5e9bd5b9b74f5
1,476
cpp
C++
Codes/CodeForces/E/1265E_2.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
3
2019-07-20T07:26:31.000Z
2020-08-06T09:31:09.000Z
Codes/CodeForces/E/1265E_2.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
null
null
null
Codes/CodeForces/E/1265E_2.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
4
2019-06-20T18:43:32.000Z
2020-10-07T16:45:23.000Z
/* Author : Qazi Fahim Farhan (@fahimfarhan) */ /* May the CodeForces be with you! */ #include <iostream> // #include <sstream> // #include <cstdio> // #include <cmath> // #include <cstring> // #include <cctype> // #include <string> #include <vector> // #include <list> // #include <set> // #include <map> // #include <queue> // #include <stack> // #include <algorithm> // #include <functional> #include <iomanip> // std::setprecision using namespace std; #define PI 2*acos(0) //typedef long long ll ll; #define ll long long int // other popular ones=> ll64_t, ull64_t => use for 10^18 const ll MOD = 119 << 23 | 1; ll inv(ll input){ ll ret = 1; ll k = MOD - 2; ll a = input; while (k) { /* code */ if( (k&1) == 1){ ret = ((ret * a) % MOD); } a = ((a*a) % MOD); k = k>>1; } return ret; } int main(int argc, char const *argv[]) { /* code */ // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); /* std::cout << std::fixed; std::cout << std::setprecision(10); cout << num1 << endl; */ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll n, m; m = inv(100); cin>>n; ll p[n+1]; for(ll i=0; i<n; i++){ cin>>p[i]; p[i] = ((p[i] * m)%MOD); } ll E = inv(p[0]); for(ll i=1; i<n; i++){ E = (E+1)*inv(p[i]); E = E%MOD; } cout<<E<<"\n"; return 0; }
17.783133
56
0.496612
49154a3892486e9327bda6161d73774316183cd2
6,039
cpp
C++
qtmultimedia/src/plugins/android/src/mediacapture/qandroidcameraimageprocessingcontrol.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qtmultimedia/src/plugins/android/src/mediacapture/qandroidcameraimageprocessingcontrol.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qtmultimedia/src/plugins/android/src/mediacapture/qandroidcameraimageprocessingcontrol.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qandroidcameraimageprocessingcontrol.h" #include "qandroidcamerasession.h" #include "androidcamera.h" QT_BEGIN_NAMESPACE QAndroidCameraImageProcessingControl::QAndroidCameraImageProcessingControl(QAndroidCameraSession *session) : QCameraImageProcessingControl() , m_session(session) , m_whiteBalanceMode(QCameraImageProcessing::WhiteBalanceAuto) { connect(m_session, SIGNAL(opened()), this, SLOT(onCameraOpened())); } bool QAndroidCameraImageProcessingControl::isParameterSupported(ProcessingParameter parameter) const { return parameter == QCameraImageProcessingControl::WhiteBalancePreset && m_session->camera() && !m_supportedWhiteBalanceModes.isEmpty(); } bool QAndroidCameraImageProcessingControl::isParameterValueSupported(ProcessingParameter parameter, const QVariant &value) const { return parameter == QCameraImageProcessingControl::WhiteBalancePreset && m_session->camera() && m_supportedWhiteBalanceModes.contains(value.value<QCameraImageProcessing::WhiteBalanceMode>()); } QVariant QAndroidCameraImageProcessingControl::parameter(ProcessingParameter parameter) const { if (parameter != QCameraImageProcessingControl::WhiteBalancePreset) return QVariant(); return QVariant::fromValue(m_whiteBalanceMode); } void QAndroidCameraImageProcessingControl::setParameter(ProcessingParameter parameter, const QVariant &value) { if (parameter != QCameraImageProcessingControl::WhiteBalancePreset) return; QCameraImageProcessing::WhiteBalanceMode mode = value.value<QCameraImageProcessing::WhiteBalanceMode>(); if (m_session->camera()) setWhiteBalanceModeHelper(mode); else m_whiteBalanceMode = mode; } void QAndroidCameraImageProcessingControl::setWhiteBalanceModeHelper(QCameraImageProcessing::WhiteBalanceMode mode) { QString wb = m_supportedWhiteBalanceModes.value(mode, QString()); if (!wb.isEmpty()) { m_session->camera()->setWhiteBalance(wb); m_whiteBalanceMode = mode; } } void QAndroidCameraImageProcessingControl::onCameraOpened() { m_supportedWhiteBalanceModes.clear(); QStringList whiteBalanceModes = m_session->camera()->getSupportedWhiteBalance(); for (int i = 0; i < whiteBalanceModes.size(); ++i) { const QString &wb = whiteBalanceModes.at(i); if (wb == QLatin1String("auto")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceAuto, QStringLiteral("auto")); } else if (wb == QLatin1String("cloudy-daylight")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceCloudy, QStringLiteral("cloudy-daylight")); } else if (wb == QLatin1String("daylight")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceSunlight, QStringLiteral("daylight")); } else if (wb == QLatin1String("fluorescent")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceFluorescent, QStringLiteral("fluorescent")); } else if (wb == QLatin1String("incandescent")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceTungsten, QStringLiteral("incandescent")); } else if (wb == QLatin1String("shade")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceShade, QStringLiteral("shade")); } else if (wb == QLatin1String("twilight")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceSunset, QStringLiteral("twilight")); } else if (wb == QLatin1String("warm-fluorescent")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceFlash, QStringLiteral("warm-fluorescent")); } } if (!m_supportedWhiteBalanceModes.contains(m_whiteBalanceMode)) m_whiteBalanceMode = QCameraImageProcessing::WhiteBalanceAuto; setWhiteBalanceModeHelper(m_whiteBalanceMode); } QT_END_NAMESPACE
44.733333
115
0.674946
4915cc1fa9aa0126e6c28cde54d0f51ccd180fa1
2,171
hpp
C++
src/SudokuGraph.hpp
luiz787/alg1-tp3
3c1e54b023ddb269bce557681cf574aca18b3a87
[ "MIT" ]
null
null
null
src/SudokuGraph.hpp
luiz787/alg1-tp3
3c1e54b023ddb269bce557681cf574aca18b3a87
[ "MIT" ]
null
null
null
src/SudokuGraph.hpp
luiz787/alg1-tp3
3c1e54b023ddb269bce557681cf574aca18b3a87
[ "MIT" ]
null
null
null
#ifndef ALG1_TP3_SUDOKUGRAPH_HPP #define ALG1_TP3_SUDOKUGRAPH_HPP #include <cstdint> #include <list> #include <vector> #include <set> #include "Vertice.hpp" class SudokuGraph { private: std::vector<Vertice*> vertices; const uint32_t quadrantColumnWidth; const uint32_t quadrantRowHeight; const uint32_t amountOfColumns; const uint32_t amountOfRows; void addEdgesToVerticesInSameColumn(Vertice *vertice); void addEdgesToVerticesInSameRow(Vertice *vertice); void addEdgesToVerticesInSameQuadrant(Vertice *vertice); uint32_t getVerticeColumn(uint32_t verticeIndex) const; uint32_t getVerticeRow(uint32_t verticeIndex) const; void printAnswer(uint32_t totalColoredVertices) const; void removeAssignedColorFromNeighbors(Vertice *vertice); void assignColorToSaturatedVertices(uint32_t &totalColoredVertices, uint32_t &verticesThatGainedColorsInCurrentIteration); void assignColorToExhaustedUnits(uint32_t &totalColoredVertices, uint32_t &verticesThatGainedColorsInCurrentIteration); void tryToAssignColorByCheckingRowExhaustion(Vertice *vertice, uint32_t &totalColoredVertices, uint32_t &verticesThatGainedColorsInCurrentIteration); void tryToAssignColorByCheckingColumnExhaustion(Vertice *vertice, uint32_t &totalColoredVertices, uint32_t &verticesThatGainedColorsInCurrentIteration); void tryToAssignColorByCheckingQuadrantExhaustion(Vertice *vertice, uint32_t &totalColoredVertices, uint32_t &verticesThatGainedColorsInCurrentIteration); void assignColorToVerticeIfPossible(Vertice *currentVertice, const std::set<Vertice *> &unassignedNeighbors, uint32_t &totalColoredVertices, uint32_t &verticesThatGainedColorsInCurrentIteration); public: SudokuGraph(uint32_t columns, uint32_t rows, const std::vector<Vertice *> &vertices); ~SudokuGraph(); void solve(); }; #endif
40.962264
112
0.702441
4917c521e1bdbf05c0de2df2793b157b01528361
13,507
cpp
C++
src/chainparams.cpp
ITZDevToo/ITZ-SPD-Experimental
7f8104e5c9a395797f623c5452917daa22223d9c
[ "MIT" ]
null
null
null
src/chainparams.cpp
ITZDevToo/ITZ-SPD-Experimental
7f8104e5c9a395797f623c5452917daa22223d9c
[ "MIT" ]
null
null
null
src/chainparams.cpp
ITZDevToo/ITZ-SPD-Experimental
7f8104e5c9a395797f623c5452917daa22223d9c
[ "MIT" ]
null
null
null
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2014-2015 Dash Developers // Copyright (c) 2017-2018 The Stipend developers // Copyright (c) 2017-2018 The Interzone developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include "base58.h" #include "protocol.h" #include "core.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" // // Main network // // Convert the pnSeeds array into usable address objects. static void convertSeeds(std::vector<CAddress> &vSeedsOut, const unsigned int *data, unsigned int count, int port) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int k = 0; k < count; ++k) { struct in_addr ip; unsigned int i = data[k], t; // -- convert to big endian t = (i & 0x000000ff) << 24u | (i & 0x0000ff00) << 8u | (i & 0x00ff0000) >> 8u | (i & 0xff000000) >> 24u; memcpy(&ip, &t, sizeof(ip)); CAddress addr(CService(ip, port)); addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek; vSeedsOut.push_back(addr); } } // Hardcoded seeds. static void getHardcodedSeeds(std::vector<CAddress> &vSeedsOut) { std::vector<std::string> ips; ips.push_back("188.226.139.237"); ips.push_back("104.207.133.227"); ips.push_back("45.63.22.217"); const int64_t oneWeek = 7 * 24 * 60 * 60; for (size_t i = 0; i < ips.size(); ++i) { CAddress addr(CService(ips[i], 55675)); addr.nTime = GetTime() - GetRand(oneWeek) - oneWeek; vSeedsOut.push_back(addr); } } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x08; pchMessageStart[1] = 0x02; pchMessageStart[2] = 0x01; pchMessageStart[3] = 0x17; vAlertPubKey = ParseHex("04579f18934b3ef39094a9999e45506a1935662d0cd4e504d07beb53b8a1bfd78d81bee47e65119318397809420d5320e3c7b2aaae58580db48c38a4e6d4f0f919"); nDefaultPort = 55675; nRPCPort = 55680; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); nSubsidyHalvingInterval = 500000; const char* pszTimestamp = "The rulers of this most insecure of all worlds are rulers by accident."; std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); //vout[0].SetEmpty(); vout[0].nValue = 16 * COIN; vout[0].scriptPubKey = CScript() << ParseHex("04becedf6ebadd4596964d890f677f8d2e74fdcc313c6416434384a66d6d8758d1c92de272dc6713e4a81d98841dfdfdc95e204ba915447d2fe9313435c78af3e8") << OP_CHECKSIG; CTransaction txNew(1, 1503332100, vin, vout, 0); // uncomment to log genesis block info // start if (true && genesis.GetHash() != hashGenesisBlock) { printf("Searching for genesis block...\n"); uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256(); uint256 thash; /*while (true) { thash = genesis.GetHash(); if (thash <= hashTarget) break; if ((genesis.nNonce & 0xFFF) == 0) { printf("nonce %08X: hash = %s (target = %s)\n", genesis.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str()); } ++genesis.nNonce; if (genesis.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++genesis.nTime; } } */ printf("genesis.pszTimestamp = %s \n", pszTimestamp); printf("genesis.nBits = %u \n", genesis.nBits); printf("genesis.nTime = %u \n", genesis.nTime); printf("genesis.nNonce = %u \n", genesis.nNonce); printf("genesis.nVersion = %u \n", genesis.nVersion); printf("genesis.GetHash = %s\n", genesis.GetHash().ToString().c_str()); //first this, then comment this line out and uncomment the one under. printf("genesis.hashMerkleRoot = %s \n", genesis.hashMerkleRoot.ToString().c_str()); //improvised. worked for me, to find merkle root } //end /* // Genesis block const char* pszTimestamp = "The rulers of this most insecure of all worlds are rulers by accident."; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 16 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04becedf6ebadd4596964d890f677f8d2e74fdcc313c6416434384a66d6d8758d1c92de272dc6713e4a81d98841dfdfdc95e204ba915447d2fe9313435c78af3e8") << OP_CHECKSIG; */ LogPrintf("genesis mainnet transaction: %s\n", txNew.ToString().c_str()); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1503332100; genesis.nBits = 0x1e0fffff; //genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 294622; // uncomment to log genesis block info // start if (true && genesis.GetHash() != hashGenesisBlock) { printf("Searching for genesis block...\n"); uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256(); uint256 thash; /*while (true) { thash = genesis.GetHash(); if (thash <= hashTarget) break; if ((genesis.nNonce & 0xFFF) == 0) { printf("nonce %08X: hash = %s (target = %s)\n", genesis.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str()); } ++genesis.nNonce; if (genesis.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++genesis.nTime; } } */ printf("genesis.pszTimestamp = %s \n", pszTimestamp); printf("genesis.nBits = %u \n", genesis.nBits); printf("genesis.nTime = %u \n", genesis.nTime); printf("genesis.nNonce = %u \n", genesis.nNonce); printf("genesis.nVersion = %u \n", genesis.nVersion); printf("genesis.GetHash = %s\n", genesis.GetHash().ToString().c_str()); //first this, then comment this line out and uncomment the one under. printf("genesis.hashMerkleRoot = %s \n", genesis.hashMerkleRoot.ToString().c_str()); //improvised. worked for me, to find merkle root } //end hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000a3e2f4ab22bae06eb1d3121262055fef0fc03da5337b1c7c153af133780")); assert(genesis.hashMerkleRoot == uint256("0x11f8d6fdf5460c2308b76da69942dd9fa386f9d337fbc95f669d73bcf02b64a5")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,0); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,28 + 128); //base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,41); //base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x99)(0x75)(0x45)(0xE2).convert_to_container<std::vector<unsigned char> >(); //base58Prefixes[EXT_SECRET_KEY] = list_of(0x99)(0x73)(0x43)(0xE3).convert_to_container<std::vector<unsigned char> >(); // NOTE: MODIFIED THIS TO 0.0.0.0 vSeeds.push_back(CDNSSeedData("1", "188.226.139.237")); vSeeds.push_back(CDNSSeedData("2", "104.207.133.227")); vSeeds.push_back(CDNSSeedData("3", "45.63.22.217")); //vSeeds.push_back(CDNSSeedData("4", "34.231.228.73")); //vSeeds.push_back(CDNSSeedData("5", "34.239.99.171")); //vSeeds.push_back(CDNSSeedData("6", "18.218.0.160")); //vSeeds.push_back(CDNSSeedData("7", "13.59.189.252")); //vSeeds.push_back(CDNSSeedData("8", "52.15.218.190")); convertSeeds(vFixedSeeds, pnSeed, ARRAYLEN(pnSeed), nDefaultPort); getHardcodedSeeds(vFixedSeeds); nPoolMaxTransactions = 3; strDarksendPoolDummyAddress = "175M2dV2DaEJWcTjxrGPJT88WDUE7Bj44U"; nLastPOWBlock = 450000; nPOSStartBlock = 210000; } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xfb; pchMessageStart[1] = 0xc2; pchMessageStart[2] = 0x11; pchMessageStart[3] = 0x02; //bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); vAlertPubKey = ParseHex("04c4d925d462a89054155314a7068bb8cf6d7c030d76491e6cc97fefcc4ab8c3665bfb34c3aba0e12b9fb4fab47502a00938dd93e0e675c4713ee47200046de2e3"); nDefaultPort = 21817; nRPCPort = 21818; strDataDir = "testnet"; genesis.nTime = 1503324223; //genesis.nBits = 0x207fffff(); genesis.nNonce = 1088722; hashGenesisBlock = genesis.GetHash(); LogPrintf("Display genesis hash so we can input it below %s\n", hashGenesisBlock.ToString().c_str()); LogPrintf("Display merkle root so we can input it below %s\n", genesis.hashMerkleRoot.ToString().c_str()); assert(hashGenesisBlock == uint256("0x0000016920f7856a2a4f342db39b70591c00a699f1fe865ebc687fd9b66aa586")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,102); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,44); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,88 + 128); //base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,43); //base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x98)(0x74)(0x44)(0xE1).convert_to_container<std::vector<unsigned char> >(); //base58Prefixes[EXT_SECRET_KEY] = list_of(0x98)(0x72)(0x42)(0xE2).convert_to_container<std::vector<unsigned char> >(); convertSeeds(vFixedSeeds, pnTestnetSeed, ARRAYLEN(pnTestnetSeed), nDefaultPort); nLastPOWBlock = 210000; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; }
41.432515
208
0.589472
4918a085c092ae79048cbc9d2b6693d185013b3b
5,921
hpp
C++
build/include/lcmtypes/drake/lcmt_viewer_draw.hpp
ericmanzi/double_pendulum_lqr
76bba3091295abb7d412c4a3156258918f280c96
[ "BSD-3-Clause" ]
null
null
null
build/include/lcmtypes/drake/lcmt_viewer_draw.hpp
ericmanzi/double_pendulum_lqr
76bba3091295abb7d412c4a3156258918f280c96
[ "BSD-3-Clause" ]
null
null
null
build/include/lcmtypes/drake/lcmt_viewer_draw.hpp
ericmanzi/double_pendulum_lqr
76bba3091295abb7d412c4a3156258918f280c96
[ "BSD-3-Clause" ]
null
null
null
/** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT MODIFY * BY HAND!! * * Generated by lcm-gen **/ #include <lcm/lcm_coretypes.h> #ifndef __drake_lcmt_viewer_draw_hpp__ #define __drake_lcmt_viewer_draw_hpp__ #include <vector> namespace drake { class lcmt_viewer_draw { public: int64_t timestamp; int32_t num_links; std::vector< std::string > link_name; std::vector< int32_t > robot_num; std::vector< std::vector< float > > position; std::vector< std::vector< float > > quaternion; public: inline int encode(void *buf, int offset, int maxlen) const; inline int getEncodedSize() const; inline int decode(const void *buf, int offset, int maxlen); inline static int64_t getHash(); inline static const char* getTypeName(); // LCM support functions. Users should not call these inline int _encodeNoHash(void *buf, int offset, int maxlen) const; inline int _getEncodedSizeNoHash() const; inline int _decodeNoHash(const void *buf, int offset, int maxlen); inline static int64_t _computeHash(const __lcm_hash_ptr *p); }; int lcmt_viewer_draw::encode(void *buf, int offset, int maxlen) const { int pos = 0, tlen; int64_t hash = getHash(); tlen = __int64_t_encode_array(buf, offset + pos, maxlen - pos, &hash, 1); if(tlen < 0) return tlen; else pos += tlen; tlen = this->_encodeNoHash(buf, offset + pos, maxlen - pos); if (tlen < 0) return tlen; else pos += tlen; return pos; } int lcmt_viewer_draw::decode(const void *buf, int offset, int maxlen) { int pos = 0, thislen; int64_t msg_hash; thislen = __int64_t_decode_array(buf, offset + pos, maxlen - pos, &msg_hash, 1); if (thislen < 0) return thislen; else pos += thislen; if (msg_hash != getHash()) return -1; thislen = this->_decodeNoHash(buf, offset + pos, maxlen - pos); if (thislen < 0) return thislen; else pos += thislen; return pos; } int lcmt_viewer_draw::getEncodedSize() const { return 8 + _getEncodedSizeNoHash(); } int64_t lcmt_viewer_draw::getHash() { static int64_t hash = _computeHash(NULL); return hash; } const char* lcmt_viewer_draw::getTypeName() { return "lcmt_viewer_draw"; } int lcmt_viewer_draw::_encodeNoHash(void *buf, int offset, int maxlen) const { int pos = 0, tlen; tlen = __int64_t_encode_array(buf, offset + pos, maxlen - pos, &this->timestamp, 1); if(tlen < 0) return tlen; else pos += tlen; tlen = __int32_t_encode_array(buf, offset + pos, maxlen - pos, &this->num_links, 1); if(tlen < 0) return tlen; else pos += tlen; for (int a0 = 0; a0 < this->num_links; a0++) { char* __cstr = (char*) this->link_name[a0].c_str(); tlen = __string_encode_array(buf, offset + pos, maxlen - pos, &__cstr, 1); if(tlen < 0) return tlen; else pos += tlen; } tlen = __int32_t_encode_array(buf, offset + pos, maxlen - pos, &this->robot_num[0], this->num_links); if(tlen < 0) return tlen; else pos += tlen; for (int a0 = 0; a0 < this->num_links; a0++) { tlen = __float_encode_array(buf, offset + pos, maxlen - pos, &this->position[a0][0], 3); if(tlen < 0) return tlen; else pos += tlen; } for (int a0 = 0; a0 < this->num_links; a0++) { tlen = __float_encode_array(buf, offset + pos, maxlen - pos, &this->quaternion[a0][0], 4); if(tlen < 0) return tlen; else pos += tlen; } return pos; } int lcmt_viewer_draw::_decodeNoHash(const void *buf, int offset, int maxlen) { int pos = 0, tlen; tlen = __int64_t_decode_array(buf, offset + pos, maxlen - pos, &this->timestamp, 1); if(tlen < 0) return tlen; else pos += tlen; tlen = __int32_t_decode_array(buf, offset + pos, maxlen - pos, &this->num_links, 1); if(tlen < 0) return tlen; else pos += tlen; this->link_name.resize(this->num_links); for (int a0 = 0; a0 < this->num_links; a0++) { int32_t __elem_len; tlen = __int32_t_decode_array(buf, offset + pos, maxlen - pos, &__elem_len, 1); if(tlen < 0) return tlen; else pos += tlen; if(__elem_len > maxlen - pos) return -1; this->link_name[a0].assign(((const char*)buf) + offset + pos, __elem_len - 1); pos += __elem_len; } this->robot_num.resize(this->num_links); if(this->num_links) { tlen = __int32_t_decode_array(buf, offset + pos, maxlen - pos, &this->robot_num[0], this->num_links); if(tlen < 0) return tlen; else pos += tlen; } this->position.resize(this->num_links); for (int a0 = 0; a0 < this->num_links; a0++) { this->position[a0].resize(3); if(3) { tlen = __float_decode_array(buf, offset + pos, maxlen - pos, &this->position[a0][0], 3); if(tlen < 0) return tlen; else pos += tlen; } } this->quaternion.resize(this->num_links); for (int a0 = 0; a0 < this->num_links; a0++) { this->quaternion[a0].resize(4); if(4) { tlen = __float_decode_array(buf, offset + pos, maxlen - pos, &this->quaternion[a0][0], 4); if(tlen < 0) return tlen; else pos += tlen; } } return pos; } int lcmt_viewer_draw::_getEncodedSizeNoHash() const { int enc_size = 0; enc_size += __int64_t_encoded_array_size(NULL, 1); enc_size += __int32_t_encoded_array_size(NULL, 1); for (int a0 = 0; a0 < this->num_links; a0++) { enc_size += this->link_name[a0].size() + 4 + 1; } enc_size += __int32_t_encoded_array_size(NULL, this->num_links); enc_size += this->num_links * __float_encoded_array_size(NULL, 3); enc_size += this->num_links * __float_encoded_array_size(NULL, 4); return enc_size; } int64_t lcmt_viewer_draw::_computeHash(const __lcm_hash_ptr *) { int64_t hash = 0x20a785ff2d97a122LL; return (hash<<1) + ((hash>>63)&1); } } #endif
31.494681
109
0.630468
49198bef6748357995d737585a3a125683391cd6
5,281
cpp
C++
src/commands.cpp
rhoot/pantryman
4df649b811f8321efe49893ed69fefb03b0977d6
[ "0BSD" ]
7
2021-01-30T01:27:24.000Z
2021-11-14T20:32:01.000Z
src/commands.cpp
rhoot/pantryman
4df649b811f8321efe49893ed69fefb03b0977d6
[ "0BSD" ]
null
null
null
src/commands.cpp
rhoot/pantryman
4df649b811f8321efe49893ed69fefb03b0977d6
[ "0BSD" ]
null
null
null
// // Copyright (c) 2018 Johan Sköld // License: https://opensource.org/licenses/ISC // #include "commands.hpp" #include "config.hpp" #include <cassert> #include <cstring> #include <algorithm> namespace pm { HostCommand::HostCommand() { } HostCommands::HostCommands() : m_buffer{PM_CONFIG_COMMAND_BUFFER_SIZE} { } bool HostCommands::nextCommand(HostCommand* cmd) { if (!m_buffer.beginRead()) { return false; } cmd->type = m_buffer.read<HostCommand::Type>(); switch (cmd->type) { case HostCommand::CREATE_WINDOW: { cmd->createWindow.handle = m_buffer.read<WindowHandle>(); cmd->createWindow.width = m_buffer.read<uint16_t>(); cmd->createWindow.height = m_buffer.read<uint16_t>(); cmd->createWindow.state = m_buffer.read<WindowState>(); cmd->createWindow.style = m_buffer.read<WindowStyle>(); const uint16_t titleLen = m_buffer.read<uint16_t>(); m_buffer.read(cmd->createWindow.title, 1, titleLen); cmd->createWindow.title[titleLen] = 0; break; } case HostCommand::DESTROY_WINDOW: cmd->windowHandle = m_buffer.read<WindowHandle>(); break; case HostCommand::EXECUTE: cmd->execute.function = m_buffer.read<ExecuteFn>(); cmd->execute.userPointer = m_buffer.read<void*>(); break; case HostCommand::SET_CALLBACK: cmd->callback.index = m_buffer.read<uint16_t>(); cmd->callback.function = m_buffer.read<ExecuteFn>(); cmd->callback.userPointer = m_buffer.read<void*>(); break; case HostCommand::SET_WINDOW_SIZE: cmd->windowSize.handle = m_buffer.read<WindowHandle>(); cmd->windowSize.width = m_buffer.read<uint16_t>(); cmd->windowSize.height = m_buffer.read<uint16_t>(); break; case HostCommand::SET_WINDOW_STATE: cmd->windowState.handle = m_buffer.read<WindowHandle>(); cmd->windowState.state = m_buffer.read<WindowState>(); break; case HostCommand::SET_WINDOW_STYLE: cmd->windowStyle.handle = m_buffer.read<WindowHandle>(); cmd->windowStyle.style = m_buffer.read<WindowStyle>(); break; case HostCommand::STOP: break; default: assert(!"invalid command type"); _Exit(1); } m_buffer.endRead(); return true; } void HostCommands::sendCreateWindow(WindowHandle handle, const WindowParams& params) { uint16_t titleLen = uint16_t(std::strlen(params.title)); if (titleLen > MAX_WINDOW_TITLE_LEN) { titleLen = MAX_WINDOW_TITLE_LEN; } m_buffer.beginWrite(); m_buffer.write(HostCommand::CREATE_WINDOW); m_buffer.write(handle); m_buffer.write(params.width); m_buffer.write(params.height); m_buffer.write(params.state); m_buffer.write(params.style); m_buffer.write(titleLen); m_buffer.write(params.title, 1, titleLen); m_buffer.endWrite(); } void HostCommands::sendDestroyWindow(WindowHandle handle) { m_buffer.beginWrite(); m_buffer.write(HostCommand::DESTROY_WINDOW); m_buffer.write(handle); m_buffer.endWrite(); } void HostCommands::sendExecute(ExecuteFn function, void* userPointer) { m_buffer.beginWrite(); m_buffer.write(HostCommand::EXECUTE); m_buffer.write(function); m_buffer.write(userPointer); m_buffer.endWrite(); } void HostCommands::sendSetCallback(uint16_t index, ExecuteFn function, void* userPointer) { m_buffer.beginWrite(); m_buffer.write(HostCommand::SET_CALLBACK); m_buffer.write(index); m_buffer.write(function); m_buffer.write(userPointer); m_buffer.endWrite(); } void HostCommands::sendSetWindowSize(WindowHandle handle, uint16_t width, uint16_t height) { m_buffer.beginWrite(); m_buffer.write(HostCommand::SET_WINDOW_SIZE); m_buffer.write(handle); m_buffer.write(width); m_buffer.write(height); m_buffer.endWrite(); } void HostCommands::sendSetWindowState(WindowHandle handle, WindowState state) { m_buffer.beginWrite(); m_buffer.write(HostCommand::SET_WINDOW_STATE); m_buffer.write(handle); m_buffer.write(state); m_buffer.endWrite(); } void HostCommands::sendSetWindowStyle(WindowHandle handle, WindowStyle style) { m_buffer.beginWrite(); m_buffer.write(HostCommand::SET_WINDOW_STYLE); m_buffer.write(handle); m_buffer.write(style); m_buffer.endWrite(); } void HostCommands::sendStop() { m_buffer.beginWrite(); m_buffer.write(HostCommand::STOP); m_buffer.endWrite(); } } // namespace pm
30.005682
94
0.589093
491c7e635e7a39b17f3b6f7ca37a096e82866725
738
cpp
C++
UnLive2DAsset/Source/UnLive2DAsset/Private/UnLive2DMotion.cpp
Monocluar/UnLive2D
f4e255d3d5c12ebd56f6b248c65db7ffb7f58571
[ "MIT" ]
null
null
null
UnLive2DAsset/Source/UnLive2DAsset/Private/UnLive2DMotion.cpp
Monocluar/UnLive2D
f4e255d3d5c12ebd56f6b248c65db7ffb7f58571
[ "MIT" ]
null
null
null
UnLive2DAsset/Source/UnLive2DAsset/Private/UnLive2DMotion.cpp
Monocluar/UnLive2D
f4e255d3d5c12ebd56f6b248c65db7ffb7f58571
[ "MIT" ]
null
null
null
#include "UnLive2DMotion.h" #include "Misc/FileHelper.h" #if WITH_EDITOR bool UUnLive2DMotion::LoadLive2DMotionData(const FString& ReadMotionPath, EUnLive2DMotionGroup InMotionGroupType, int32 InMotionCount, float FadeInTime, float FadeOutTime) { const bool ReadSuc = FFileHelper::LoadFileToArray(MotionData.MotionByteData, *ReadMotionPath); MotionData.FadeInTime = FadeInTime; MotionData.FadeOutTime = FadeOutTime; MotionData.MotionCount = InMotionCount; MotionData.MotionGroupType = InMotionGroupType; return ReadSuc; } void UUnLive2DMotion::SetLive2DMotionData(FUnLive2DMotionData& InMotionData) { MotionData = InMotionData; } #endif const FUnLive2DMotionData* UUnLive2DMotion::GetMotionData() { return &MotionData; }
23.806452
171
0.817073
491d4d9781e754486e2d6adee12d3b075a0aa0c8
734
hpp
C++
src/interfaces/json_storage.hpp
aahmed-2/telemetry
7e098e93ef0974739459d296f99ddfab54722c23
[ "Apache-2.0" ]
4
2019-11-14T10:41:34.000Z
2021-12-09T23:54:52.000Z
src/interfaces/json_storage.hpp
aahmed-2/telemetry
7e098e93ef0974739459d296f99ddfab54722c23
[ "Apache-2.0" ]
2
2021-10-04T20:12:53.000Z
2021-12-14T18:13:03.000Z
src/interfaces/json_storage.hpp
aahmed-2/telemetry
7e098e93ef0974739459d296f99ddfab54722c23
[ "Apache-2.0" ]
2
2021-08-05T11:17:03.000Z
2021-12-13T15:22:48.000Z
#pragma once #include <boost/serialization/strong_typedef.hpp> #include <nlohmann/json.hpp> #include <filesystem> #include <optional> #include <string> namespace interfaces { class JsonStorage { public: BOOST_STRONG_TYPEDEF(std::filesystem::path, FilePath) BOOST_STRONG_TYPEDEF(std::filesystem::path, DirectoryPath) virtual ~JsonStorage() = default; virtual void store(const FilePath& subPath, const nlohmann::json& data) = 0; virtual bool remove(const FilePath& subPath) = 0; virtual bool exist(const FilePath& path) const = 0; virtual std::optional<nlohmann::json> load(const FilePath& subPath) const = 0; virtual std::vector<FilePath> list() const = 0; }; } // namespace interfaces
24.466667
80
0.719346
491db81b8315955dbd6a8777eb20a33854432efc
107,574
cc
C++
sandboxed_api/sandbox2/syscall_defs.cc
oshogbo/sandboxed-api
8e82b900f4d873219b3abfa2fd06ecbd416edefd
[ "Apache-2.0" ]
1,562
2019-03-07T10:02:53.000Z
2022-03-31T17:43:05.000Z
sandboxed_api/sandbox2/syscall_defs.cc
oshogbo/sandboxed-api
8e82b900f4d873219b3abfa2fd06ecbd416edefd
[ "Apache-2.0" ]
70
2019-03-19T01:02:49.000Z
2022-03-30T17:26:53.000Z
sandboxed_api/sandbox2/syscall_defs.cc
oshogbo/sandboxed-api
8e82b900f4d873219b3abfa2fd06ecbd416edefd
[ "Apache-2.0" ]
181
2019-03-18T19:41:30.000Z
2022-03-29T13:08:26.000Z
#include "sandboxed_api/sandbox2/syscall_defs.h" #include <cstdint> #include <type_traits> #include <glog/logging.h> #include "absl/algorithm/container.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "sandboxed_api/config.h" #include "sandboxed_api/sandbox2/util.h" namespace sandbox2 { // Type of a given syscall argument. Used with argument conversion routines. enum ArgType { kGen = 1, kInt, kPath, kHex, kOct, kSocketCall, kSocketCallPtr, kSignal, kString, kAddressFamily, kSockaddr, kSockmsghdr, kCloneFlag, }; // Single syscall definition struct SyscallTable::Entry { // Returns the number of arguments which given syscall takes. int GetNumArgs() const { if (num_args < 0 || num_args > syscalls::kMaxArgs) { return syscalls::kMaxArgs; } return num_args; } static std::string GetArgumentDescription(uint64_t value, ArgType type, pid_t pid); std::vector<std::string> GetArgumentsDescription( const uint64_t values[syscalls::kMaxArgs], pid_t pid) const; static constexpr bool BySyscallNr(const SyscallTable::Entry& a, const SyscallTable::Entry& b) { return a.nr < b.nr; } int nr; absl::string_view name; int num_args; std::array<ArgType, syscalls::kMaxArgs> arg_types; }; std::string SyscallTable::Entry::GetArgumentDescription(uint64_t value, ArgType type, pid_t pid) { std::string ret = absl::StrFormat("%#x", value); switch (type) { case kOct: absl::StrAppendFormat(&ret, " [\\0%o]", value); break; case kPath: if (auto path_or = util::ReadCPathFromPid(pid, value); path_or.ok()) { absl::StrAppendFormat(&ret, " ['%s']", absl::CHexEscape(path_or.value())); } else { absl::StrAppend(&ret, " [unreadable path]"); } break; case kInt: absl::StrAppendFormat(&ret, " [%d]", value); break; default: break; } return ret; } absl::string_view SyscallTable::GetName(int syscall) const { auto it = absl::c_lower_bound( data_, syscall, [](const SyscallTable::Entry& entry, int syscall) { return entry.nr < syscall; }); if (it == data_.end() || it->nr != syscall) { return ""; } return it->name; } namespace { template <typename... ArgTypes> constexpr SyscallTable::Entry MakeEntry(int nr, absl::string_view name, ArgTypes... arg_types) { static_assert(sizeof...(arg_types) <= syscalls::kMaxArgs, "Too many arguments for syscall"); return {nr, name, sizeof...(arg_types), {arg_types...}}; } struct UnknownArguments {}; constexpr SyscallTable::Entry MakeEntry(int nr, absl::string_view name, UnknownArguments) { return {nr, name, -1, {kGen, kGen, kGen, kGen, kGen, kGen}}; } } // namespace std::vector<std::string> SyscallTable::GetArgumentsDescription( int syscall, const uint64_t values[], pid_t pid) const { static SyscallTable::Entry kInvalidEntry = MakeEntry(-1, "", UnknownArguments()); auto it = absl::c_lower_bound( data_, syscall, [](const SyscallTable::Entry& entry, int syscall) { return entry.nr < syscall; }); const auto& entry = it != data_.end() && it->nr == syscall ? *it : kInvalidEntry; int num_args = entry.GetNumArgs(); std::vector<std::string> rv; rv.reserve(num_args); for (int i = 0; i < num_args; ++i) { rv.push_back(SyscallTable::Entry::GetArgumentDescription( values[i], entry.arg_types[i], pid)); } return rv; } namespace { // TODO(C++20) Use std::is_sorted template <typename Container, typename Compare> constexpr bool IsSorted(const Container& container, Compare comp) { auto it = std::begin(container); if (it == std::end(container)) { return true; } auto last = it; for (++it; it != std::end(container); ++it) { if (!comp(*last, *it)) { return false; } last = it; } return true; } // Syscall description table for Linux x86_64 constexpr std::array kSyscallDataX8664 = { // clang-format off MakeEntry(0, "read", kInt, kHex, kInt), MakeEntry(1, "write", kInt, kHex, kInt), MakeEntry(2, "open", kPath, kHex, kOct), MakeEntry(3, "close", kInt), MakeEntry(4, "stat", kPath, kGen), MakeEntry(5, "fstat", kInt, kHex), MakeEntry(6, "lstat", kPath, kGen), MakeEntry(7, "poll", kGen, kInt, kInt), MakeEntry(8, "lseek", kInt, kInt, kInt), MakeEntry(9, "mmap", kHex, kInt, kHex, kHex, kInt, kInt), MakeEntry(10, "mprotect", kHex, kInt, kHex), MakeEntry(11, "munmap", kHex, kInt), MakeEntry(12, "brk", kInt), MakeEntry(13, "rt_sigaction", kSignal, kHex, kHex, kInt), MakeEntry(14, "rt_sigprocmask", kInt, kHex, kHex, kInt), MakeEntry(15, "rt_sigreturn"), MakeEntry(16, "ioctl", kInt, kInt, kHex), MakeEntry(17, "pread64", kInt, kHex, kInt, kInt), MakeEntry(18, "pwrite64", kInt, kHex, kInt, kInt), MakeEntry(19, "readv", kInt, kHex, kInt), MakeEntry(20, "writev", kInt, kHex, kInt), MakeEntry(21, "access", kPath, kOct), MakeEntry(22, "pipe", kHex), MakeEntry(23, "select", kInt, kHex, kHex, kHex, kHex), MakeEntry(24, "sched_yield"), MakeEntry(25, "mremap", kHex, kInt, kInt, kInt, kHex), MakeEntry(26, "msync", kHex, kInt, kInt), MakeEntry(27, "mincore", kHex, kInt, kHex), MakeEntry(28, "madvise", kHex, kInt, kInt), MakeEntry(29, "shmget", kInt, kInt, kHex), MakeEntry(30, "shmat", kInt, kHex, kHex), MakeEntry(31, "shmctl", kInt, kInt, kHex), MakeEntry(32, "dup", kInt), MakeEntry(33, "dup2", kInt, kInt), MakeEntry(34, "pause"), MakeEntry(35, "nanosleep", kHex, kHex), MakeEntry(36, "getitimer", kInt, kHex), MakeEntry(37, "alarm", kInt), MakeEntry(38, "setitimer", kInt, kHex, kHex), MakeEntry(39, "getpid"), MakeEntry(40, "sendfile", kInt, kInt, kHex, kInt), MakeEntry(41, "socket", kAddressFamily, kInt, kInt), MakeEntry(42, "connect", kInt, kSockaddr, kInt), MakeEntry(43, "accept", kInt, kSockaddr, kHex), MakeEntry(44, "sendto", kInt, kHex, kInt, kHex, kSockaddr, kInt), MakeEntry(45, "recvfrom", kInt, kHex, kInt, kHex, kSockaddr, kHex), MakeEntry(46, "sendmsg", kInt, kSockmsghdr, kHex), MakeEntry(47, "recvmsg", kInt, kHex, kInt), MakeEntry(48, "shutdown", kInt, kInt), MakeEntry(49, "bind", kInt, kSockaddr, kInt), MakeEntry(50, "listen", kInt, kInt), MakeEntry(51, "getsockname", kInt, kSockaddr, kHex), MakeEntry(52, "getpeername", kInt, kSockaddr, kHex), MakeEntry(53, "socketpair", kAddressFamily, kInt, kInt, kHex), MakeEntry(54, "setsockopt", kInt, kInt, kInt, kHex, kHex), MakeEntry(55, "getsockopt", kInt, kInt, kInt, kHex, kInt), MakeEntry(56, "clone", kCloneFlag, kHex, kHex, kHex, kHex), MakeEntry(57, "fork"), MakeEntry(58, "vfork"), MakeEntry(59, "execve", kPath, kHex, kHex), MakeEntry(60, "exit", kInt), MakeEntry(61, "wait4", kInt, kHex, kHex, kHex), MakeEntry(62, "kill", kInt, kSignal), MakeEntry(63, "uname", kInt), MakeEntry(64, "semget", kInt, kInt, kHex), MakeEntry(65, "semop", kInt, kHex, kInt), MakeEntry(66, "semctl", kInt, kInt, kInt, kHex), MakeEntry(67, "shmdt", kHex), MakeEntry(68, "msgget", kInt, kHex), MakeEntry(69, "msgsnd", kInt, kHex, kInt, kHex), MakeEntry(70, "msgrcv", kInt, kHex, kInt, kInt, kHex), MakeEntry(71, "msgctl", kInt, kInt, kHex), MakeEntry(72, "fcntl", kInt, kInt, kHex), MakeEntry(73, "flock", kInt, kInt), MakeEntry(74, "fsync", kInt), MakeEntry(75, "fdatasync", kInt), MakeEntry(76, "truncate", kPath, kInt), MakeEntry(77, "ftruncate", kInt, kInt), MakeEntry(78, "getdents", kInt, kHex, kInt), MakeEntry(79, "getcwd", kHex, kInt), MakeEntry(80, "chdir", kPath), MakeEntry(81, "fchdir", kInt), MakeEntry(82, "rename", kPath, kPath), MakeEntry(83, "mkdir", kPath, kOct), MakeEntry(84, "rmdir", kPath), MakeEntry(85, "creat", kPath, kOct), MakeEntry(86, "link", kPath, kPath), MakeEntry(87, "unlink", kPath), MakeEntry(88, "symlink", kPath, kPath), MakeEntry(89, "readlink", kPath, kHex, kInt), MakeEntry(90, "chmod", kPath, kOct), MakeEntry(91, "fchmod", kInt, kOct), MakeEntry(92, "chown", kPath, kInt, kInt), MakeEntry(93, "fchown", kInt, kInt, kInt), MakeEntry(94, "lchown", kPath, kInt, kInt), MakeEntry(95, "umask", kHex), MakeEntry(96, "gettimeofday", kHex, kHex), MakeEntry(97, "getrlimit", kInt, kHex), MakeEntry(98, "getrusage", kInt, kHex), MakeEntry(99, "sysinfo", kHex), MakeEntry(100, "times", kHex), MakeEntry(101, "ptrace", kInt, kInt, kHex, kHex), MakeEntry(102, "getuid"), MakeEntry(103, "syslog", kInt, kHex, kInt), MakeEntry(104, "getgid"), MakeEntry(105, "setuid", kInt), MakeEntry(106, "setgid", kInt), MakeEntry(107, "geteuid"), MakeEntry(108, "getegid"), MakeEntry(109, "setpgid", kInt, kInt), MakeEntry(110, "getppid"), MakeEntry(111, "getpgrp"), MakeEntry(112, "setsid"), MakeEntry(113, "setreuid", kInt, kInt), MakeEntry(114, "setregid", kInt, kInt), MakeEntry(115, "getgroups", kInt, kHex), MakeEntry(116, "setgroups", kInt, kHex), MakeEntry(117, "setresuid", kInt, kInt, kInt), MakeEntry(118, "getresuid", kHex, kHex, kHex), MakeEntry(119, "setresgid", kInt, kInt, kInt), MakeEntry(120, "getresgid", kHex, kHex, kHex), MakeEntry(121, "getpgid", kInt), MakeEntry(122, "setfsuid", kInt), MakeEntry(123, "setfsgid", kInt), MakeEntry(124, "getsid", kInt), MakeEntry(125, "capget", kHex, kHex), MakeEntry(126, "capset", kHex, kHex), MakeEntry(127, "rt_sigpending", kHex, kInt), MakeEntry(128, "rt_sigtimedwait", kHex, kHex, kHex, kInt), MakeEntry(129, "rt_sigqueueinfo", kInt, kSignal, kHex), MakeEntry(130, "rt_sigsuspend", kHex, kInt), MakeEntry(131, "sigaltstack", kHex, kHex), MakeEntry(132, "utime", kPath, kHex), MakeEntry(133, "mknod", kPath, kOct, kHex), MakeEntry(134, "uselib", kPath), MakeEntry(135, "personality", kHex), MakeEntry(136, "ustat", kHex, kHex), MakeEntry(137, "statfs", kPath, kHex), MakeEntry(138, "fstatfs", kInt, kHex), MakeEntry(139, "sysfs", kInt, kInt, kInt), MakeEntry(140, "getpriority", kInt, kInt), MakeEntry(141, "setpriority", kInt, kInt, kInt), MakeEntry(142, "sched_setparam", kInt, kHex), MakeEntry(143, "sched_getparam", kInt, kHex), MakeEntry(144, "sched_setscheduler", kInt, kInt, kHex), MakeEntry(145, "sched_getscheduler", kInt), MakeEntry(146, "sched_get_priority_max", kInt), MakeEntry(147, "sched_get_priority_min", kInt), MakeEntry(148, "sched_rr_get_interval", kInt, kHex), MakeEntry(149, "mlock", kInt, kInt), MakeEntry(150, "munlock", kInt, kInt), MakeEntry(151, "mlockall", kHex), MakeEntry(152, "munlockall"), MakeEntry(153, "vhangup"), MakeEntry(154, "modify_ldt", kInt, kHex, kInt), MakeEntry(155, "pivot_root", kPath, kPath), MakeEntry(156, "_sysctl", kHex), MakeEntry(157, "prctl", kInt, kHex, kHex, kHex, kHex), MakeEntry(158, "arch_prctl", kInt, kHex), MakeEntry(159, "adjtimex", kHex), MakeEntry(160, "setrlimit", kInt, kHex), MakeEntry(161, "chroot", kPath), MakeEntry(162, "sync"), MakeEntry(163, "acct", kPath), MakeEntry(164, "settimeofday", kHex, kHex), MakeEntry(165, "mount", kPath, kPath, kString, kHex, kGen), MakeEntry(166, "umount2", kPath, kHex), MakeEntry(167, "swapon", kPath, kHex), MakeEntry(168, "swapoff", kPath), MakeEntry(169, "reboot", kInt, kHex, kHex, kGen), MakeEntry(170, "sethostname", kString, kInt), MakeEntry(171, "setdomainname", kString, kInt), MakeEntry(172, "iopl", kInt), MakeEntry(173, "ioperm", kInt, kInt, kInt), MakeEntry(174, "create_module", kString, kInt), MakeEntry(175, "init_module", kGen, kInt, kString), MakeEntry(176, "delete_module", kString, kHex), MakeEntry(177, "get_kernel_syms", kHex), MakeEntry(178, "query_module", kString, kInt, kGen, kInt, kGen), MakeEntry(179, "quotactl", kInt, kPath, kInt, kGen), MakeEntry(180, "nfsservctl", kInt, kGen, kGen), MakeEntry(181, "getpmsg", UnknownArguments()), MakeEntry(182, "putpmsg", UnknownArguments()), MakeEntry(183, "afs_syscall", UnknownArguments()), MakeEntry(184, "tuxcall", UnknownArguments()), MakeEntry(185, "security", UnknownArguments()), MakeEntry(186, "gettid"), MakeEntry(187, "readahead", kInt, kInt, kInt), MakeEntry(188, "setxattr", kPath, kString, kGen, kInt, kHex), MakeEntry(189, "lsetxattr", kPath, kString, kGen, kInt, kHex), MakeEntry(190, "fsetxattr", kInt, kString, kGen, kInt, kHex), MakeEntry(191, "getxattr", kPath, kString, kGen, kInt), MakeEntry(192, "lgetxattr", kPath, kString, kGen, kInt), MakeEntry(193, "fgetxattr", kInt, kString, kGen, kInt), MakeEntry(194, "listxattr", kPath, kGen, kInt), MakeEntry(195, "llistxattr", kPath, kGen, kInt), MakeEntry(196, "flistxattr", kInt, kGen, kInt), MakeEntry(197, "removexattr", kPath, kString), MakeEntry(198, "lremovexattr", kPath, kString), MakeEntry(199, "fremovexattr", kInt, kString), MakeEntry(200, "tkill", kInt, kSignal), MakeEntry(201, "time", kHex), MakeEntry(202, "futex", kGen, kInt, kInt, kGen, kGen, kInt), MakeEntry(203, "sched_setaffinity", kInt, kInt, kHex), MakeEntry(204, "sched_getaffinity", kInt, kInt, kHex), MakeEntry(205, "set_thread_area", kHex), MakeEntry(206, "io_setup", kInt, kHex), MakeEntry(207, "io_destroy", kInt), MakeEntry(208, "io_getevents", kInt, kInt, kInt, kHex, kHex), MakeEntry(209, "io_submit", kInt, kInt, kHex), MakeEntry(210, "io_cancel", kInt, kHex, kHex), MakeEntry(211, "get_thread_area", kHex), MakeEntry(212, "lookup_dcookie", kInt, kString, kInt), MakeEntry(213, "epoll_create", kInt), MakeEntry(214, "epoll_ctl_old", UnknownArguments()), MakeEntry(215, "epoll_wait_old", UnknownArguments()), MakeEntry(216, "remap_file_pages", kGen, kInt, kInt, kInt, kHex), MakeEntry(217, "getdents64", kInt, kHex, kInt), MakeEntry(218, "set_tid_address", kHex), MakeEntry(219, "restart_syscall"), MakeEntry(220, "semtimedop", kInt, kHex, kInt, kHex), MakeEntry(221, "fadvise64", kInt, kInt, kInt, kInt), MakeEntry(222, "timer_create", kInt, kHex, kHex), MakeEntry(223, "timer_settime", kInt, kHex, kHex, kHex), MakeEntry(224, "timer_gettime", kInt, kHex), MakeEntry(225, "timer_getoverrun", kInt), MakeEntry(226, "timer_delete", kInt), MakeEntry(227, "clock_settime", kInt, kHex), MakeEntry(228, "clock_gettime", kInt, kHex), MakeEntry(229, "clock_getres", kInt, kHex), MakeEntry(230, "clock_nanosleep", kInt, kHex, kHex, kHex), MakeEntry(231, "exit_group", kInt), MakeEntry(232, "epoll_wait", kInt, kHex, kInt, kInt), MakeEntry(233, "epoll_ctl", kInt, kInt, kInt, kHex), MakeEntry(234, "tgkill", kInt, kInt, kSignal), MakeEntry(235, "utimes", kPath, kHex), MakeEntry(236, "vserver", UnknownArguments()), MakeEntry(237, "mbind", kGen, kInt, kInt, kHex, kInt, kHex), MakeEntry(238, "set_mempolicy", kInt, kHex, kInt), MakeEntry(239, "get_mempolicy", kInt, kHex, kInt, kInt, kHex), MakeEntry(240, "mq_open", kString, kHex, kOct, kHex), MakeEntry(241, "mq_unlink", kString), MakeEntry(242, "mq_timedsend", kHex, kHex, kInt, kInt, kHex), MakeEntry(243, "mq_timedreceive", kHex, kHex, kInt, kHex, kHex), MakeEntry(244, "mq_notify", kHex, kHex), MakeEntry(245, "mq_getsetattr", kHex, kHex, kHex), MakeEntry(246, "kexec_load", kHex, kInt, kHex, kHex), MakeEntry(247, "waitid", kInt, kInt, kHex, kInt, kHex), MakeEntry(248, "add_key", kString, kString, kGen, kInt, kInt), MakeEntry(249, "request_key", kString, kString, kHex, kInt), MakeEntry(250, "keyctl", kInt, kInt, kInt, kInt, kInt), MakeEntry(251, "ioprio_set", kInt, kInt, kInt), MakeEntry(252, "ioprio_get", kInt, kInt), MakeEntry(253, "inotify_init"), MakeEntry(254, "inotify_add_watch", kInt, kPath, kHex), MakeEntry(255, "inotify_rm_watch", kInt, kInt), MakeEntry(256, "migrate_pages", kInt, kInt, kHex, kHex), MakeEntry(257, "openat", kInt, kPath, kHex, kOct), MakeEntry(258, "mkdirat", kInt, kPath, kOct), MakeEntry(259, "mknodat", kInt, kPath, kOct, kHex), MakeEntry(260, "fchownat", kInt, kPath, kInt, kInt, kHex), MakeEntry(261, "futimesat", kInt, kPath, kHex), MakeEntry(262, "newfstatat", kInt, kPath, kHex, kHex), MakeEntry(263, "unlinkat", kInt, kPath, kHex), MakeEntry(264, "renameat", kInt, kPath, kInt, kPath), MakeEntry(265, "linkat", kInt, kPath, kInt, kPath, kHex), MakeEntry(266, "symlinkat", kPath, kInt, kPath), MakeEntry(267, "readlinkat", kInt, kPath, kHex, kInt), MakeEntry(268, "fchmodat", kInt, kPath, kOct), MakeEntry(269, "faccessat", kInt, kPath, kInt, kHex), MakeEntry(270, "pselect6", kInt, kHex, kHex, kHex, kHex), MakeEntry(271, "ppoll", kHex, kInt, kHex, kHex, kInt), MakeEntry(272, "unshare", kHex), MakeEntry(273, "set_robust_list", kHex, kInt), MakeEntry(274, "get_robust_list", kInt, kHex, kHex), MakeEntry(275, "splice", kInt, kHex, kInt, kHex, kInt, kHex), MakeEntry(276, "tee", kInt, kInt, kInt, kHex), MakeEntry(277, "sync_file_range", kInt, kInt, kInt, kHex), MakeEntry(278, "vmsplice", kInt, kHex, kInt, kInt), MakeEntry(279, "move_pages", kInt, kInt, kHex, kHex, kHex, kHex), MakeEntry(280, "utimensat", kInt, kPath, kHex, kHex), MakeEntry(281, "epoll_pwait", kInt, kHex, kInt, kInt, kHex, kInt), MakeEntry(282, "signalfd", kInt, kHex, kHex), MakeEntry(283, "timerfd_create", kInt, kHex), MakeEntry(284, "eventfd", kInt), MakeEntry(285, "fallocate", kInt, kOct, kInt, kInt), MakeEntry(286, "timerfd_settime", kInt, kHex, kHex, kHex), MakeEntry(287, "timerfd_gettime", kInt, kHex), MakeEntry(288, "accept4", kInt, kHex, kHex, kInt), MakeEntry(289, "signalfd4", kInt, kHex, kHex, kHex), MakeEntry(290, "eventfd2", kInt, kHex), MakeEntry(291, "epoll_create1", kHex), MakeEntry(292, "dup3", kInt, kInt, kHex), MakeEntry(293, "pipe2", kHex, kHex), MakeEntry(294, "inotify_init1", kHex), MakeEntry(295, "preadv", kInt, kHex, kInt, kInt, kInt), MakeEntry(296, "pwritev", kInt, kHex, kInt, kInt, kInt), MakeEntry(297, "rt_tgsigqueueinfo", kInt, kInt, kInt, kHex), MakeEntry(298, "perf_event_open", kHex, kInt, kInt, kInt, kHex), MakeEntry(299, "recvmmsg", kInt, kHex, kInt, kHex, kHex), MakeEntry(300, "fanotify_init", kHex, kHex), MakeEntry(301, "fanotify_mark", kInt, kHex, kHex, kInt, kPath), MakeEntry(302, "prlimit64", kInt, kInt, kHex, kHex), MakeEntry(303, "name_to_handle_at", kInt, kPath, kHex, kHex, kHex), MakeEntry(304, "open_by_handle_at", kInt, kHex, kHex), MakeEntry(305, "clock_adjtime", kInt, kHex), MakeEntry(306, "syncfs", kInt), MakeEntry(307, "sendmmsg", kInt, kHex, kInt, kHex), MakeEntry(308, "setns", kInt, kHex), MakeEntry(309, "getcpu", kHex, kHex, kHex), MakeEntry(310, "process_vm_readv", kInt, kHex, kInt, kHex, kInt, kInt), MakeEntry(311, "process_vm_writev", kInt, kHex, kInt, kHex, kInt, kInt), MakeEntry(312, "kcmp", kInt, kInt, kInt, kInt, kInt), MakeEntry(313, "finit_module", kInt, kString, kHex), MakeEntry(314, "sched_setattr", kInt, kHex, kHex), MakeEntry(315, "sched_getattr", kInt, kHex, kInt, kHex), MakeEntry(316, "renameat2", kInt, kPath, kInt, kPath, kHex), MakeEntry(317, "seccomp", kInt, kHex, kHex), MakeEntry(318, "getrandom", kGen, kInt, kHex), MakeEntry(319, "memfd_create", kString, kHex), MakeEntry(320, "kexec_file_load", kInt, kInt, kInt, kString, kHex), MakeEntry(321, "bpf", kInt, kHex, kInt), MakeEntry(322, "execveat", kInt, kPath, kHex, kHex, kHex), MakeEntry(323, "userfaultfd", kHex), MakeEntry(324, "membarrier", kInt, kHex), MakeEntry(325, "mlock2", kHex, kInt, kHex), MakeEntry(326, "copy_file_range", kInt, kHex, kInt, kHex, kInt, kHex), MakeEntry(327, "preadv2", kInt, kHex, kInt, kInt, kInt, kHex), MakeEntry(328, "pwritev2", kInt, kHex, kInt, kInt, kInt, kHex), MakeEntry(329, "pkey_mprotect", kInt, kInt, kHex, kInt), MakeEntry(330, "pkey_alloc", kInt, kInt), MakeEntry(331, "pkey_free", kInt), MakeEntry(332, "statx", kInt, kPath, kHex, kHex, kHex), MakeEntry(333, "io_pgetevents", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(334, "rseq", kHex, kInt, kHex, kHex), // clang-format on }; static_assert(IsSorted(kSyscallDataX8664, SyscallTable::Entry::BySyscallNr), "Syscalls should be sorted"); constexpr std::array kSyscallDataX8632 = { // clang-format off MakeEntry(0, "restart_syscall", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(1, "exit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(2, "fork", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(3, "read", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(4, "write", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(5, "open", kPath, kHex, kOct, kHex, kHex, kHex), MakeEntry(6, "close", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(7, "waitpid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(8, "creat", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(9, "link", kPath, kPath, kHex, kHex, kHex, kHex), MakeEntry(10, "unlink", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(11, "execve", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(12, "chdir", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(13, "time", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(14, "mknod", kPath, kOct, kHex, kHex, kHex, kHex), MakeEntry(15, "chmod", kPath, kOct, kHex, kHex, kHex, kHex), MakeEntry(16, "lchown", kPath, kInt, kInt, kHex, kHex, kHex), MakeEntry(17, "break", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(18, "oldstat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(19, "lseek", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(20, "getpid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(21, "mount", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(22, "umount", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(23, "setuid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(24, "getuid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(25, "stime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(26, "ptrace", kHex, kHex, kHex, kHex), MakeEntry(27, "alarm", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(28, "oldfstat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(29, "pause", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(30, "utime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(31, "stty", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(32, "gtty", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(33, "access", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(34, "nice", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(35, "ftime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(36, "sync", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(37, "kill", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(38, "rename", kPath, kPath, kHex, kHex, kHex, kHex), MakeEntry(39, "mkdir", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(40, "rmdir", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(41, "dup", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(42, "pipe", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(43, "times", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(44, "prof", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(45, "brk", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(46, "setgid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(47, "getgid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(48, "signal", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(49, "geteuid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(50, "getegid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(51, "acct", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(52, "umount2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(53, "lock", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(54, "ioctl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(55, "fcntl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(56, "mpx", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(57, "setpgid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(58, "ulimit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(59, "oldolduname", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(60, "umask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(61, "chroot", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(62, "ustat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(63, "dup2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(64, "getppid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(65, "getpgrp", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(66, "setsid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(67, "sigaction", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(68, "sgetmask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(69, "ssetmask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(70, "setreuid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(71, "setregid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(72, "sigsuspend", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(73, "sigpending", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(74, "sethostname", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(75, "setrlimit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(76, "getrlimit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(77, "getrusage", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(78, "gettimeofday", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(79, "settimeofday", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(80, "getgroups", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(81, "setgroups", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(82, "select", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(83, "symlink", kPath, kPath, kHex, kHex, kHex, kHex), MakeEntry(84, "oldlstat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(85, "readlink", kPath, kHex, kInt, kHex, kHex, kHex), MakeEntry(86, "uselib", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(87, "swapon", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(88, "reboot", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(89, "readdir", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(90, "mmap", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(91, "munmap", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(92, "truncate", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(93, "ftruncate", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(94, "fchmod", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(95, "fchown", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(96, "getpriority", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(97, "setpriority", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(98, "profil", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(99, "statfs", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(100, "fstatfs", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(101, "ioperm", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(102, "socketcall", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(103, "syslog", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(104, "setitimer", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(105, "getitimer", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(106, "stat", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(107, "lstat", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(108, "fstat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(109, "olduname", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(110, "iopl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(111, "vhangup", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(112, "idle", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(113, "vm86old", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(114, "wait4", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(115, "swapoff", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(116, "sysinfo", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(117, "ipc", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(118, "fsync", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(119, "sigreturn", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(120, "clone", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(121, "setdomainname", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(122, "uname", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(123, "modify_ldt", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(124, "adjtimex", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(125, "mprotect", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(126, "sigprocmask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(127, "create_module", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(128, "init_module", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(129, "delete_module", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(130, "get_kernel_syms", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(131, "quotactl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(132, "getpgid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(133, "fchdir", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(134, "bdflush", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(135, "sysfs", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(136, "personality", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(137, "afs_syscall", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(138, "setfsuid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(139, "setfsgid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(140, "_llseek", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(141, "getdents", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(142, "_newselect", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(143, "flock", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(144, "msync", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(145, "readv", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(146, "writev", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(147, "getsid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(148, "fdatasync", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(149, "_sysctl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(150, "mlock", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(151, "munlock", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(152, "mlockall", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(153, "munlockall", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(154, "sched_setparam", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(155, "sched_getparam", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(156, "sched_setscheduler", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(157, "sched_getscheduler", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(158, "sched_yield", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(159, "sched_get_priority_max", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(160, "sched_get_priority_min", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(161, "sched_rr_get_interval", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(162, "nanosleep", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(163, "mremap", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(164, "setresuid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(165, "getresuid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(166, "vm86", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(167, "query_module", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(168, "poll", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(169, "nfsservctl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(170, "setresgid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(171, "getresgid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(172, "prctl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(173, "rt_sigreturn", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(174, "rt_sigaction", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(175, "rt_sigprocmask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(176, "rt_sigpending", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(177, "rt_sigtimedwait", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(178, "rt_sigqueueinfo", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(179, "rt_sigsuspend", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(180, "pread64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(181, "pwrite64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(182, "chown", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(183, "getcwd", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(184, "capget", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(185, "capset", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(186, "sigaltstack", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(187, "sendfile", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(188, "getpmsg", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(189, "putpmsg", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(190, "vfork", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(191, "ugetrlimit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(192, "mmap2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(193, "truncate64", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(194, "ftruncate64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(195, "stat64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(196, "lstat64", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(197, "fstat64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(198, "lchown32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(199, "getuid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(200, "getgid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(201, "geteuid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(202, "getegid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(203, "setreuid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(204, "setregid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(205, "getgroups32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(206, "setgroups32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(207, "fchown32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(208, "setresuid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(209, "getresuid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(210, "setresgid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(211, "getresgid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(212, "chown32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(213, "setuid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(214, "setgid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(215, "setfsuid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(216, "setfsgid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(217, "pivot_root", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(218, "mincore", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(219, "madvise", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(220, "getdents64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(221, "fcntl64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(222, "unused1-222", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(223, "unused2-223", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(224, "gettid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(225, "readahead", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(226, "setxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(227, "lsetxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(228, "fsetxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(229, "getxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(230, "lgetxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(231, "fgetxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(232, "listxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(233, "llistxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(234, "flistxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(235, "removexattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(236, "lremovexattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(237, "fremovexattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(238, "tkill", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(239, "sendfile64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(240, "futex", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(241, "sched_setaffinity", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(242, "sched_getaffinity", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(243, "set_thread_area", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(244, "get_thread_area", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(245, "io_setup", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(246, "io_destroy", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(247, "io_getevents", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(248, "io_submit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(249, "io_cancel", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(250, "fadvise64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(251, "251-old_sys_set_zone_reclaim", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(252, "exit_group", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(253, "lookup_dcookie", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(254, "epoll_create", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(255, "epoll_ctl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(256, "epoll_wait", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(257, "remap_file_pages", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(258, "set_tid_address", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(259, "timer_create", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(260, "timer_settime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(261, "timer_gettime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(262, "timer_getoverrun", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(263, "timer_delete", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(264, "clock_settime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(265, "clock_gettime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(266, "clock_getres", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(267, "clock_nanosleep", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(268, "statfs64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(269, "fstatfs64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(270, "tgkill", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(271, "utimes", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(272, "fadvise64_64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(273, "vserver", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(274, "mbind", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(275, "get_mempolicy", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(276, "set_mempolicy", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(277, "mq_open", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(278, "mq_unlink", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(279, "mq_timedsend", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(280, "mq_timedreceive", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(281, "mq_notify", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(282, "mq_getsetattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(283, "kexec_load", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(284, "waitid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(285, "285-old_sys_setaltroot", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(286, "add_key", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(287, "request_key", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(288, "keyctl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(289, "ioprio_set", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(290, "ioprio_get", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(291, "inotify_init", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(292, "inotify_add_watch", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(293, "inotify_rm_watch", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(294, "migrate_pages", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(295, "openat", kHex, kPath, kOct, kHex, kHex, kHex), MakeEntry(296, "mkdirat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(297, "mknodat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(298, "fchownat", kHex, kPath, kHex, kHex, kHex, kHex), MakeEntry(299, "futimesat", kHex, kPath, kHex, kHex, kHex, kHex), MakeEntry(300, "fstatat64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(301, "unlinkat", kHex, kPath, kHex, kHex, kHex, kHex), MakeEntry(302, "renameat", kHex, kPath, kHex, kPath, kHex, kHex), MakeEntry(303, "linkat", kHex, kPath, kHex, kPath, kHex, kHex), MakeEntry(304, "symlinkat", kPath, kHex, kPath, kHex, kHex, kHex), MakeEntry(305, "readlinkat", kHex, kPath, kHex, kHex, kHex, kHex), MakeEntry(306, "fchmodat", kHex, kPath, kHex, kHex, kHex, kHex), MakeEntry(307, "faccessat", kHex, kPath, kHex, kHex, kHex, kHex), MakeEntry(308, "pselect6", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(309, "ppoll", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(310, "unshare", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(311, "set_robust_list", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(312, "get_robust_list", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(313, "splice", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(314, "sync_file_range", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(315, "tee", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(316, "vmsplice", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(317, "move_pages", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(318, "getcpu", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(319, "epoll_pwait", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(320, "utimensat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(321, "signalfd", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(322, "timerfd_create", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(323, "eventfd", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(324, "fallocate", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(325, "timerfd_settime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(326, "timerfd_gettime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(327, "signalfd4", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(328, "eventfd2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(329, "epoll_create1", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(330, "dup3", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(331, "pipe2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(332, "inotify_init1", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(333, "preadv", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(334, "pwritev", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(335, "rt_tgsigqueueinfo", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(336, "perf_event_open", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(337, "recvmmsg", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(338, "fanotify_init", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(339, "fanotify_mark", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(340, "prlimit64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(341, "name_to_handle_at", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(342, "open_by_handle_at", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(343, "clock_adjtime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(344, "syncfs", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(345, "sendmmsg", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(346, "setns", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(347, "process_vm_readv", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(348, "process_vm_writev", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(349, "kcmp", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(350, "finit_module", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(351, "sched_setattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(352, "sched_getattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(353, "renameat2", kHex, kPath, kHex, kPath, kHex, kHex), MakeEntry(354, "seccomp", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(355, "getrandom", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(356, "memfd_create", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(357, "bpf", kHex, kHex, kHex, kHex, kHex, kHex), // clang-format on }; static_assert(IsSorted(kSyscallDataX8632, SyscallTable::Entry::BySyscallNr), "Syscalls should be sorted"); // http://lxr.free-electrons.com/source/arch/powerpc/include/uapi/asm/unistd.h // Note: PPC64 syscalls can have up to 7 register arguments, but nobody is // using the 7th argument - probably for x64 compatibility reasons. constexpr std::array kSyscallDataPPC64LE = { // clang-format off MakeEntry(0, "restart_syscall", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(1, "exit", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(2, "fork", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(3, "read", kInt, kHex, kInt), MakeEntry(4, "write", kInt, kHex, kInt, kGen, kGen, kGen), MakeEntry(5, "open", kPath, kHex, kOct, kGen, kGen, kGen), MakeEntry(6, "close", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(7, "waitpid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(8, "creat", kPath, kOct, kGen, kGen, kGen, kGen), MakeEntry(9, "link", kPath, kPath, kGen, kGen, kGen, kGen), MakeEntry(10, "unlink", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(11, "execve", kPath, kHex, kHex, kGen, kGen, kGen), MakeEntry(12, "chdir", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(13, "time", kHex, kGen, kGen, kGen, kGen, kGen), MakeEntry(14, "mknod", kPath, kOct, kHex, kGen, kGen, kGen), MakeEntry(15, "chmod", kPath, kOct, kGen, kGen, kGen, kGen), MakeEntry(16, "lchown", kPath, kInt, kInt, kGen, kGen, kGen), MakeEntry(17, "break", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(18, "oldstat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(19, "lseek", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(20, "getpid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(21, "mount", kPath, kPath, kString, kHex, kGen, kGen), MakeEntry(22, "umount", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(23, "setuid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(24, "getuid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(25, "stime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(26, "ptrace", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(27, "alarm", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(28, "oldfstat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(29, "pause", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(30, "utime", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(31, "stty", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(32, "gtty", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(33, "access", kPath, kHex, kGen, kGen, kGen, kGen), MakeEntry(34, "nice", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(35, "ftime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(36, "sync", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(37, "kill", kInt, kSignal, kGen, kGen, kGen, kGen), MakeEntry(38, "rename", kPath, kPath, kGen, kGen, kGen, kGen), MakeEntry(39, "mkdir", kPath, kOct, kGen, kGen, kGen, kGen), MakeEntry(40, "rmdir", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(41, "dup", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(42, "pipe", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(43, "times", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(44, "prof", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(45, "brk", kHex, kGen, kGen, kGen, kGen, kGen), MakeEntry(46, "setgid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(47, "getgid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(48, "signal", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(49, "geteuid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(50, "getegid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(51, "acct", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(52, "umount2", kPath, kHex, kGen, kGen, kGen, kGen), MakeEntry(53, "lock", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(54, "ioctl", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(55, "fcntl", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(56, "mpx", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(57, "setpgid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(58, "ulimit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(59, "oldolduname", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(60, "umask", kHex, kGen, kGen, kGen, kGen, kGen), MakeEntry(61, "chroot", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(62, "ustat", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(63, "dup2", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(64, "getppid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(65, "getpgrp", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(66, "setsid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(67, "sigaction", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(68, "sgetmask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(69, "ssetmask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(70, "setreuid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(71, "setregid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(72, "sigsuspend", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(73, "sigpending", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(74, "sethostname", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(75, "setrlimit", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(76, "getrlimit", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(77, "getrusage", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(78, "gettimeofday", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(79, "settimeofday", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(80, "getgroups", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(81, "setgroups", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(82, "select", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(83, "symlink", kPath, kPath, kGen, kGen, kGen, kGen), MakeEntry(84, "oldlstat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(85, "readlink", kPath, kGen, kInt, kGen, kGen, kGen), MakeEntry(86, "uselib", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(87, "swapon", kPath, kHex, kGen, kGen, kGen, kGen), MakeEntry(88, "reboot", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(89, "readdir", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(90, "mmap", kHex, kInt, kHex, kHex, kInt, kInt), MakeEntry(91, "munmap", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(92, "truncate", kPath, kInt, kGen, kGen, kGen, kGen), MakeEntry(93, "ftruncate", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(94, "fchmod", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(95, "fchown", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(96, "getpriority", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(97, "setpriority", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(98, "profil", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(99, "statfs", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(100, "fstatfs", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(101, "ioperm", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(102, "socketcall", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(103, "syslog", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(104, "setitimer", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(105, "getitimer", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(106, "stat", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(107, "lstat", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(108, "fstat", kInt, kHex, kGen, kGen, kGen, kGen), MakeEntry(109, "olduname", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(110, "iopl", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(111, "vhangup", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(112, "idle", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(113, "vm86", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(114, "wait4", kInt, kHex, kHex, kHex, kGen, kGen), MakeEntry(115, "swapoff", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(116, "sysinfo", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(117, "ipc", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(118, "fsync", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(119, "sigreturn", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(120, "clone", kCloneFlag, kHex, kHex, kHex, kHex, kGen), MakeEntry(121, "setdomainname", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(122, "uname", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(123, "modify_ldt", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(124, "adjtimex", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(125, "mprotect", kHex, kHex, kHex, kGen, kGen, kGen), MakeEntry(126, "sigprocmask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(127, "create_module", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(128, "init_module", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(129, "delete_module", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(130, "get_kernel_syms", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(131, "quotactl", kInt, kPath, kInt, kGen, kGen, kGen), MakeEntry(132, "getpgid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(133, "fchdir", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(134, "bdflush", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(135, "sysfs", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(136, "personality", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(137, "afs_syscall", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(138, "setfsuid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(139, "setfsgid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(140, "_llseek", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(141, "getdents", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(142, "_newselect", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(143, "flock", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(144, "msync", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(145, "readv", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(146, "writev", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(147, "getsid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(148, "fdatasync", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(149, "_sysctl", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(150, "mlock", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(151, "munlock", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(152, "mlockall", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(153, "munlockall", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(154, "sched_setparam", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(155, "sched_getparam", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(156, "sched_setscheduler", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(157, "sched_getscheduler", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(158, "sched_yield", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(159, "sched_get_priority_max", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(160, "sched_get_priority_min", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(161, "sched_rr_get_interval", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(162, "nanosleep", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(163, "mremap", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(164, "setresuid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(165, "getresuid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(166, "query_module", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(167, "poll", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(168, "nfsservctl", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(169, "setresgid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(170, "getresgid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(171, "prctl", kInt, kHex, kHex, kHex, kHex, kGen), MakeEntry(172, "rt_sigreturn", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(173, "rt_sigaction", kSignal, kHex, kHex, kInt, kGen, kGen), MakeEntry(174, "rt_sigprocmask", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(175, "rt_sigpending", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(176, "rt_sigtimedwait", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(177, "rt_sigqueueinfo", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(178, "rt_sigsuspend", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(179, "pread64", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(180, "pwrite64", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(181, "chown", kPath, kInt, kInt, kGen, kGen, kGen), MakeEntry(182, "getcwd", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(183, "capget", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(184, "capset", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(185, "sigaltstack", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(186, "sendfile", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(187, "getpmsg", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(188, "putpmsg", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(189, "vfork", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(190, "ugetrlimit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(191, "readahead", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(192, "mmap2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(193, "truncate64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(194, "ftruncate64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(195, "stat64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(196, "lstat64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(197, "fstat64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(198, "pciconfig_read", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(199, "pciconfig_write", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(200, "pciconfig_iobase", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(201, "multiplexer", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(202, "getdents64", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(203, "pivot_root", kPath, kPath, kGen, kGen, kGen, kGen), MakeEntry(204, "fcntl64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(205, "madvise", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(206, "mincore", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(207, "gettid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(208, "tkill", kInt, kSignal, kGen, kGen, kGen, kGen), MakeEntry(209, "setxattr", kPath, kString, kGen, kInt, kHex, kGen), MakeEntry(210, "lsetxattr", kPath, kString, kGen, kInt, kHex, kGen), MakeEntry(211, "fsetxattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(212, "getxattr", kPath, kString, kGen, kInt, kGen, kGen), MakeEntry(213, "lgetxattr", kPath, kString, kGen, kInt, kGen, kGen), MakeEntry(214, "fgetxattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(215, "listxattr", kPath, kGen, kInt, kGen, kGen, kGen), MakeEntry(216, "llistxattr", kPath, kGen, kInt, kGen, kGen, kGen), MakeEntry(217, "flistxattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(218, "removexattr", kPath, kString, kGen, kGen, kGen, kGen), MakeEntry(219, "lremovexattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(220, "fremovexattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(221, "futex", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(222, "sched_setaffinity", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(223, "sched_getaffinity", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(225, "tuxcall", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(226, "sendfile64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(227, "io_setup", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(228, "io_destroy", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(229, "io_getevents", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(230, "io_submit", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(231, "io_cancel", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(232, "set_tid_address", kHex, kGen, kGen, kGen, kGen, kGen), MakeEntry(233, "fadvise64", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(234, "exit_group", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(235, "lookup_dcookie", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(236, "epoll_create", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(237, "epoll_ctl", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(238, "epoll_wait", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(239, "remap_file_pages", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(240, "timer_create", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(241, "timer_settime", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(242, "timer_gettime", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(243, "timer_getoverrun", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(244, "timer_delete", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(245, "clock_settime", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(246, "clock_gettime", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(247, "clock_getres", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(248, "clock_nanosleep", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(249, "swapcontext", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(250, "tgkill", kInt, kInt, kSignal, kGen, kGen, kGen), MakeEntry(251, "utimes", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(252, "statfs64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(253, "fstatfs64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(254, "fadvise64_64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(255, "rtas", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(256, "sys_debug_setcontext", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(258, "migrate_pages", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(259, "mbind", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(260, "get_mempolicy", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(261, "set_mempolicy", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(262, "mq_open", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(263, "mq_unlink", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(264, "mq_timedsend", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(265, "mq_timedreceive", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(266, "mq_notify", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(267, "mq_getsetattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(268, "kexec_load", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(269, "add_key", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(270, "request_key", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(271, "keyctl", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(272, "waitid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(273, "ioprio_set", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(274, "ioprio_get", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(275, "inotify_init", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(276, "inotify_add_watch", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(277, "inotify_rm_watch", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(278, "spu_run", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(279, "spu_create", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(280, "pselect6", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(281, "ppoll", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(282, "unshare", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(283, "splice", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(284, "tee", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(285, "vmsplice", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(286, "openat", kGen, kPath, kOct, kHex, kGen, kGen), MakeEntry(287, "mkdirat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(288, "mknodat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(289, "fchownat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(290, "futimesat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(291, "newfstatat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(292, "unlinkat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(293, "renameat", kGen, kPath, kGen, kPath, kGen, kGen), MakeEntry(294, "linkat", kGen, kPath, kGen, kPath, kGen, kGen), MakeEntry(295, "symlinkat", kPath, kGen, kPath, kGen, kGen, kGen), MakeEntry(296, "readlinkat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(297, "fchmodat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(298, "faccessat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(299, "get_robust_list", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(300, "set_robust_list", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(301, "move_pages", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(302, "getcpu", kHex, kHex, kHex, kGen, kGen, kGen), MakeEntry(303, "epoll_pwait", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(304, "utimensat", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(305, "signalfd", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(306, "timerfd_create", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(307, "eventfd", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(308, "sync_file_range2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(309, "fallocate", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(310, "subpage_prot", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(311, "timerfd_settime", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(312, "timerfd_gettime", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(313, "signalfd4", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(314, "eventfd2", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(315, "epoll_create1", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(316, "dup3", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(317, "pipe2", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(318, "inotify_init1", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(319, "perf_event_open", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(320, "preadv", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(321, "pwritev", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(322, "rt_tgsigqueueinfo", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(323, "fanotify_init", kHex, kHex, kInt, kGen, kGen, kGen), MakeEntry(324, "fanotify_mark", kInt, kHex, kInt, kPath, kGen, kGen), MakeEntry(325, "prlimit64", kInt, kInt, kHex, kHex, kGen, kGen), MakeEntry(326, "socket", kAddressFamily, kInt, kInt, kGen, kGen, kGen), MakeEntry(327, "bind", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(328, "connect", kInt, kSockaddr, kInt, kGen, kGen, kGen), MakeEntry(329, "listen", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(330, "accept", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(331, "getsockname", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(332, "getpeername", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(333, "socketpair", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(334, "send", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(335, "sendto", kInt, kGen, kInt, kHex, kSockaddr, kInt), MakeEntry(336, "recv", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(337, "recvfrom", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(338, "shutdown", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(339, "setsockopt", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(340, "getsockopt", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(341, "sendmsg", kInt, kSockmsghdr, kHex, kGen, kGen, kGen), MakeEntry(342, "recvmsg", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(343, "recvmmsg", kInt, kHex, kHex, kHex, kGen, kGen), MakeEntry(344, "accept4", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(345, "name_to_handle_at", kInt, kGen, kHex, kHex, kHex, kGen), MakeEntry(346, "open_by_handle_at", kInt, kHex, kHex, kGen, kGen, kGen), MakeEntry(347, "clock_adjtime", kInt, kHex, kGen, kGen, kGen, kGen), MakeEntry(348, "syncfs", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(349, "sendmmsg", kInt, kHex, kInt, kHex, kGen, kGen), MakeEntry(350, "setns", kInt, kHex, kGen, kGen, kGen, kGen), MakeEntry(351, "process_vm_readv", kInt, kHex, kInt, kHex, kInt, kInt), MakeEntry(352, "process_vm_writev", kInt, kHex, kInt, kHex, kInt, kInt), MakeEntry(353, "finit_module", kInt, kPath, kHex, kGen, kGen, kGen), MakeEntry(354, "kcmp", kInt, kInt, kInt, kHex, kHex, kGen), MakeEntry(355, "sched_setattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(356, "sched_getattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(357, "renameat2", kGen, kPath, kGen, kPath, kGen, kGen), MakeEntry(358, "seccomp", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(359, "getrandom", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(360, "memfd_create", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(361, "bpf", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(362, "execveat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(363, "switch_endian", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(364, "userfaultfd", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(365, "membarrier", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(378, "mlock2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(379, "copy_file_range", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(380, "preadv2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(381, "pwritev2", kHex, kHex, kHex, kHex, kHex, kHex), // clang-format on }; static_assert(IsSorted(kSyscallDataPPC64LE, SyscallTable::Entry::BySyscallNr), "Syscalls should be sorted"); // TODO(cblichmann): Confirm the entries in this list. // https://github.com/torvalds/linux/blob/v5.8/include/uapi/asm-generic/unistd.h constexpr std::array kSyscallDataArm64 = { // clang-format off MakeEntry(0, "io_setup", UnknownArguments()), MakeEntry(1, "io_destroy", UnknownArguments()), MakeEntry(2, "io_submit", UnknownArguments()), MakeEntry(3, "io_cancel", UnknownArguments()), MakeEntry(4, "io_getevents", UnknownArguments()), MakeEntry(5, "setxattr", kPath, kString, kGen, kInt, kHex, kGen), MakeEntry(6, "lsetxattr", kPath, kString, kGen, kInt, kHex, kGen), MakeEntry(7, "fsetxattr", UnknownArguments()), MakeEntry(8, "getxattr", kPath, kString, kGen, kInt, kGen, kGen), MakeEntry(9, "lgetxattr", kPath, kString, kGen, kInt, kGen, kGen), MakeEntry(10, "fgetxattr", UnknownArguments()), MakeEntry(11, "listxattr", kPath, kGen, kInt, kGen, kGen, kGen), MakeEntry(12, "llistxattr", kPath, kGen, kInt, kGen, kGen, kGen), MakeEntry(13, "flistxattr", UnknownArguments()), MakeEntry(14, "removexattr", kPath, kString, kGen, kGen, kGen, kGen), MakeEntry(15, "lremovexattr", UnknownArguments()), MakeEntry(16, "fremovexattr", UnknownArguments()), MakeEntry(17, "getcwd", UnknownArguments()), MakeEntry(18, "lookup_dcookie", UnknownArguments()), MakeEntry(19, "eventfd2", UnknownArguments()), MakeEntry(20, "epoll_create1", UnknownArguments()), MakeEntry(21, "epoll_ctl", UnknownArguments()), MakeEntry(22, "epoll_pwait", UnknownArguments()), MakeEntry(23, "dup", UnknownArguments()), MakeEntry(24, "dup3", UnknownArguments()), MakeEntry(25, "fcntl", UnknownArguments()), MakeEntry(26, "inotify_init1", UnknownArguments()), MakeEntry(27, "inotify_add_watch", UnknownArguments()), MakeEntry(28, "inotify_rm_watch", UnknownArguments()), MakeEntry(29, "ioctl", UnknownArguments()), MakeEntry(30, "ioprio_set", UnknownArguments()), MakeEntry(31, "ioprio_get", UnknownArguments()), MakeEntry(32, "flock", UnknownArguments()), MakeEntry(33, "mknodat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(34, "mkdirat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(35, "unlinkat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(36, "symlinkat", kPath, kGen, kPath, kGen, kGen, kGen), MakeEntry(37, "linkat", kGen, kPath, kGen, kPath, kGen, kGen), MakeEntry(38, "renameat", kGen, kPath, kGen, kPath, kGen, kGen), MakeEntry(39, "umount2", kPath, kHex, kGen, kGen, kGen, kGen), MakeEntry(40, "mount", kPath, kPath, kString, kHex, kGen, kGen), MakeEntry(41, "pivot_root", kPath, kPath, kGen, kGen, kGen, kGen), MakeEntry(42, "nfsservctl", UnknownArguments()), MakeEntry(43, "statfs", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(44, "fstatfs", UnknownArguments()), MakeEntry(45, "truncate", kPath, kInt, kGen, kGen, kGen, kGen), MakeEntry(46, "ftruncate", UnknownArguments()), MakeEntry(47, "fallocate", UnknownArguments()), MakeEntry(48, "faccessat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(49, "chdir", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(50, "fchdir", UnknownArguments()), MakeEntry(51, "chroot", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(52, "fchmod", UnknownArguments()), MakeEntry(53, "fchmodat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(54, "fchownat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(55, "fchown", UnknownArguments()), MakeEntry(56, "openat", kGen, kPath, kOct, kHex, kGen, kGen), MakeEntry(57, "close", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(58, "vhangup", UnknownArguments()), MakeEntry(59, "pipe2", UnknownArguments()), MakeEntry(60, "quotactl", kInt, kPath, kInt, kGen, kGen, kGen), MakeEntry(61, "getdents64", UnknownArguments()), MakeEntry(62, "lseek", UnknownArguments()), MakeEntry(63, "read", kInt, kHex, kInt, kGen, kGen, kGen), MakeEntry(64, "write", kInt, kHex, kInt, kGen, kGen, kGen), MakeEntry(65, "readv", UnknownArguments()), MakeEntry(66, "writev", UnknownArguments()), MakeEntry(67, "pread64", UnknownArguments()), MakeEntry(68, "pwrite64", UnknownArguments()), MakeEntry(69, "preadv", UnknownArguments()), MakeEntry(70, "pwritev", UnknownArguments()), MakeEntry(71, "sendfile", UnknownArguments()), MakeEntry(72, "pselect6", UnknownArguments()), MakeEntry(73, "ppoll", UnknownArguments()), MakeEntry(74, "signalfd4", UnknownArguments()), MakeEntry(75, "vmsplice", UnknownArguments()), MakeEntry(76, "splice", UnknownArguments()), MakeEntry(77, "tee", UnknownArguments()), MakeEntry(78, "readlinkat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(79, "newfstatat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(80, "fstat", kInt, kHex, kGen, kGen, kGen, kGen), MakeEntry(81, "sync", UnknownArguments()), MakeEntry(82, "fsync", UnknownArguments()), MakeEntry(83, "fdatasync", UnknownArguments()), MakeEntry(84, "sync_file_range", UnknownArguments()), MakeEntry(85, "timerfd_create", UnknownArguments()), MakeEntry(86, "timerfd_settime", UnknownArguments()), MakeEntry(87, "timerfd_gettime", UnknownArguments()), MakeEntry(88, "utimensat", UnknownArguments()), MakeEntry(89, "acct", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(90, "capget", UnknownArguments()), MakeEntry(91, "capset", UnknownArguments()), MakeEntry(92, "personality", UnknownArguments()), MakeEntry(93, "exit", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(94, "exit_group", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(95, "waitid", UnknownArguments()), MakeEntry(96, "set_tid_address", kHex, kGen, kGen, kGen, kGen, kGen), MakeEntry(97, "unshare", UnknownArguments()), MakeEntry(98, "futex", UnknownArguments()), MakeEntry(99, "set_robust_list", UnknownArguments()), MakeEntry(100, "get_robust_list", UnknownArguments()), MakeEntry(101, "nanosleep", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(102, "getitimer", UnknownArguments()), MakeEntry(103, "setitimer", UnknownArguments()), MakeEntry(104, "kexec_load", UnknownArguments()), MakeEntry(105, "init_module", UnknownArguments()), MakeEntry(106, "delete_module", UnknownArguments()), MakeEntry(107, "timer_create", UnknownArguments()), MakeEntry(108, "timer_gettime", UnknownArguments()), MakeEntry(109, "timer_getoverrun", UnknownArguments()), MakeEntry(110, "timer_settime", UnknownArguments()), MakeEntry(111, "timer_delete", UnknownArguments()), MakeEntry(112, "clock_settime", UnknownArguments()), MakeEntry(113, "clock_gettime", UnknownArguments()), MakeEntry(114, "clock_getres", UnknownArguments()), MakeEntry(115, "clock_nanosleep", UnknownArguments()), MakeEntry(116, "syslog", UnknownArguments()), MakeEntry(117, "ptrace", UnknownArguments()), MakeEntry(118, "sched_setparam", UnknownArguments()), MakeEntry(119, "sched_setscheduler", UnknownArguments()), MakeEntry(120, "sched_getscheduler", UnknownArguments()), MakeEntry(121, "sched_getparam", UnknownArguments()), MakeEntry(122, "sched_setaffinity", UnknownArguments()), MakeEntry(123, "sched_getaffinity", UnknownArguments()), MakeEntry(124, "sched_yield", UnknownArguments()), MakeEntry(125, "sched_get_priority_max", UnknownArguments()), MakeEntry(126, "sched_get_priority_min", UnknownArguments()), MakeEntry(127, "sched_rr_get_interval", UnknownArguments()), MakeEntry(128, "restart_syscall", UnknownArguments()), MakeEntry(129, "kill", kInt, kSignal, kGen, kGen, kGen, kGen), MakeEntry(130, "tkill", kInt, kSignal, kGen, kGen, kGen, kGen), MakeEntry(131, "tgkill", kInt, kInt, kSignal, kGen, kGen, kGen), MakeEntry(132, "sigaltstack", UnknownArguments()), MakeEntry(133, "rt_sigsuspend", UnknownArguments()), MakeEntry(134, "rt_sigaction", kSignal, kHex, kHex, kInt, kGen, kGen), MakeEntry(135, "rt_sigprocmask", UnknownArguments()), MakeEntry(136, "rt_sigpending", UnknownArguments()), MakeEntry(137, "rt_sigtimedwait", UnknownArguments()), MakeEntry(138, "rt_sigqueueinfo", UnknownArguments()), MakeEntry(139, "rt_sigreturn", UnknownArguments()), MakeEntry(140, "setpriority", UnknownArguments()), MakeEntry(141, "getpriority", UnknownArguments()), MakeEntry(142, "reboot", UnknownArguments()), MakeEntry(143, "setregid", UnknownArguments()), MakeEntry(144, "setgid", UnknownArguments()), MakeEntry(145, "setreuid", UnknownArguments()), MakeEntry(146, "setuid", UnknownArguments()), MakeEntry(147, "setresuid", UnknownArguments()), MakeEntry(148, "getresuid", UnknownArguments()), MakeEntry(149, "setresgid", UnknownArguments()), MakeEntry(150, "getresgid", UnknownArguments()), MakeEntry(151, "setfsuid", UnknownArguments()), MakeEntry(152, "setfsgid", UnknownArguments()), MakeEntry(153, "times", UnknownArguments()), MakeEntry(154, "setpgid", UnknownArguments()), MakeEntry(155, "getpgid", UnknownArguments()), MakeEntry(156, "getsid", UnknownArguments()), MakeEntry(157, "setsid", UnknownArguments()), MakeEntry(158, "getgroups", UnknownArguments()), MakeEntry(159, "setgroups", UnknownArguments()), MakeEntry(160, "uname", UnknownArguments()), MakeEntry(161, "sethostname", UnknownArguments()), MakeEntry(162, "setdomainname", UnknownArguments()), MakeEntry(163, "getrlimit", UnknownArguments()), MakeEntry(164, "setrlimit", UnknownArguments()), MakeEntry(165, "getrusage", UnknownArguments()), MakeEntry(166, "umask", kHex, kGen, kGen, kGen, kGen, kGen), MakeEntry(167, "prctl", kInt, kHex, kHex, kHex, kHex, kGen), MakeEntry(168, "getcpu", kHex, kHex, kHex, kGen, kGen, kGen), MakeEntry(169, "gettimeofday", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(170, "settimeofday", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(171, "adjtimex", UnknownArguments()), MakeEntry(172, "getpid", UnknownArguments()), MakeEntry(173, "getppid", UnknownArguments()), MakeEntry(174, "getuid", UnknownArguments()), MakeEntry(175, "geteuid", UnknownArguments()), MakeEntry(176, "getgid", UnknownArguments()), MakeEntry(177, "getegid", UnknownArguments()), MakeEntry(178, "gettid", UnknownArguments()), MakeEntry(179, "sysinfo", UnknownArguments()), MakeEntry(180, "mq_open", UnknownArguments()), MakeEntry(181, "mq_unlink", UnknownArguments()), MakeEntry(182, "mq_timedsend", UnknownArguments()), MakeEntry(183, "mq_timedreceive", UnknownArguments()), MakeEntry(184, "mq_notify", UnknownArguments()), MakeEntry(185, "mq_getsetattr", UnknownArguments()), MakeEntry(186, "msgget", UnknownArguments()), MakeEntry(187, "msgctl", UnknownArguments()), MakeEntry(188, "msgrcv", UnknownArguments()), MakeEntry(189, "msgsnd", UnknownArguments()), MakeEntry(190, "semget", UnknownArguments()), MakeEntry(191, "semctl", UnknownArguments()), MakeEntry(192, "semtimedop", UnknownArguments()), MakeEntry(193, "semop", UnknownArguments()), MakeEntry(194, "shmget", UnknownArguments()), MakeEntry(195, "shmctl", UnknownArguments()), MakeEntry(196, "shmat", UnknownArguments()), MakeEntry(197, "shmdt", UnknownArguments()), MakeEntry(198, "socket", kAddressFamily, kInt, kInt, kGen, kGen, kGen), MakeEntry(199, "socketpair", UnknownArguments()), MakeEntry(200, "bind", UnknownArguments()), MakeEntry(201, "listen", UnknownArguments()), MakeEntry(202, "accept", UnknownArguments()), MakeEntry(203, "connect", kInt, kSockaddr, kInt, kGen, kGen, kGen), MakeEntry(204, "getsockname", UnknownArguments()), MakeEntry(205, "getpeername", UnknownArguments()), MakeEntry(206, "sendto", kInt, kGen, kInt, kHex, kSockaddr, kInt), MakeEntry(207, "recvfrom", UnknownArguments()), MakeEntry(208, "setsockopt", UnknownArguments()), MakeEntry(209, "getsockopt", UnknownArguments()), MakeEntry(210, "shutdown", UnknownArguments()), MakeEntry(211, "sendmsg", kInt, kSockmsghdr, kHex, kGen, kGen, kGen), MakeEntry(212, "recvmsg", UnknownArguments()), MakeEntry(213, "readahead", UnknownArguments()), MakeEntry(214, "brk", kHex, kGen, kGen, kGen, kGen, kGen), MakeEntry(215, "munmap", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(216, "mremap", UnknownArguments()), MakeEntry(217, "add_key", UnknownArguments()), MakeEntry(218, "request_key", UnknownArguments()), MakeEntry(219, "keyctl", UnknownArguments()), MakeEntry(220, "clone", kCloneFlag, kHex, kHex, kHex, kHex, kGen), MakeEntry(221, "execve", kPath, kHex, kHex, kGen, kGen, kGen), MakeEntry(222, "mmap", kHex, kInt, kHex, kHex, kInt, kInt), MakeEntry(223, "fadvise64", UnknownArguments()), MakeEntry(224, "swapon", kPath, kHex, kGen, kGen, kGen, kGen), MakeEntry(225, "swapoff", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(226, "mprotect", kHex, kHex, kHex, kGen, kGen, kGen), MakeEntry(227, "msync", UnknownArguments()), MakeEntry(228, "mlock", UnknownArguments()), MakeEntry(229, "munlock", UnknownArguments()), MakeEntry(230, "mlockall", UnknownArguments()), MakeEntry(231, "munlockall", UnknownArguments()), MakeEntry(232, "mincore", UnknownArguments()), MakeEntry(233, "madvise", UnknownArguments()), MakeEntry(234, "remap_file_pages", UnknownArguments()), MakeEntry(235, "mbind", UnknownArguments()), MakeEntry(236, "get_mempolicy", UnknownArguments()), MakeEntry(237, "set_mempolicy", UnknownArguments()), MakeEntry(238, "migrate_pages", UnknownArguments()), MakeEntry(239, "move_pages", UnknownArguments()), MakeEntry(240, "rt_tgsigqueueinfo", UnknownArguments()), MakeEntry(241, "perf_event_open", UnknownArguments()), MakeEntry(242, "accept4", UnknownArguments()), MakeEntry(243, "recvmmsg", kInt, kHex, kHex, kHex, kGen, kGen), MakeEntry(260, "wait4", kInt, kHex, kHex, kHex, kGen, kGen), MakeEntry(261, "prlimit64", kInt, kInt, kHex, kHex, kGen, kGen), MakeEntry(262, "fanotify_init", kHex, kHex, kInt, kGen, kGen, kGen), MakeEntry(263, "fanotify_mark", kInt, kHex, kInt, kPath, kGen, kGen), MakeEntry(264, "name_to_handle_at", kInt, kGen, kHex, kHex, kHex, kGen), MakeEntry(265, "open_by_handle_at", kInt, kHex, kHex, kGen, kGen, kGen), MakeEntry(266, "clock_adjtime", kInt, kHex, kGen, kGen, kGen, kGen), MakeEntry(267, "syncfs", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(268, "setns", kInt, kHex, kGen, kGen, kGen, kGen), MakeEntry(269, "sendmmsg", kInt, kHex, kInt, kHex, kGen, kGen), MakeEntry(270, "process_vm_readv", kInt, kHex, kInt, kHex, kInt, kInt), MakeEntry(271, "process_vm_writev", kInt, kHex, kInt, kHex, kInt, kInt), MakeEntry(272, "kcmp", kInt, kInt, kInt, kHex, kHex, kGen), MakeEntry(273, "finit_module", kInt, kPath, kHex, kGen, kGen, kGen), MakeEntry(274, "sched_setattr", UnknownArguments()), MakeEntry(275, "sched_getattr", UnknownArguments()), MakeEntry(276, "renameat2", kGen, kPath, kGen, kPath, kGen, kGen), MakeEntry(277, "seccomp", UnknownArguments()), MakeEntry(278, "getrandom", UnknownArguments()), MakeEntry(279, "memfd_create", UnknownArguments()), // clang-format on }; static_assert(IsSorted(kSyscallDataArm64, SyscallTable::Entry::BySyscallNr), "Syscalls should be sorted"); constexpr std::array kSyscallDataArm32 = { // clang-format off MakeEntry(0, "restart_syscall", kGen, kGen, kGen, kGen), MakeEntry(1, "exit", kHex, kHex, kHex, kHex), MakeEntry(2, "fork", kGen, kGen, kGen, kGen), MakeEntry(3, "read", kInt, kHex, kInt), MakeEntry(4, "write", kHex, kHex, kHex, kHex), MakeEntry(5, "open", kPath, kHex, kOct), MakeEntry(6, "close", kHex, kHex, kHex, kHex), MakeEntry(8, "creat", kPath, kHex, kHex, kHex), MakeEntry(9, "link", kPath, kPath), MakeEntry(10, "unlink", kPath), MakeEntry(11, "execve", kPath, kHex, kHex), MakeEntry(12, "chdir", kPath), MakeEntry(14, "mknod", kPath, kOct, kHex), MakeEntry(15, "chmod", kPath, kOct), MakeEntry(16, "lchown", kPath, kInt, kInt), MakeEntry(19, "lseek", kGen, kGen, kGen, kGen), MakeEntry(20, "getpid", kGen, kGen, kGen, kGen), MakeEntry(21, "mount", kHex, kHex, kHex, kHex), MakeEntry(23, "setuid", kGen, kGen, kGen, kGen), MakeEntry(24, "getuid", kGen, kGen, kGen, kGen), MakeEntry(26, "ptrace", kGen, kGen, kGen), MakeEntry(29, "pause", kGen, kGen, kGen, kGen), MakeEntry(33, "access", kPath, kHex), MakeEntry(34, "nice", kHex, kHex, kHex, kHex), MakeEntry(36, "sync", kGen, kGen, kGen, kGen), MakeEntry(37, "kill", kHex, kHex, kHex, kHex), MakeEntry(38, "rename", kPath, kPath), MakeEntry(39, "mkdir", kPath, kHex, kHex, kHex), MakeEntry(40, "rmdir", kHex, kHex, kHex, kHex), MakeEntry(41, "dup", kGen, kGen, kGen, kGen), MakeEntry(42, "pipe", kGen, kGen, kGen, kGen), MakeEntry(43, "times", kGen, kGen, kGen, kGen), MakeEntry(45, "brk", kHex), MakeEntry(46, "setgid", kGen, kGen, kGen, kGen), MakeEntry(47, "getgid", kGen, kGen, kGen, kGen), MakeEntry(49, "geteuid", kGen, kGen, kGen, kGen), MakeEntry(50, "getegid", kGen, kGen, kGen, kGen), MakeEntry(51, "acct", kHex, kHex, kHex, kHex), MakeEntry(52, "umount2", kHex, kHex, kHex, kHex), MakeEntry(54, "ioctl", kGen, kGen, kGen, kGen), MakeEntry(55, "fcntl", kGen, kGen, kGen, kGen), MakeEntry(57, "setpgid", kGen, kGen, kGen, kGen), MakeEntry(60, "umask", kHex), MakeEntry(61, "chroot", kHex, kHex, kHex, kHex), MakeEntry(62, "ustat", kGen, kGen, kGen, kGen), MakeEntry(63, "dup2", kGen, kGen), MakeEntry(64, "getppid", kGen, kGen, kGen, kGen), MakeEntry(65, "getpgrp", kGen, kGen, kGen, kGen), MakeEntry(66, "setsid", kGen, kGen, kGen, kGen), MakeEntry(67, "sigaction", kHex, kHex, kHex, kHex), MakeEntry(70, "setreuid", kGen, kGen, kGen, kGen), MakeEntry(71, "setregid", kGen, kGen, kGen, kGen), MakeEntry(72, "sigsuspend", kHex, kHex, kHex, kHex), MakeEntry(73, "sigpending", kHex, kHex, kHex, kHex), MakeEntry(74, "sethostname", kGen, kGen, kGen, kGen), MakeEntry(75, "setrlimit", kGen, kGen, kGen, kGen), MakeEntry(77, "getrusage", kGen, kGen, kGen, kGen), MakeEntry(78, "gettimeofday", kHex, kHex), MakeEntry(79, "settimeofday", kHex, kHex), MakeEntry(80, "getgroups", kGen, kGen, kGen, kGen), MakeEntry(81, "setgroups", kGen, kGen, kGen, kGen), MakeEntry(83, "symlink", kPath, kPath), MakeEntry(85, "readlink", kPath, kGen, kInt), MakeEntry(86, "uselib", kPath), MakeEntry(87, "swapon", kHex, kHex, kHex, kHex), MakeEntry(88, "reboot", kGen, kGen, kGen, kGen), MakeEntry(91, "munmap", kHex, kHex), MakeEntry(92, "truncate", kPath, kHex, kHex, kHex), MakeEntry(93, "ftruncate", kGen, kGen, kGen, kGen), MakeEntry(94, "fchmod", kGen, kGen, kGen, kGen), MakeEntry(95, "fchown", kGen, kGen, kGen, kGen), MakeEntry(96, "getpriority", kGen, kGen, kGen, kGen), MakeEntry(97, "setpriority", kGen, kGen, kGen, kGen), MakeEntry(99, "statfs", kPath, kGen, kGen, kGen), MakeEntry(100, "fstatfs", kGen, kGen, kGen, kGen), MakeEntry(103, "syslog", kGen, kGen, kGen, kGen), MakeEntry(104, "setitimer", kGen, kGen, kGen, kGen), MakeEntry(105, "getitimer", kGen, kGen, kGen, kGen), MakeEntry(106, "stat", kPath, kGen), MakeEntry(107, "lstat", kPath, kGen), MakeEntry(108, "fstat", kHex, kHex, kHex, kHex), MakeEntry(111, "vhangup", kGen, kGen, kGen, kGen), MakeEntry(114, "wait4", kHex, kHex, kHex, kHex), MakeEntry(115, "swapoff", kHex, kHex, kHex, kHex), MakeEntry(116, "sysinfo", kGen, kGen, kGen, kGen), MakeEntry(118, "fsync", kGen, kGen, kGen, kGen), MakeEntry(119, "sigreturn", kHex, kHex, kHex, kHex), MakeEntry(120, "clone", kCloneFlag, kHex, kHex, kHex), MakeEntry(121, "setdomainname", kGen, kGen, kGen, kGen), MakeEntry(122, "uname", kGen, kGen, kGen, kGen), MakeEntry(124, "adjtimex", kGen, kGen, kGen, kGen), MakeEntry(125, "mprotect", kHex, kHex, kHex), MakeEntry(126, "sigprocmask", kHex, kHex, kHex, kHex), MakeEntry(128, "init_module", kGen, kGen, kGen, kGen), MakeEntry(129, "delete_module", kGen, kGen, kGen, kGen), MakeEntry(131, "quotactl", kHex, kHex, kHex, kHex), MakeEntry(132, "getpgid", kGen, kGen, kGen, kGen), MakeEntry(133, "fchdir", kGen, kGen, kGen, kGen), MakeEntry(134, "bdflush", kHex, kHex, kHex, kHex), MakeEntry(135, "sysfs", kGen, kGen, kGen, kGen), MakeEntry(136, "personality", kGen, kGen, kGen, kGen), MakeEntry(138, "setfsuid", kGen, kGen, kGen, kGen), MakeEntry(139, "setfsgid", kGen, kGen, kGen, kGen), MakeEntry(140, "_llseek", kHex, kHex, kHex, kHex), MakeEntry(141, "getdents", kGen, kGen, kGen, kGen), MakeEntry(142, "_newselect", kHex, kHex, kHex, kHex), MakeEntry(143, "flock", kGen, kGen, kGen, kGen), MakeEntry(144, "msync", kGen, kGen, kGen, kGen), MakeEntry(145, "readv", kGen, kGen, kGen, kGen), MakeEntry(146, "writev", kGen, kGen, kGen, kGen), MakeEntry(147, "getsid", kGen, kGen, kGen, kGen), MakeEntry(148, "fdatasync", kGen, kGen, kGen, kGen), MakeEntry(149, "_sysctl", kGen, kGen, kGen, kGen), MakeEntry(150, "mlock", kGen, kGen, kGen, kGen), MakeEntry(151, "munlock", kGen, kGen, kGen, kGen), MakeEntry(152, "mlockall", kGen, kGen, kGen, kGen), MakeEntry(153, "munlockall", kGen, kGen, kGen, kGen), MakeEntry(154, "sched_setparam", kGen, kGen, kGen, kGen), MakeEntry(155, "sched_getparam", kGen, kGen, kGen, kGen), MakeEntry(156, "sched_setscheduler", kGen, kGen, kGen, kGen), MakeEntry(157, "sched_getscheduler", kGen, kGen, kGen, kGen), MakeEntry(158, "sched_yield", kGen, kGen, kGen, kGen), MakeEntry(159, "sched_get_priority_max", kGen, kGen, kGen, kGen), MakeEntry(160, "sched_get_priority_min", kGen, kGen, kGen, kGen), MakeEntry(161, "sched_rr_get_interval", kGen, kGen, kGen, kGen), MakeEntry(162, "nanosleep", kHex, kHex), MakeEntry(163, "mremap", kGen, kGen, kGen, kGen), MakeEntry(164, "setresuid", kGen, kGen, kGen, kGen), MakeEntry(165, "getresuid", kGen, kGen, kGen, kGen), MakeEntry(168, "poll", kGen, kGen, kGen, kGen), MakeEntry(169, "nfsservctl", kGen, kGen, kGen, kGen), MakeEntry(170, "setresgid", kGen, kGen, kGen, kGen), MakeEntry(171, "getresgid", kGen, kGen, kGen, kGen), MakeEntry(172, "prctl", kHex, kHex, kHex, kHex), MakeEntry(173, "rt_sigreturn", kGen, kGen, kGen, kGen), MakeEntry(174, "rt_sigaction", kHex, kHex, kHex, kHex), MakeEntry(175, "rt_sigprocmask", kGen, kGen, kGen, kGen), MakeEntry(176, "rt_sigpending", kGen, kGen, kGen, kGen), MakeEntry(177, "rt_sigtimedwait", kGen, kGen, kGen, kGen), MakeEntry(178, "rt_sigqueueinfo", kGen, kGen, kGen, kGen), MakeEntry(179, "rt_sigsuspend", kGen, kGen, kGen, kGen), MakeEntry(180, "pread64", kGen, kGen, kGen, kGen), MakeEntry(181, "pwrite64", kGen, kGen, kGen, kGen), MakeEntry(182, "chown", kHex, kHex, kHex, kHex), MakeEntry(183, "getcwd", kGen, kGen, kGen, kGen), MakeEntry(184, "capget", kGen, kGen, kGen, kGen), MakeEntry(185, "capset", kGen, kGen, kGen, kGen), MakeEntry(186, "sigaltstack", kGen, kGen, kGen, kGen), MakeEntry(187, "sendfile", kGen, kGen, kGen, kGen), MakeEntry(190, "vfork", kGen, kGen, kGen, kGen), MakeEntry(191, "ugetrlimit", kHex, kHex, kHex, kHex), MakeEntry(192, "mmap2", kHex, kHex, kHex, kHex), MakeEntry(193, "truncate64", kHex, kHex, kHex, kHex), MakeEntry(194, "ftruncate64", kHex, kHex, kHex, kHex), MakeEntry(195, "stat64", kHex, kHex, kHex, kHex), MakeEntry(196, "lstat64", kHex, kHex, kHex, kHex), MakeEntry(197, "fstat64", kHex, kHex, kHex, kHex), MakeEntry(198, "lchown32", kHex, kHex, kHex, kHex), MakeEntry(199, "getuid32", kHex, kHex, kHex, kHex), MakeEntry(200, "getgid32", kHex, kHex, kHex, kHex), MakeEntry(201, "geteuid32", kHex, kHex, kHex, kHex), MakeEntry(202, "getegid32", kHex, kHex, kHex, kHex), MakeEntry(203, "setreuid32", kHex, kHex, kHex, kHex), MakeEntry(204, "setregid32", kHex, kHex, kHex, kHex), MakeEntry(205, "getgroups32", kHex, kHex, kHex, kHex), MakeEntry(206, "setgroups32", kHex, kHex, kHex, kHex), MakeEntry(207, "fchown32", kHex, kHex, kHex, kHex), MakeEntry(208, "setresuid32", kHex, kHex, kHex, kHex), MakeEntry(209, "getresuid32", kHex, kHex, kHex, kHex), MakeEntry(210, "setresgid32", kHex, kHex, kHex, kHex), MakeEntry(211, "getresgid32", kHex, kHex, kHex, kHex), MakeEntry(212, "chown32", kHex, kHex, kHex, kHex), MakeEntry(213, "setuid32", kHex, kHex, kHex, kHex), MakeEntry(214, "setgid32", kHex, kHex, kHex, kHex), MakeEntry(215, "setfsuid32", kHex, kHex, kHex, kHex), MakeEntry(216, "setfsgid32", kHex, kHex, kHex, kHex), MakeEntry(217, "getdents64", kGen, kGen, kGen, kGen), MakeEntry(218, "pivot_root", kHex, kHex, kHex, kHex), MakeEntry(219, "mincore", kGen, kGen, kGen, kGen), MakeEntry(220, "madvise", kGen, kGen, kGen, kGen), MakeEntry(221, "fcntl64", kHex, kHex, kHex, kHex), MakeEntry(224, "gettid", kGen, kGen, kGen, kGen), MakeEntry(225, "readahead", kGen, kGen, kGen, kGen), MakeEntry(226, "setxattr", kHex, kHex, kHex, kHex), MakeEntry(227, "lsetxattr", kHex, kHex, kHex, kHex), MakeEntry(228, "fsetxattr", kGen, kGen, kGen, kGen), MakeEntry(229, "getxattr", kHex, kHex, kHex, kHex), MakeEntry(230, "lgetxattr", kHex, kHex, kHex, kHex), MakeEntry(231, "fgetxattr", kGen, kGen, kGen, kGen), MakeEntry(232, "listxattr", kHex, kHex, kHex, kHex), MakeEntry(233, "llistxattr", kHex, kHex, kHex, kHex), MakeEntry(234, "flistxattr", kGen, kGen, kGen, kGen), MakeEntry(235, "removexattr", kHex, kHex, kHex, kHex), MakeEntry(236, "lremovexattr", kGen, kGen, kGen, kGen), MakeEntry(237, "fremovexattr", kGen, kGen, kGen, kGen), MakeEntry(238, "tkill", kHex, kHex, kHex, kHex), MakeEntry(239, "sendfile64", kHex, kHex, kHex, kHex), MakeEntry(240, "futex", kGen, kGen, kGen, kGen), MakeEntry(241, "sched_setaffinity", kGen, kGen, kGen, kGen), MakeEntry(242, "sched_getaffinity", kGen, kGen, kGen, kGen), MakeEntry(243, "io_setup", kGen, kGen, kGen, kGen), MakeEntry(244, "io_destroy", kGen, kGen, kGen, kGen), MakeEntry(245, "io_getevents", kGen, kGen, kGen, kGen), MakeEntry(246, "io_submit", kGen, kGen, kGen, kGen), MakeEntry(247, "io_cancel", kGen, kGen, kGen, kGen), MakeEntry(248, "exit_group", kHex, kHex, kHex, kHex), MakeEntry(249, "lookup_dcookie", kGen, kGen, kGen, kGen), MakeEntry(250, "epoll_create", kGen, kGen, kGen, kGen), MakeEntry(251, "epoll_ctl", kGen, kGen, kGen, kGen), MakeEntry(252, "epoll_wait", kGen, kGen, kGen, kGen), MakeEntry(253, "remap_file_pages", kGen, kGen, kGen, kGen), MakeEntry(256, "set_tid_address", kHex), MakeEntry(257, "timer_create", kGen, kGen, kGen, kGen), MakeEntry(258, "timer_settime", kGen, kGen, kGen, kGen), MakeEntry(259, "timer_gettime", kGen, kGen, kGen, kGen), MakeEntry(260, "timer_getoverrun", kGen, kGen, kGen, kGen), MakeEntry(261, "timer_delete", kGen, kGen, kGen, kGen), MakeEntry(262, "clock_settime", kGen, kGen, kGen, kGen), MakeEntry(263, "clock_gettime", kGen, kGen, kGen, kGen), MakeEntry(264, "clock_getres", kGen, kGen, kGen, kGen), MakeEntry(265, "clock_nanosleep", kGen, kGen, kGen, kGen), MakeEntry(266, "statfs64", kHex, kHex, kHex, kHex), MakeEntry(267, "fstatfs64", kHex, kHex, kHex, kHex), MakeEntry(268, "tgkill", kHex, kHex, kHex, kHex), MakeEntry(269, "utimes", kGen, kGen, kGen, kGen), MakeEntry(271, "pciconfig_iobase", kHex, kHex, kHex, kHex), MakeEntry(272, "pciconfig_read", kHex, kHex, kHex, kHex), MakeEntry(273, "pciconfig_write", kHex, kHex, kHex, kHex), MakeEntry(274, "mq_open", kGen, kGen, kGen, kGen), MakeEntry(275, "mq_unlink", kGen, kGen, kGen, kGen), MakeEntry(276, "mq_timedsend", kGen, kGen, kGen, kGen), MakeEntry(277, "mq_timedreceive", kGen, kGen, kGen, kGen), MakeEntry(278, "mq_notify", kGen, kGen, kGen, kGen), MakeEntry(279, "mq_getsetattr", kGen, kGen, kGen, kGen), MakeEntry(280, "waitid", kGen, kGen, kGen, kGen), MakeEntry(281, "socket", kAddressFamily, kInt, kInt), MakeEntry(282, "bind", kGen, kGen, kGen, kGen), MakeEntry(283, "connect", kInt, kSockaddr, kInt), MakeEntry(284, "listen", kGen, kGen, kGen, kGen), MakeEntry(285, "accept", kGen, kGen, kGen, kGen), MakeEntry(286, "getsockname", kGen, kGen, kGen, kGen), MakeEntry(287, "getpeername", kGen, kGen, kGen, kGen), MakeEntry(288, "socketpair", kGen, kGen, kGen, kGen), MakeEntry(289, "send", kHex, kHex, kHex, kHex), MakeEntry(290, "sendto", kInt, kGen, kInt, kHex), MakeEntry(291, "recv", kHex, kHex, kHex, kHex), MakeEntry(292, "recvfrom", kGen, kGen, kGen, kGen), MakeEntry(293, "shutdown", kGen, kGen, kGen, kGen), MakeEntry(294, "setsockopt", kGen, kGen, kGen, kGen), MakeEntry(295, "getsockopt", kGen, kGen, kGen, kGen), MakeEntry(296, "sendmsg", kInt, kSockmsghdr, kHex), MakeEntry(297, "recvmsg", kGen, kGen, kGen, kGen), MakeEntry(298, "semop", UnknownArguments()), MakeEntry(299, "semget", UnknownArguments()), MakeEntry(300, "semctl", UnknownArguments()), MakeEntry(301, "msgsnd", UnknownArguments()), MakeEntry(302, "msgrcv", UnknownArguments()), MakeEntry(303, "msgget", UnknownArguments()), MakeEntry(304, "msgctl", UnknownArguments()), MakeEntry(305, "shmat", UnknownArguments()), MakeEntry(306, "shmdt", UnknownArguments()), MakeEntry(307, "shmget", UnknownArguments()), MakeEntry(308, "shmctl", UnknownArguments()), MakeEntry(309, "add_key", kGen, kGen, kGen, kGen), MakeEntry(310, "request_key", kGen, kGen, kGen, kGen), MakeEntry(311, "keyctl", kGen, kGen, kGen, kGen), MakeEntry(312, "semtimedop", UnknownArguments()), MakeEntry(313, "vserver", kHex, kHex, kHex, kHex), MakeEntry(314, "ioprio_set", kGen, kGen, kGen, kGen), MakeEntry(315, "ioprio_get", kGen, kGen, kGen, kGen), MakeEntry(316, "inotify_init", kGen, kGen, kGen, kGen), MakeEntry(317, "inotify_add_watch", kGen, kGen, kGen, kGen), MakeEntry(318, "inotify_rm_watch", kGen, kGen, kGen, kGen), MakeEntry(319, "mbind", kGen, kGen, kGen, kGen), MakeEntry(320, "get_mempolicy", kGen, kGen, kGen, kGen), MakeEntry(321, "set_mempolicy", kGen, kGen, kGen, kGen), MakeEntry(322, "openat", kGen, kPath, kOct, kHex), MakeEntry(323, "mkdirat", kGen, kPath), MakeEntry(324, "mknodat", kGen, kPath), MakeEntry(325, "fchownat", kGen, kPath), MakeEntry(326, "futimesat", kGen, kPath), MakeEntry(327, "fstatat64", kHex, kHex, kHex, kHex), MakeEntry(328, "unlinkat", kGen, kPath), MakeEntry(329, "renameat", kGen, kPath, kGen, kPath), MakeEntry(330, "linkat", kGen, kPath, kGen, kPath), MakeEntry(331, "symlinkat", kPath, kGen, kPath), MakeEntry(332, "readlinkat", kGen, kPath), MakeEntry(333, "fchmodat", kGen, kPath), MakeEntry(334, "faccessat", kGen, kPath), MakeEntry(335, "pselect6", kGen, kGen, kGen, kGen), MakeEntry(336, "ppoll", kGen, kGen, kGen, kGen), MakeEntry(337, "unshare", kGen, kGen, kGen, kGen), MakeEntry(338, "set_robust_list", kGen, kGen), MakeEntry(339, "get_robust_list", kGen, kGen, kGen, kGen), MakeEntry(340, "splice", kGen, kGen, kGen, kGen), MakeEntry(342, "tee", kGen, kGen, kGen, kGen), MakeEntry(343, "vmsplice", kGen, kGen, kGen, kGen), MakeEntry(344, "move_pages", kGen, kGen, kGen, kGen), MakeEntry(345, "getcpu", kHex, kHex, kHex), MakeEntry(346, "epoll_pwait", kGen, kGen, kGen, kGen), MakeEntry(347, "kexec_load", kGen, kGen, kGen, kGen), MakeEntry(348, "utimensat", kGen, kGen, kGen, kGen), MakeEntry(349, "signalfd", kGen, kGen, kGen, kGen), MakeEntry(350, "timerfd_create", kGen, kGen, kGen, kGen), MakeEntry(351, "eventfd", kGen, kGen, kGen, kGen), MakeEntry(352, "fallocate", kGen, kGen, kGen, kGen), MakeEntry(353, "timerfd_settime", kGen, kGen, kGen, kGen), MakeEntry(354, "timerfd_gettime", kGen, kGen, kGen, kGen), MakeEntry(355, "signalfd4", kGen, kGen, kGen, kGen), MakeEntry(356, "eventfd2", kGen, kGen, kGen, kGen), MakeEntry(357, "epoll_create1", kGen, kGen, kGen, kGen), MakeEntry(358, "dup3", kGen, kGen, kGen), MakeEntry(359, "pipe2", kGen, kGen, kGen, kGen), MakeEntry(360, "inotify_init1", kGen, kGen, kGen, kGen), MakeEntry(361, "preadv", kGen, kGen, kGen, kGen), MakeEntry(362, "pwritev", kGen, kGen, kGen, kGen), MakeEntry(363, "rt_tgsigqueueinfo", kGen, kGen, kGen, kGen), MakeEntry(364, "perf_event_open", kGen, kGen, kGen, kGen), MakeEntry(365, "recvmmsg", kHex, kHex, kHex, kHex), MakeEntry(366, "accept4", kGen, kGen, kGen, kGen), MakeEntry(367, "fanotify_init", kHex, kHex, kHex, kHex), MakeEntry(368, "fanotify_mark", kHex, kHex, kHex, kHex), MakeEntry(369, "prlimit64", kHex, kHex, kHex, kHex), MakeEntry(370, "name_to_handle_at", kHex, kHex, kHex, kHex), MakeEntry(371, "open_by_handle_at", kHex, kHex, kHex, kHex), MakeEntry(372, "clock_adjtime", kHex, kHex, kHex, kHex), MakeEntry(373, "syncfs", kHex, kHex, kHex, kHex), MakeEntry(374, "sendmmsg", kHex, kHex, kHex, kHex), MakeEntry(375, "setns", kHex, kHex, kHex, kHex), MakeEntry(376, "process_vm_readv", kHex, kHex, kHex, kHex), MakeEntry(377, "process_vm_writev", kHex, kHex, kHex, kHex), MakeEntry(378, "kcmp", kHex, kHex, kHex, kHex), MakeEntry(379, "finit_module", kHex, kHex, kHex, kHex), MakeEntry(380, "sched_setattr", kGen, kGen, kGen, kGen), MakeEntry(381, "sched_getattr", kGen, kGen, kGen, kGen), MakeEntry(382, "renameat2", kGen, kPath, kGen, kPath), MakeEntry(383, "seccomp", kGen, kGen, kGen, kGen), MakeEntry(384, "getrandom", kGen, kGen, kGen, kGen), MakeEntry(385, "memfd_create", kGen, kGen, kGen, kGen), MakeEntry(386, "bpf", kHex, kHex, kHex, kHex), MakeEntry(387, "execveat", kHex, kHex, kHex, kHex), MakeEntry(388, "userfaultfd", kHex), MakeEntry(389, "membarrier", kHex, kHex), MakeEntry(390, "mlock2", kHex, kHex, kHex, kHex), MakeEntry(391, "copy_file_range", kHex, kHex, kHex, kHex), MakeEntry(392, "preadv2", kHex, kHex, kHex, kHex), MakeEntry(393, "pwritev2", kHex, kHex, kHex, kHex), MakeEntry(400, "migrate_pages", kGen, kGen, kGen, kGen), MakeEntry(401, "kexec_file_load", kGen, kGen, kGen, kGen), MakeEntry(0xf0001, "ARM_breakpoint", kHex, kHex, kHex, kHex), MakeEntry(0xf0002, "ARM_cacheflush", kHex, kHex, kHex, kHex), MakeEntry(0xf0003, "ARM_usr26", kHex, kHex, kHex, kHex), MakeEntry(0xf0004, "ARM_usr32", kHex, kHex, kHex, kHex), MakeEntry(0xf0005, "ARM_set_tls", kHex, kHex, kHex, kHex), // clang-format on }; static_assert(IsSorted(kSyscallDataArm32, SyscallTable::Entry::BySyscallNr), "Syscalls should be sorted"); } // namespace SyscallTable SyscallTable::get(sapi::cpu::Architecture arch) { switch (arch) { case sapi::cpu::kX8664: return SyscallTable(kSyscallDataX8664); case sapi::cpu::kX86: return SyscallTable(kSyscallDataX8632); case sapi::cpu::kPPC64LE: return SyscallTable(kSyscallDataPPC64LE); case sapi::cpu::kArm64: return SyscallTable(kSyscallDataArm64); case sapi::cpu::kArm: return SyscallTable(kSyscallDataArm32); default: return SyscallTable(); } } } // namespace sandbox2
56.291994
80
0.652844
4920e34b4bc7e375aef545fb49136ef9e39dd7f1
34,971
cpp
C++
src/pvrt/PVRTMatrixF.cpp
aunali1/sauerbraten-ios
247de70e6889d424b041ce08627aa446caaef46c
[ "Cube", "Zlib" ]
1
2019-10-25T05:46:42.000Z
2019-10-25T05:46:42.000Z
src/pvrt/PVRTMatrixF.cpp
aunali1/sauerbraten-ios
247de70e6889d424b041ce08627aa446caaef46c
[ "Cube", "Zlib" ]
1
2015-05-24T01:30:20.000Z
2015-05-24T01:30:20.000Z
src/pvrt/PVRTMatrixF.cpp
aunali1/sauerbraten-ios
247de70e6889d424b041ce08627aa446caaef46c
[ "Cube", "Zlib" ]
null
null
null
/****************************************************************************** @File PVRTMatrixF.cpp @Title @Copyright Copyright (C) 1999 - 2008 by Imagination Technologies Limited. @Platform ANSI compatible @Description Set of mathematical functions involving matrices, vectors and quaternions. The general matrix format used is directly compatible with, for example, both DirectX and OpenGL. For the reasons why, read this: http://research.microsoft.com/~hollasch/cgindex/math/matrix/column-vec.html ******************************************************************************/ #include "PVRTGlobal.h" //#include "PVRTContext.h" #include <math.h> #include <string.h> #include "PVRTFixedPoint.h" // Only needed for trig function float lookups #include "PVRTMatrix.h" /**************************************************************************** ** Constants ****************************************************************************/ static const PVRTMATRIXf c_mIdentity = { { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } }; /**************************************************************************** ** Functions ****************************************************************************/ /*!*************************************************************************** @Function PVRTMatrixIdentityF @Output mOut Set to identity @Description Reset matrix to identity matrix. *****************************************************************************/ void PVRTMatrixIdentityF(PVRTMATRIXf &mOut) { mOut.f[ 0]=1.0f; mOut.f[ 4]=0.0f; mOut.f[ 8]=0.0f; mOut.f[12]=0.0f; mOut.f[ 1]=0.0f; mOut.f[ 5]=1.0f; mOut.f[ 9]=0.0f; mOut.f[13]=0.0f; mOut.f[ 2]=0.0f; mOut.f[ 6]=0.0f; mOut.f[10]=1.0f; mOut.f[14]=0.0f; mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f; } /*!*************************************************************************** @Function PVRTMatrixMultiplyF @Output mOut Result of mA x mB @Input mA First operand @Input mB Second operand @Description Multiply mA by mB and assign the result to mOut (mOut = p1 * p2). A copy of the result matrix is done in the function because mOut can be a parameter mA or mB. *****************************************************************************/ void PVRTMatrixMultiplyF( PVRTMATRIXf &mOut, const PVRTMATRIXf &mA, const PVRTMATRIXf &mB) { PVRTMATRIXf mRet; /* Perform calculation on a dummy matrix (mRet) */ mRet.f[ 0] = mA.f[ 0]*mB.f[ 0] + mA.f[ 1]*mB.f[ 4] + mA.f[ 2]*mB.f[ 8] + mA.f[ 3]*mB.f[12]; mRet.f[ 1] = mA.f[ 0]*mB.f[ 1] + mA.f[ 1]*mB.f[ 5] + mA.f[ 2]*mB.f[ 9] + mA.f[ 3]*mB.f[13]; mRet.f[ 2] = mA.f[ 0]*mB.f[ 2] + mA.f[ 1]*mB.f[ 6] + mA.f[ 2]*mB.f[10] + mA.f[ 3]*mB.f[14]; mRet.f[ 3] = mA.f[ 0]*mB.f[ 3] + mA.f[ 1]*mB.f[ 7] + mA.f[ 2]*mB.f[11] + mA.f[ 3]*mB.f[15]; mRet.f[ 4] = mA.f[ 4]*mB.f[ 0] + mA.f[ 5]*mB.f[ 4] + mA.f[ 6]*mB.f[ 8] + mA.f[ 7]*mB.f[12]; mRet.f[ 5] = mA.f[ 4]*mB.f[ 1] + mA.f[ 5]*mB.f[ 5] + mA.f[ 6]*mB.f[ 9] + mA.f[ 7]*mB.f[13]; mRet.f[ 6] = mA.f[ 4]*mB.f[ 2] + mA.f[ 5]*mB.f[ 6] + mA.f[ 6]*mB.f[10] + mA.f[ 7]*mB.f[14]; mRet.f[ 7] = mA.f[ 4]*mB.f[ 3] + mA.f[ 5]*mB.f[ 7] + mA.f[ 6]*mB.f[11] + mA.f[ 7]*mB.f[15]; mRet.f[ 8] = mA.f[ 8]*mB.f[ 0] + mA.f[ 9]*mB.f[ 4] + mA.f[10]*mB.f[ 8] + mA.f[11]*mB.f[12]; mRet.f[ 9] = mA.f[ 8]*mB.f[ 1] + mA.f[ 9]*mB.f[ 5] + mA.f[10]*mB.f[ 9] + mA.f[11]*mB.f[13]; mRet.f[10] = mA.f[ 8]*mB.f[ 2] + mA.f[ 9]*mB.f[ 6] + mA.f[10]*mB.f[10] + mA.f[11]*mB.f[14]; mRet.f[11] = mA.f[ 8]*mB.f[ 3] + mA.f[ 9]*mB.f[ 7] + mA.f[10]*mB.f[11] + mA.f[11]*mB.f[15]; mRet.f[12] = mA.f[12]*mB.f[ 0] + mA.f[13]*mB.f[ 4] + mA.f[14]*mB.f[ 8] + mA.f[15]*mB.f[12]; mRet.f[13] = mA.f[12]*mB.f[ 1] + mA.f[13]*mB.f[ 5] + mA.f[14]*mB.f[ 9] + mA.f[15]*mB.f[13]; mRet.f[14] = mA.f[12]*mB.f[ 2] + mA.f[13]*mB.f[ 6] + mA.f[14]*mB.f[10] + mA.f[15]*mB.f[14]; mRet.f[15] = mA.f[12]*mB.f[ 3] + mA.f[13]*mB.f[ 7] + mA.f[14]*mB.f[11] + mA.f[15]*mB.f[15]; /* Copy result in pResultMatrix */ mOut = mRet; } /*!*************************************************************************** @Function Name PVRTMatrixTranslationF @Output mOut Translation matrix @Input fX X component of the translation @Input fY Y component of the translation @Input fZ Z component of the translation @Description Build a transaltion matrix mOut using fX, fY and fZ. *****************************************************************************/ void PVRTMatrixTranslationF( PVRTMATRIXf &mOut, const float fX, const float fY, const float fZ) { mOut.f[ 0]=1.0f; mOut.f[ 4]=0.0f; mOut.f[ 8]=0.0f; mOut.f[12]=fX; mOut.f[ 1]=0.0f; mOut.f[ 5]=1.0f; mOut.f[ 9]=0.0f; mOut.f[13]=fY; mOut.f[ 2]=0.0f; mOut.f[ 6]=0.0f; mOut.f[10]=1.0f; mOut.f[14]=fZ; mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f; } /*!*************************************************************************** @Function Name PVRTMatrixScalingF @Output mOut Scale matrix @Input fX X component of the scaling @Input fY Y component of the scaling @Input fZ Z component of the scaling @Description Build a scale matrix mOut using fX, fY and fZ. *****************************************************************************/ void PVRTMatrixScalingF( PVRTMATRIXf &mOut, const float fX, const float fY, const float fZ) { mOut.f[ 0]=fX; mOut.f[ 4]=0.0f; mOut.f[ 8]=0.0f; mOut.f[12]=0.0f; mOut.f[ 1]=0.0f; mOut.f[ 5]=fY; mOut.f[ 9]=0.0f; mOut.f[13]=0.0f; mOut.f[ 2]=0.0f; mOut.f[ 6]=0.0f; mOut.f[10]=fZ; mOut.f[14]=0.0f; mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f; } /*!*************************************************************************** @Function Name PVRTMatrixRotationXF @Output mOut Rotation matrix @Input fAngle Angle of the rotation @Description Create an X rotation matrix mOut. *****************************************************************************/ void PVRTMatrixRotationXF( PVRTMATRIXf &mOut, const float fAngle) { float fCosine, fSine; /* Precompute cos and sin */ #if defined(BUILD_DX9) || defined(BUILD_D3DM) fCosine = (float)PVRTFCOS(-fAngle); fSine = (float)PVRTFSIN(-fAngle); #else fCosine = (float)PVRTFCOS(fAngle); fSine = (float)PVRTFSIN(fAngle); #endif /* Create the trigonometric matrix corresponding to X Rotation */ mOut.f[ 0]=1.0f; mOut.f[ 4]=0.0f; mOut.f[ 8]=0.0f; mOut.f[12]=0.0f; mOut.f[ 1]=0.0f; mOut.f[ 5]=fCosine; mOut.f[ 9]=fSine; mOut.f[13]=0.0f; mOut.f[ 2]=0.0f; mOut.f[ 6]=-fSine; mOut.f[10]=fCosine; mOut.f[14]=0.0f; mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f; } /*!*************************************************************************** @Function Name PVRTMatrixRotationYF @Output mOut Rotation matrix @Input fAngle Angle of the rotation @Description Create an Y rotation matrix mOut. *****************************************************************************/ void PVRTMatrixRotationYF( PVRTMATRIXf &mOut, const float fAngle) { float fCosine, fSine; /* Precompute cos and sin */ #if defined(BUILD_DX9) || defined(BUILD_D3DM) fCosine = (float)PVRTFCOS(-fAngle); fSine = (float)PVRTFSIN(-fAngle); #else fCosine = (float)PVRTFCOS(fAngle); fSine = (float)PVRTFSIN(fAngle); #endif /* Create the trigonometric matrix corresponding to Y Rotation */ mOut.f[ 0]=fCosine; mOut.f[ 4]=0.0f; mOut.f[ 8]=-fSine; mOut.f[12]=0.0f; mOut.f[ 1]=0.0f; mOut.f[ 5]=1.0f; mOut.f[ 9]=0.0f; mOut.f[13]=0.0f; mOut.f[ 2]=fSine; mOut.f[ 6]=0.0f; mOut.f[10]=fCosine; mOut.f[14]=0.0f; mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f; } /*!*************************************************************************** @Function Name PVRTMatrixRotationZF @Output mOut Rotation matrix @Input fAngle Angle of the rotation @Description Create an Z rotation matrix mOut. *****************************************************************************/ void PVRTMatrixRotationZF( PVRTMATRIXf &mOut, const float fAngle) { float fCosine, fSine; /* Precompute cos and sin */ #if defined(BUILD_DX9) || defined(BUILD_D3DM) fCosine = (float)PVRTFCOS(-fAngle); fSine = (float)PVRTFSIN(-fAngle); #else fCosine = (float)PVRTFCOS(fAngle); fSine = (float)PVRTFSIN(fAngle); #endif /* Create the trigonometric matrix corresponding to Z Rotation */ mOut.f[ 0]=fCosine; mOut.f[ 4]=fSine; mOut.f[ 8]=0.0f; mOut.f[12]=0.0f; mOut.f[ 1]=-fSine; mOut.f[ 5]=fCosine; mOut.f[ 9]=0.0f; mOut.f[13]=0.0f; mOut.f[ 2]=0.0f; mOut.f[ 6]=0.0f; mOut.f[10]=1.0f; mOut.f[14]=0.0f; mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f; } /*!*************************************************************************** @Function Name PVRTMatrixTransposeF @Output mOut Transposed matrix @Input mIn Original matrix @Description Compute the transpose matrix of mIn. *****************************************************************************/ void PVRTMatrixTransposeF( PVRTMATRIXf &mOut, const PVRTMATRIXf &mIn) { PVRTMATRIXf mTmp; mTmp.f[ 0]=mIn.f[ 0]; mTmp.f[ 4]=mIn.f[ 1]; mTmp.f[ 8]=mIn.f[ 2]; mTmp.f[12]=mIn.f[ 3]; mTmp.f[ 1]=mIn.f[ 4]; mTmp.f[ 5]=mIn.f[ 5]; mTmp.f[ 9]=mIn.f[ 6]; mTmp.f[13]=mIn.f[ 7]; mTmp.f[ 2]=mIn.f[ 8]; mTmp.f[ 6]=mIn.f[ 9]; mTmp.f[10]=mIn.f[10]; mTmp.f[14]=mIn.f[11]; mTmp.f[ 3]=mIn.f[12]; mTmp.f[ 7]=mIn.f[13]; mTmp.f[11]=mIn.f[14]; mTmp.f[15]=mIn.f[15]; mOut = mTmp; } /*!*************************************************************************** @Function PVRTMatrixInverseF @Output mOut Inversed matrix @Input mIn Original matrix @Description Compute the inverse matrix of mIn. The matrix must be of the form : A 0 C 1 Where A is a 3x3 matrix and C is a 1x3 matrix. *****************************************************************************/ void PVRTMatrixInverseF( PVRTMATRIXf &mOut, const PVRTMATRIXf &mIn) { PVRTMATRIXf mDummyMatrix; double det_1; double pos, neg, temp; /* Calculate the determinant of submatrix A and determine if the the matrix is singular as limited by the double precision floating-point data representation. */ pos = neg = 0.0; temp = mIn.f[ 0] * mIn.f[ 5] * mIn.f[10]; if (temp >= 0.0) pos += temp; else neg += temp; temp = mIn.f[ 4] * mIn.f[ 9] * mIn.f[ 2]; if (temp >= 0.0) pos += temp; else neg += temp; temp = mIn.f[ 8] * mIn.f[ 1] * mIn.f[ 6]; if (temp >= 0.0) pos += temp; else neg += temp; temp = -mIn.f[ 8] * mIn.f[ 5] * mIn.f[ 2]; if (temp >= 0.0) pos += temp; else neg += temp; temp = -mIn.f[ 4] * mIn.f[ 1] * mIn.f[10]; if (temp >= 0.0) pos += temp; else neg += temp; temp = -mIn.f[ 0] * mIn.f[ 9] * mIn.f[ 6]; if (temp >= 0.0) pos += temp; else neg += temp; det_1 = pos + neg; /* Is the submatrix A singular? */ if ((det_1 == 0.0) || (PVRTABS(det_1 / (pos - neg)) < 1.0e-15)) { /* Matrix M has no inverse */ #ifndef BADA _RPT0(_CRT_WARN, "Matrix has no inverse : singular matrix\n"); #endif return; } else { /* Calculate inverse(A) = adj(A) / det(A) */ det_1 = 1.0 / det_1; mDummyMatrix.f[ 0] = ( mIn.f[ 5] * mIn.f[10] - mIn.f[ 9] * mIn.f[ 6] ) * (float)det_1; mDummyMatrix.f[ 1] = - ( mIn.f[ 1] * mIn.f[10] - mIn.f[ 9] * mIn.f[ 2] ) * (float)det_1; mDummyMatrix.f[ 2] = ( mIn.f[ 1] * mIn.f[ 6] - mIn.f[ 5] * mIn.f[ 2] ) * (float)det_1; mDummyMatrix.f[ 4] = - ( mIn.f[ 4] * mIn.f[10] - mIn.f[ 8] * mIn.f[ 6] ) * (float)det_1; mDummyMatrix.f[ 5] = ( mIn.f[ 0] * mIn.f[10] - mIn.f[ 8] * mIn.f[ 2] ) * (float)det_1; mDummyMatrix.f[ 6] = - ( mIn.f[ 0] * mIn.f[ 6] - mIn.f[ 4] * mIn.f[ 2] ) * (float)det_1; mDummyMatrix.f[ 8] = ( mIn.f[ 4] * mIn.f[ 9] - mIn.f[ 8] * mIn.f[ 5] ) * (float)det_1; mDummyMatrix.f[ 9] = - ( mIn.f[ 0] * mIn.f[ 9] - mIn.f[ 8] * mIn.f[ 1] ) * (float)det_1; mDummyMatrix.f[10] = ( mIn.f[ 0] * mIn.f[ 5] - mIn.f[ 4] * mIn.f[ 1] ) * (float)det_1; /* Calculate -C * inverse(A) */ mDummyMatrix.f[12] = - ( mIn.f[12] * mDummyMatrix.f[ 0] + mIn.f[13] * mDummyMatrix.f[ 4] + mIn.f[14] * mDummyMatrix.f[ 8] ); mDummyMatrix.f[13] = - ( mIn.f[12] * mDummyMatrix.f[ 1] + mIn.f[13] * mDummyMatrix.f[ 5] + mIn.f[14] * mDummyMatrix.f[ 9] ); mDummyMatrix.f[14] = - ( mIn.f[12] * mDummyMatrix.f[ 2] + mIn.f[13] * mDummyMatrix.f[ 6] + mIn.f[14] * mDummyMatrix.f[10] ); /* Fill in last row */ mDummyMatrix.f[ 3] = 0.0f; mDummyMatrix.f[ 7] = 0.0f; mDummyMatrix.f[11] = 0.0f; mDummyMatrix.f[15] = 1.0f; } /* Copy contents of dummy matrix in pfMatrix */ mOut = mDummyMatrix; } /*!*************************************************************************** @Function PVRTMatrixInverseExF @Output mOut Inversed matrix @Input mIn Original matrix @Description Compute the inverse matrix of mIn. Uses a linear equation solver and the knowledge that M.M^-1=I. Use this fn to calculate the inverse of matrices that PVRTMatrixInverse() cannot. *****************************************************************************/ void PVRTMatrixInverseExF( PVRTMATRIXf &mOut, const PVRTMATRIXf &mIn) { PVRTMATRIXf mTmp; float *ppfRows[4]; float pfRes[4]; float pfIn[20]; int i, j; for(i = 0; i < 4; ++i) ppfRows[i] = &pfIn[i * 5]; /* Solve 4 sets of 4 linear equations */ for(i = 0; i < 4; ++i) { for(j = 0; j < 4; ++j) { ppfRows[j][0] = c_mIdentity.f[i + 4 * j]; memcpy(&ppfRows[j][1], &mIn.f[j * 4], 4 * sizeof(float)); } PVRTMatrixLinearEqSolveF(pfRes, (float**)ppfRows, 4); for(j = 0; j < 4; ++j) { mTmp.f[i + 4 * j] = pfRes[j]; } } mOut = mTmp; } /*!*************************************************************************** @Function PVRTMatrixLookAtLHF @Output mOut Look-at view matrix @Input vEye Position of the camera @Input vAt Point the camera is looking at @Input vUp Up direction for the camera @Description Create a look-at view matrix. *****************************************************************************/ void PVRTMatrixLookAtLHF( PVRTMATRIXf &mOut, const PVRTVECTOR3f &vEye, const PVRTVECTOR3f &vAt, const PVRTVECTOR3f &vUp) { PVRTVECTOR3f f, vUpActual, s, u; PVRTMATRIXf t; f.x = vEye.x - vAt.x; f.y = vEye.y - vAt.y; f.z = vEye.z - vAt.z; PVRTMatrixVec3NormalizeF(f, f); PVRTMatrixVec3NormalizeF(vUpActual, vUp); PVRTMatrixVec3CrossProductF(s, f, vUpActual); PVRTMatrixVec3CrossProductF(u, s, f); mOut.f[ 0] = s.x; mOut.f[ 1] = u.x; mOut.f[ 2] = -f.x; mOut.f[ 3] = 0; mOut.f[ 4] = s.y; mOut.f[ 5] = u.y; mOut.f[ 6] = -f.y; mOut.f[ 7] = 0; mOut.f[ 8] = s.z; mOut.f[ 9] = u.z; mOut.f[10] = -f.z; mOut.f[11] = 0; mOut.f[12] = 0; mOut.f[13] = 0; mOut.f[14] = 0; mOut.f[15] = 1; PVRTMatrixTranslationF(t, -vEye.x, -vEye.y, -vEye.z); PVRTMatrixMultiplyF(mOut, t, mOut); } /*!*************************************************************************** @Function PVRTMatrixLookAtRHF @Output mOut Look-at view matrix @Input vEye Position of the camera @Input vAt Point the camera is looking at @Input vUp Up direction for the camera @Description Create a look-at view matrix. *****************************************************************************/ void PVRTMatrixLookAtRHF( PVRTMATRIXf &mOut, const PVRTVECTOR3f &vEye, const PVRTVECTOR3f &vAt, const PVRTVECTOR3f &vUp) { PVRTVECTOR3f f, vUpActual, s, u; PVRTMATRIXf t; f.x = vAt.x - vEye.x; f.y = vAt.y - vEye.y; f.z = vAt.z - vEye.z; PVRTMatrixVec3NormalizeF(f, f); PVRTMatrixVec3NormalizeF(vUpActual, vUp); PVRTMatrixVec3CrossProductF(s, f, vUpActual); PVRTMatrixVec3CrossProductF(u, s, f); mOut.f[ 0] = s.x; mOut.f[ 1] = u.x; mOut.f[ 2] = -f.x; mOut.f[ 3] = 0; mOut.f[ 4] = s.y; mOut.f[ 5] = u.y; mOut.f[ 6] = -f.y; mOut.f[ 7] = 0; mOut.f[ 8] = s.z; mOut.f[ 9] = u.z; mOut.f[10] = -f.z; mOut.f[11] = 0; mOut.f[12] = 0; mOut.f[13] = 0; mOut.f[14] = 0; mOut.f[15] = 1; PVRTMatrixTranslationF(t, -vEye.x, -vEye.y, -vEye.z); PVRTMatrixMultiplyF(mOut, t, mOut); } /*!*************************************************************************** @Function PVRTMatrixPerspectiveFovLHF @Output mOut Perspective matrix @Input fFOVy Field of view @Input fAspect Aspect ratio @Input fNear Near clipping distance @Input fFar Far clipping distance @Input bRotate Should we rotate it ? (for upright screens) @Description Create a perspective matrix. *****************************************************************************/ void PVRTMatrixPerspectiveFovLHF( PVRTMATRIXf &mOut, const float fFOVy, const float fAspect, const float fNear, const float fFar, const bool bRotate) { float f, n, fRealAspect; if (bRotate) fRealAspect = 1.0f / fAspect; else fRealAspect = fAspect; // cotangent(a) == 1.0f / tan(a); f = 1.0f / (float)PVRTFTAN(fFOVy * 0.5f); n = 1.0f / (fFar - fNear); mOut.f[ 0] = f / fRealAspect; mOut.f[ 1] = 0; mOut.f[ 2] = 0; mOut.f[ 3] = 0; mOut.f[ 4] = 0; mOut.f[ 5] = f; mOut.f[ 6] = 0; mOut.f[ 7] = 0; mOut.f[ 8] = 0; mOut.f[ 9] = 0; mOut.f[10] = fFar * n; mOut.f[11] = 1; mOut.f[12] = 0; mOut.f[13] = 0; mOut.f[14] = -fFar * fNear * n; mOut.f[15] = 0; if (bRotate) { PVRTMATRIXf mRotation, mTemp = mOut; PVRTMatrixRotationZF(mRotation, 90.0f*PVRT_PIf/180.0f); PVRTMatrixMultiplyF(mOut, mTemp, mRotation); } } /*!*************************************************************************** @Function PVRTMatrixPerspectiveFovRHF @Output mOut Perspective matrix @Input fFOVy Field of view @Input fAspect Aspect ratio @Input fNear Near clipping distance @Input fFar Far clipping distance @Input bRotate Should we rotate it ? (for upright screens) @Description Create a perspective matrix. *****************************************************************************/ void PVRTMatrixPerspectiveFovRHF( PVRTMATRIXf &mOut, const float fFOVy, const float fAspect, const float fNear, const float fFar, const bool bRotate) { float f, n, fRealAspect; if (bRotate) fRealAspect = 1.0f / fAspect; else fRealAspect = fAspect; // cotangent(a) == 1.0f / tan(a); f = 1.0f / (float)PVRTFTAN(fFOVy * 0.5f); n = 1.0f / (fNear - fFar); mOut.f[ 0] = f / fRealAspect; mOut.f[ 1] = 0; mOut.f[ 2] = 0; mOut.f[ 3] = 0; mOut.f[ 4] = 0; mOut.f[ 5] = f; mOut.f[ 6] = 0; mOut.f[ 7] = 0; mOut.f[ 8] = 0; mOut.f[ 9] = 0; mOut.f[10] = (fFar + fNear) * n; mOut.f[11] = -1; mOut.f[12] = 0; mOut.f[13] = 0; mOut.f[14] = (2 * fFar * fNear) * n; mOut.f[15] = 0; if (bRotate) { PVRTMATRIXf mRotation, mTemp = mOut; PVRTMatrixRotationZF(mRotation, -90.0f*PVRT_PIf/180.0f); PVRTMatrixMultiplyF(mOut, mTemp, mRotation); } } /*!*************************************************************************** @Function PVRTMatrixOrthoLHF @Output mOut Orthographic matrix @Input w Width of the screen @Input h Height of the screen @Input zn Near clipping distance @Input zf Far clipping distance @Input bRotate Should we rotate it ? (for upright screens) @Description Create an orthographic matrix. *****************************************************************************/ void PVRTMatrixOrthoLHF( PVRTMATRIXf &mOut, const float w, const float h, const float zn, const float zf, const bool bRotate) { mOut.f[ 0] = 2 / w; mOut.f[ 1] = 0; mOut.f[ 2] = 0; mOut.f[ 3] = 0; mOut.f[ 4] = 0; mOut.f[ 5] = 2 / h; mOut.f[ 6] = 0; mOut.f[ 7] = 0; mOut.f[ 8] = 0; mOut.f[ 9] = 0; mOut.f[10] = 1 / (zf - zn); mOut.f[11] = zn / (zn - zf); mOut.f[12] = 0; mOut.f[13] = 0; mOut.f[14] = 0; mOut.f[15] = 1; if (bRotate) { PVRTMATRIXf mRotation, mTemp = mOut; PVRTMatrixRotationZF(mRotation, -90.0f*PVRT_PIf/180.0f); PVRTMatrixMultiplyF(mOut, mRotation, mTemp); } } /*!*************************************************************************** @Function PVRTMatrixOrthoRHF @Output mOut Orthographic matrix @Input w Width of the screen @Input h Height of the screen @Input zn Near clipping distance @Input zf Far clipping distance @Input bRotate Should we rotate it ? (for upright screens) @Description Create an orthographic matrix. *****************************************************************************/ void PVRTMatrixOrthoRHF( PVRTMATRIXf &mOut, const float w, const float h, const float zn, const float zf, const bool bRotate) { mOut.f[ 0] = 2 / w; mOut.f[ 1] = 0; mOut.f[ 2] = 0; mOut.f[ 3] = 0; mOut.f[ 4] = 0; mOut.f[ 5] = 2 / h; mOut.f[ 6] = 0; mOut.f[ 7] = 0; mOut.f[ 8] = 0; mOut.f[ 9] = 0; mOut.f[10] = 1 / (zn - zf); mOut.f[11] = zn / (zn - zf); mOut.f[12] = 0; mOut.f[13] = 0; mOut.f[14] = 0; mOut.f[15] = 1; if (bRotate) { PVRTMATRIXf mRotation, mTemp = mOut; PVRTMatrixRotationZF(mRotation, -90.0f*PVRT_PIf/180.0f); PVRTMatrixMultiplyF(mOut, mRotation, mTemp); } } /*!*************************************************************************** @Function PVRTMatrixVec3LerpF @Output vOut Result of the interpolation @Input v1 First vector to interpolate from @Input v2 Second vector to interpolate form @Input s Coefficient of interpolation @Description This function performs the linear interpolation based on the following formula: V1 + s(V2-V1). *****************************************************************************/ void PVRTMatrixVec3LerpF( PVRTVECTOR3f &vOut, const PVRTVECTOR3f &v1, const PVRTVECTOR3f &v2, const float s) { vOut.x = v1.x + s * (v2.x - v1.x); vOut.y = v1.y + s * (v2.y - v1.y); vOut.z = v1.z + s * (v2.z - v1.z); } /*!*************************************************************************** @Function PVRTMatrixVec3DotProductF @Input v1 First vector @Input v2 Second vector @Return Dot product of the two vectors. @Description This function performs the dot product of the two supplied vectors. *****************************************************************************/ float PVRTMatrixVec3DotProductF( const PVRTVECTOR3f &v1, const PVRTVECTOR3f &v2) { return (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); } /*!*************************************************************************** @Function PVRTMatrixVec3CrossProductF @Output vOut Cross product of the two vectors @Input v1 First vector @Input v2 Second vector @Description This function performs the cross product of the two supplied vectors. *****************************************************************************/ void PVRTMatrixVec3CrossProductF( PVRTVECTOR3f &vOut, const PVRTVECTOR3f &v1, const PVRTVECTOR3f &v2) { PVRTVECTOR3f result; /* Perform calculation on a dummy VECTOR (result) */ result.x = v1.y * v2.z - v1.z * v2.y; result.y = v1.z * v2.x - v1.x * v2.z; result.z = v1.x * v2.y - v1.y * v2.x; /* Copy result in pOut */ vOut = result; } /*!*************************************************************************** @Function PVRTMatrixVec3NormalizeF @Output vOut Normalized vector @Input vIn Vector to normalize @Description Normalizes the supplied vector. *****************************************************************************/ void PVRTMatrixVec3NormalizeF( PVRTVECTOR3f &vOut, const PVRTVECTOR3f &vIn) { float f; double temp; temp = (double)(vIn.x * vIn.x + vIn.y * vIn.y + vIn.z * vIn.z); temp = 1.0 / sqrt(temp); f = (float)temp; vOut.x = vIn.x * f; vOut.y = vIn.y * f; vOut.z = vIn.z * f; } /*!*************************************************************************** @Function PVRTMatrixVec3LengthF @Input vIn Vector to get the length of @Return The length of the vector @Description Gets the length of the supplied vector. *****************************************************************************/ float PVRTMatrixVec3LengthF( const PVRTVECTOR3f &vIn) { double temp; temp = (double)(vIn.x * vIn.x + vIn.y * vIn.y + vIn.z * vIn.z); return (float) sqrt(temp); } /*!*************************************************************************** @Function PVRTMatrixQuaternionIdentityF @Output qOut Identity quaternion @Description Sets the quaternion to (0, 0, 0, 1), the identity quaternion. *****************************************************************************/ void PVRTMatrixQuaternionIdentityF( PVRTQUATERNIONf &qOut) { qOut.x = 0; qOut.y = 0; qOut.z = 0; qOut.w = 1; } /*!*************************************************************************** @Function PVRTMatrixQuaternionRotationAxisF @Output qOut Rotation quaternion @Input vAxis Axis to rotate around @Input fAngle Angle to rotate @Description Create quaternion corresponding to a rotation of fAngle radians around submitted vector. *****************************************************************************/ void PVRTMatrixQuaternionRotationAxisF( PVRTQUATERNIONf &qOut, const PVRTVECTOR3f &vAxis, const float fAngle) { float fSin, fCos; fSin = (float)PVRTFSIN(fAngle * 0.5f); fCos = (float)PVRTFCOS(fAngle * 0.5f); /* Create quaternion */ qOut.x = vAxis.x * fSin; qOut.y = vAxis.y * fSin; qOut.z = vAxis.z * fSin; qOut.w = fCos; /* Normalise it */ PVRTMatrixQuaternionNormalizeF(qOut); } /*!*************************************************************************** @Function PVRTMatrixQuaternionToAxisAngleF @Input qIn Quaternion to transform @Output vAxis Axis of rotation @Output fAngle Angle of rotation @Description Convert a quaternion to an axis and angle. Expects a unit quaternion. *****************************************************************************/ void PVRTMatrixQuaternionToAxisAngleF( const PVRTQUATERNIONf &qIn, PVRTVECTOR3f &vAxis, float &fAngle) { float fCosAngle, fSinAngle; double temp; /* Compute some values */ fCosAngle = qIn.w; temp = 1.0f - fCosAngle*fCosAngle; fAngle = (float)PVRTFACOS(fCosAngle)*2.0f; fSinAngle = (float)sqrt(temp); /* This is to avoid a division by zero */ if ((float)fabs(fSinAngle)<0.0005f) fSinAngle = 1.0f; /* Get axis vector */ vAxis.x = qIn.x / fSinAngle; vAxis.y = qIn.y / fSinAngle; vAxis.z = qIn.z / fSinAngle; } /*!*************************************************************************** @Function PVRTMatrixQuaternionSlerpF @Output qOut Result of the interpolation @Input qA First quaternion to interpolate from @Input qB Second quaternion to interpolate from @Input t Coefficient of interpolation @Description Perform a Spherical Linear intERPolation between quaternion A and quaternion B at time t. t must be between 0.0f and 1.0f *****************************************************************************/ void PVRTMatrixQuaternionSlerpF( PVRTQUATERNIONf &qOut, const PVRTQUATERNIONf &qA, const PVRTQUATERNIONf &qB, const float t) { float fCosine, fAngle, A, B; /* Parameter checking */ if (t<0.0f || t>1.0f) { #ifndef BADA _RPT0(_CRT_WARN, "PVRTMatrixQuaternionSlerp : Bad parameters\n"); #endif qOut.x = 0; qOut.y = 0; qOut.z = 0; qOut.w = 1; return; } /* Find sine of Angle between Quaternion A and B (dot product between quaternion A and B) */ fCosine = qA.w*qB.w + qA.x*qB.x + qA.y*qB.y + qA.z*qB.z; if (fCosine < 0) { PVRTQUATERNIONf qi; /* <http://www.magic-software.com/Documentation/Quaternions.pdf> "It is important to note that the quaternions q and -q represent the same rotation... while either quaternion will do, the interpolation methods require choosing one over the other. "Although q1 and -q1 represent the same rotation, the values of Slerp(t; q0, q1) and Slerp(t; q0,-q1) are not the same. It is customary to choose the sign... on q1 so that... the angle between q0 and q1 is acute. This choice avoids extra spinning caused by the interpolated rotations." */ qi.x = -qB.x; qi.y = -qB.y; qi.z = -qB.z; qi.w = -qB.w; PVRTMatrixQuaternionSlerpF(qOut, qA, qi, t); return; } fCosine = PVRT_MIN(fCosine, 1.0f); fAngle = (float)PVRTFACOS(fCosine); /* Avoid a division by zero */ if (fAngle==0.0f) { qOut = qA; return; } /* Precompute some values */ A = (float)(PVRTFSIN((1.0f-t)*fAngle) / PVRTFSIN(fAngle)); B = (float)(PVRTFSIN(t*fAngle) / PVRTFSIN(fAngle)); /* Compute resulting quaternion */ qOut.x = A * qA.x + B * qB.x; qOut.y = A * qA.y + B * qB.y; qOut.z = A * qA.z + B * qB.z; qOut.w = A * qA.w + B * qB.w; /* Normalise result */ PVRTMatrixQuaternionNormalizeF(qOut); } /*!*************************************************************************** @Function PVRTMatrixQuaternionNormalizeF @Modified quat Vector to normalize @Description Normalize quaternion. *****************************************************************************/ void PVRTMatrixQuaternionNormalizeF(PVRTQUATERNIONf &quat) { float fMagnitude; double temp; /* Compute quaternion magnitude */ temp = quat.w*quat.w + quat.x*quat.x + quat.y*quat.y + quat.z*quat.z; fMagnitude = (float)sqrt(temp); /* Divide each quaternion component by this magnitude */ if (fMagnitude!=0.0f) { fMagnitude = 1.0f / fMagnitude; quat.x *= fMagnitude; quat.y *= fMagnitude; quat.z *= fMagnitude; quat.w *= fMagnitude; } } /*!*************************************************************************** @Function PVRTMatrixRotationQuaternionF @Output mOut Resulting rotation matrix @Input quat Quaternion to transform @Description Create rotation matrix from submitted quaternion. Assuming the quaternion is of the form [X Y Z W]: | 2 2 | | 1 - 2Y - 2Z 2XY - 2ZW 2XZ + 2YW 0 | | | | 2 2 | M = | 2XY + 2ZW 1 - 2X - 2Z 2YZ - 2XW 0 | | | | 2 2 | | 2XZ - 2YW 2YZ + 2XW 1 - 2X - 2Y 0 | | | | 0 0 0 1 | *****************************************************************************/ void PVRTMatrixRotationQuaternionF( PVRTMATRIXf &mOut, const PVRTQUATERNIONf &quat) { const PVRTQUATERNIONf *pQ; #if defined(BUILD_DX9) || defined(BUILD_D3DM) PVRTQUATERNIONf qInv; qInv.x = -quat.x; qInv.y = -quat.y; qInv.z = -quat.z; qInv.w = quat.w; pQ = &qInv; #else pQ = &quat; #endif /* Fill matrix members */ mOut.f[0] = 1.0f - 2.0f*pQ->y*pQ->y - 2.0f*pQ->z*pQ->z; mOut.f[1] = 2.0f*pQ->x*pQ->y - 2.0f*pQ->z*pQ->w; mOut.f[2] = 2.0f*pQ->x*pQ->z + 2.0f*pQ->y*pQ->w; mOut.f[3] = 0.0f; mOut.f[4] = 2.0f*pQ->x*pQ->y + 2.0f*pQ->z*pQ->w; mOut.f[5] = 1.0f - 2.0f*pQ->x*pQ->x - 2.0f*pQ->z*pQ->z; mOut.f[6] = 2.0f*pQ->y*pQ->z - 2.0f*pQ->x*pQ->w; mOut.f[7] = 0.0f; mOut.f[8] = 2.0f*pQ->x*pQ->z - 2*pQ->y*pQ->w; mOut.f[9] = 2.0f*pQ->y*pQ->z + 2.0f*pQ->x*pQ->w; mOut.f[10] = 1.0f - 2.0f*pQ->x*pQ->x - 2*pQ->y*pQ->y; mOut.f[11] = 0.0f; mOut.f[12] = 0.0f; mOut.f[13] = 0.0f; mOut.f[14] = 0.0f; mOut.f[15] = 1.0f; } /*!*************************************************************************** @Function PVRTMatrixQuaternionMultiplyF @Output qOut Resulting quaternion @Input qA First quaternion to multiply @Input qB Second quaternion to multiply @Description Multiply quaternion A with quaternion B and return the result in qOut. *****************************************************************************/ void PVRTMatrixQuaternionMultiplyF( PVRTQUATERNIONf &qOut, const PVRTQUATERNIONf &qA, const PVRTQUATERNIONf &qB) { PVRTVECTOR3f CrossProduct; /* Compute scalar component */ qOut.w = (qA.w*qB.w) - (qA.x*qB.x + qA.y*qB.y + qA.z*qB.z); /* Compute cross product */ CrossProduct.x = qA.y*qB.z - qA.z*qB.y; CrossProduct.y = qA.z*qB.x - qA.x*qB.z; CrossProduct.z = qA.x*qB.y - qA.y*qB.x; /* Compute result vector */ qOut.x = (qA.w * qB.x) + (qB.w * qA.x) + CrossProduct.x; qOut.y = (qA.w * qB.y) + (qB.w * qA.y) + CrossProduct.y; qOut.z = (qA.w * qB.z) + (qB.w * qA.z) + CrossProduct.z; /* Normalize resulting quaternion */ PVRTMatrixQuaternionNormalizeF(qOut); } /*!*************************************************************************** @Function PVRTMatrixLinearEqSolveF @Input pSrc 2D array of floats. 4 Eq linear problem is 5x4 matrix, constants in first column @Input nCnt Number of equations to solve @Output pRes Result @Description Solves 'nCnt' simultaneous equations of 'nCnt' variables. pRes should be an array large enough to contain the results: the values of the 'nCnt' variables. This fn recursively uses Gaussian Elimination. *****************************************************************************/ void PVRTMatrixLinearEqSolveF( float * const pRes, float ** const pSrc, // 2D array of floats. 4 Eq linear problem is 5x4 matrix, constants in first column. const int nCnt) { int i, j, k; float f; #if 0 /* Show the matrix in debug output */ _RPT1(_CRT_WARN, "LinearEqSolve(%d)\n", nCnt); for(i = 0; i < nCnt; ++i) { _RPT1(_CRT_WARN, "%.8f |", pSrc[i][0]); for(j = 1; j <= nCnt; ++j) _RPT1(_CRT_WARN, " %.8f", pSrc[i][j]); _RPT0(_CRT_WARN, "\n"); } #endif if(nCnt == 1) { #ifndef BADA _ASSERT(pSrc[0][1] != 0); #endif pRes[0] = pSrc[0][0] / pSrc[0][1]; return; } // Loop backwards in an attempt avoid the need to swap rows i = nCnt; while(i) { --i; if(pSrc[i][nCnt] != 0) { // Row i can be used to zero the other rows; let's move it to the bottom if(i != (nCnt-1)) { for(j = 0; j <= nCnt; ++j) { // Swap the two values f = pSrc[nCnt-1][j]; pSrc[nCnt-1][j] = pSrc[i][j]; pSrc[i][j] = f; } } // Now zero the last columns of the top rows for(j = 0; j < (nCnt-1); ++j) { #ifndef BADA _ASSERT(pSrc[nCnt-1][nCnt] != 0); #endif f = pSrc[j][nCnt] / pSrc[nCnt-1][nCnt]; // No need to actually calculate a zero for the final column for(k = 0; k < nCnt; ++k) { pSrc[j][k] -= f * pSrc[nCnt-1][k]; } } break; } } // Solve the top-left sub matrix PVRTMatrixLinearEqSolveF(pRes, pSrc, nCnt - 1); // Now calc the solution for the bottom row f = pSrc[nCnt-1][0]; for(k = 1; k < nCnt; ++k) { f -= pSrc[nCnt-1][k] * pRes[k-1]; } #ifndef BADA _ASSERT(pSrc[nCnt-1][nCnt] != 0); #endif f /= pSrc[nCnt-1][nCnt]; pRes[nCnt-1] = f; #if 0 { float fCnt; /* Verify that the result is correct */ fCnt = 0; for(i = 1; i <= nCnt; ++i) fCnt += pSrc[nCnt-1][i] * pRes[i-1]; _ASSERT(abs(fCnt - pSrc[nCnt-1][0]) < 1e-3); } #endif } /***************************************************************************** End of file (PVRTMatrixF.cpp) *****************************************************************************/
30.436031
132
0.528552
49221953ee2738b15d33786523097b56f7c985b5
384
cpp
C++
fre_check.cpp
1432junaid/cpp
8faf7ac856a50937f3a563dc8d23ee8e205a489c
[ "MIT" ]
null
null
null
fre_check.cpp
1432junaid/cpp
8faf7ac856a50937f3a563dc8d23ee8e205a489c
[ "MIT" ]
null
null
null
fre_check.cpp
1432junaid/cpp
8faf7ac856a50937f3a563dc8d23ee8e205a489c
[ "MIT" ]
null
null
null
#include<iostream> #include<cstring> using namespace std; int main(){ char *city = "lucknow junction"; char *c = "lucknow"; int hash[26]= {0}; int len = strlen(city); for(int i = 0; i<len ; i++){ if(city[i] >= 97 && city[i] <= 122) hash[city[i] - 'a']++; } for(int i=0; i<26;i++){ if(hash[i]>0){ cout<<char(i+'a')<<" "<<hash[i]<<endl; } } // if(len) return 0; }
17.454545
42
0.533854
49267adedbd3f62879ef3c4aa4e7a8c28800caa1
6,300
cpp
C++
src/libs/qlib/qdmvideoout.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/libs/qlib/qdmvideoout.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/libs/qlib/qdmvideoout.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
1
2021-01-03T16:16:47.000Z
2021-01-03T16:16:47.000Z
/* * QDMVideoOut - definition/implementation * 13-11-99: Support for VL65 interface * NOTES: * - Generated by mkclass * BUGS: * - Same bugs apply as for QDMVideoIn; event handling of VL was changed * to generate events for all paths in one place. Need to demultiplex. * (C) 01-01-98 MarketGraph/RVG */ #include <qlib/dmvideoout.h> #include <qlib/dmbpool.h> #include <qlib/app.h> #include <qlib/debug.h> DEBUG_ENABLE #undef DBG_CLASS #define DBG_CLASS "QDMVideoOut" QDMVideoOut::QDMVideoOut() : QDMObject() { QVideoServer *vs; int x,y; DBG_C("ctor") vs=app->GetVideoServer(); // Nodes from video to memory srcNode=new QVideoNode(vs,VL_SRC,VL_MEM,VL_ANY); drnNode=new QVideoNode(vs,VL_DRN,VL_VIDEO,VL_ANY); // Create path pathOut=new QVideoPath(vs,VL_ANY,srcNode,drnNode); // Setup hardware if(!pathOut->Setup(VL_SHARE,VL_SHARE)) { qerr("QDMVideoOut: can't setup input path"); } // Default control values SetTiming(VL_TIMING_625_CCIR601); //SetPacking(VL_PACKING_YVYU_422_8); SetPacking(VL_PACKING_ABGR_8); //drnNode->SetControl(VL_CAP_TYPE,VL_CAPTURE_NONINTERLEAVED); //srcNode->SetControl(VL_CAP_TYPE,VL_CAPTURE_INTERLEAVED); SetCaptureType(VL_CAPTURE_INTERLEAVED); SetFormat(VL_FORMAT_RGB); //srcNode->SetControl(VL_FORMAT,VL_FORMAT_RGB); drnNode->SetControl(VL_SYNC,VL_SYNC_INTERNAL); //srcNode->GetXYControl(VL_SIZE,&x,&y); //SetZoomSize(x,y); //drnNode->SetControl(VL_ORIGIN,0,16); // ?? //drnNode->SetControl(VL_ZOOM,1,1); //srcNode->SetControl(VL_TIMING,VL_TIMING_625_CCIR601); //drnNode->SetControl(VL_CAP_TYPE,VL_CAPTURE_INTERLEAVED); SetLayout(VL_LAYOUT_GRAPHICS); // Debug //qdbg(" video in transfer size=%d\n",pathOut->GetTransferSize()); drnNode->GetXYControl(VL_SIZE,&x,&y); //qdbg(" video in size: %dx%d\n",x,y); } QDMVideoOut::~QDMVideoOut() { delete pathOut; delete drnNode; delete srcNode; } /******* * POOL * *******/ void QDMVideoOut::AddConsumerParams(QDMBPool *pool) // Get necessary params to use this input object { #ifdef USE_VL_65 vlDMGetParams(app->GetVideoServer()->GetSGIServer(), pathOut->GetSGIPath(),drnNode->GetSGINode(), pool->GetCreateParams()->GetDMparams()); #else vlDMPoolGetParams(app->GetVideoServer()->GetSGIServer(), pathOut->GetSGIPath(),drnNode->GetSGINode(), pool->GetCreateParams()->GetDMparams()); #endif qdbg("QDMVideoOut:GetPoolParams; buffersize=%d\n", pool->GetCreateParams()->GetInt(DM_BUFFER_SIZE)); } void QDMVideoOut::RegisterPool(QDMBPool *pool) { if(vlDMPoolRegister(app->GetVideoServer()->GetSGIServer(), pathOut->GetSGIPath(),drnNode->GetSGINode(),pool->GetDMbufferpool())<0) qerr("QDMVideoOut: can't register pool"); } /******* * INFO * *******/ int QDMVideoOut::GetFD() { #ifdef USE_VL_65 //return drnNode->GetFD(); return srcNode->GetFD(); #else return pathOut->GetFD(); #endif } void QDMVideoOut::GetSize(int *w,int *h) { drnNode->GetXYControl(VL_SIZE,w,h); } int QDMVideoOut::GetTransferSize() { if(!pathOut)return 0; return pathOut->GetTransferSize(); } void QDMVideoOut::SetSize(int w,int h) { //drnNode->SetControl(VL_SIZE,w,h); srcNode->SetControl(VL_SIZE,w,h); } void QDMVideoOut::SetZoomSize(int w,int h) { drnNode->SetControl(VL_MVP_ZOOMSIZE,w,h); } void QDMVideoOut::SetOffset(int x,int y) { drnNode->SetControl(VL_SIZE,x,y); } void QDMVideoOut::SetOrigin(int x,int y) { drnNode->SetControl(VL_ORIGIN,x,y); } void QDMVideoOut::SetLayout(int n) { srcNode->SetControl(VL_LAYOUT,n); } void QDMVideoOut::SetFormat(int n) { srcNode->SetControl(VL_FORMAT,n); } void QDMVideoOut::SetPacking(int n) { srcNode->SetControl(VL_PACKING,n); } void QDMVideoOut::SetCaptureType(int n) { srcNode->SetControl(VL_CAP_TYPE,n); } void QDMVideoOut::SetTiming(int n) { drnNode->SetControl(VL_TIMING,n); } void QDMVideoOut::SetGenlock(bool b) { drnNode->SetControl(VL_SYNC,b?VL_SYNC_GENLOCK:VL_SYNC_INTERNAL); } void QDMVideoOut::Start() // Start transferring { #ifdef FUTURE VLTransferDescriptor xferDesc; #endif pathOut->SelectEvents( VLTransferCompleteMask | VLStreamBusyMask | VLStreamPreemptedMask | VLAdvanceMissedMask | VLStreamAvailableMask | VLSyncLostMask | VLStreamStartedMask | VLStreamStoppedMask | VLSequenceLostMask | VLControlChangedMask | VLTransferCompleteMask | VLTransferFailedMask | //VLEvenVerticalRetraceMask | //VLOddVerticalRetraceMask | //VLFrameVerticalRetraceMask | VLDeviceEventMask | VLDefaultSourceMask | VLControlRangeChangedMask | VLControlPreemptedMask | VLControlAvailableMask | VLDefaultDrainMask | VLStreamChangedMask | VLTransferError); /*pathOut->SelectEvents(VLTransferCompleteMask| VLTransferFailedMask| VLStreamPreemptedMask| VLDeviceEventMask);*/ #ifdef FUTURE xferDesc.mode=VL_TRANSFER_MODE_CONTINUOUS; xferDesc.count=1; xferDesc.delay=0; xferDesc.trigger=VLTriggerImmediate; #endif pathOut->BeginTransfer(); } void QDMVideoOut::GetEvent(VLEvent *event) // This is actually not advised to use under USE_VL_65 // Use QVideoServer's event handling functions; this function // will return events for ANY video path, not just the video out path (!) { #ifdef USE_VL_65 if(vlPending(app->GetVideoServer()->GetSGIServer())<=0) return /*FALSE*/; if(vlNextEvent(app->GetVideoServer()->GetSGIServer(),event)!=DM_SUCCESS) #else if(vlEventRecv(app->GetVideoServer()->GetSGIServer(), pathOut->GetSGIPath(),event)!=DM_SUCCESS) #endif { qerr("QDMVideoOut:GetEvent failed vlEventRecv"); return; } } void QDMVideoOut::Send(DMbuffer buf) { #ifdef USE_VL_65 if(vlDMBufferPutValid(app->GetVideoServer()->GetSGIServer(), pathOut->GetSGIPath(),drnNode->GetSGINode(),buf)!=0) #else if(vlDMBufferSend(app->GetVideoServer()->GetSGIServer(), pathOut->GetSGIPath(),buf)!=0) #endif { qerr("QDMVideoOut::Send(buf) failed; %s",vlStrError(vlGetErrno())); } }
27.272727
75
0.685079
492baaf94ed04edfec0954b99b40d808fec4c397
3,165
cpp
C++
src/daemon/CmdListener.cpp
klx99/Elastos.Service.CarrierGroup
a1922402af66308178f048352ab6038f4c2d848b
[ "MIT" ]
null
null
null
src/daemon/CmdListener.cpp
klx99/Elastos.Service.CarrierGroup
a1922402af66308178f048352ab6038f4c2d848b
[ "MIT" ]
null
null
null
src/daemon/CmdListener.cpp
klx99/Elastos.Service.CarrierGroup
a1922402af66308178f048352ab6038f4c2d848b
[ "MIT" ]
null
null
null
#include "CmdListener.hpp" #include <vector> #include <Carrier.hpp> #include <CmdParser.hpp> #include <DateTime.hpp> #include <ErrCode.hpp> #include <GroupCmdParser.hpp> #include <Log.hpp> #include <OptParser.hpp> namespace elastos { /* =========================================== */ /* === static variables initialize =========== */ /* =========================================== */ /* =========================================== */ /* === static function implement ============= */ /* =========================================== */ /* =========================================== */ /* === class public function implement ====== */ /* =========================================== */ int CmdListener::config(std::weak_ptr<Carrier> carrier) { this->carrier = carrier; this->cmdParser = CmdParser::Factory::Create(); int rc = this->cmdParser->config(carrier); CHECK_ERROR(rc); return 0; } void CmdListener::onError(int errCode) { Log::D(Log::TAG, "%s errCode=%d", __PRETTY_FUNCTION__, errCode); } void CmdListener::onStatusChanged(const std::string& userId, Status status) { Log::D(Log::TAG, "%s", __PRETTY_FUNCTION__); } void CmdListener::onFriendRequest(const std::string& friendCode, const std::string& summary) { Log::D(Log::TAG, "%s", __PRETTY_FUNCTION__); auto cmdline = CmdParser::Cmd::AddFriend + " " + friendCode + " " + summary; int rc = cmdParser->parse(carrier, cmdline, friendCode, 0); if(rc < 0) { onError(rc); return; } return; } void CmdListener::onFriendStatusChanged(const std::string& friendCode, Status status) { Log::D(Log::TAG, "%s", __PRETTY_FUNCTION__); bool isGroup = !OptParser::GetInstance()->isManager(); if(isGroup && status == Status::Online) { int rc = cmdParser->parse(carrier, GroupCmdParser::Cmd::ForwardMessage, friendCode, DateTime::CurrentNS()); CHECK_RETVAL(rc); } } void CmdListener::onReceivedMessage(const std::string& friendCode, int64_t timestamp, const std::vector<uint8_t>& message) { Log::D(Log::TAG, "%s", __PRETTY_FUNCTION__); std::string cmdline = std::string{message.begin(), message.end()}; // ignore hyper return receipt if(cmdline == "{\"command\":\"messageSeen\"}") { return; } if(cmdline.find_first_of('/') != 0) { // if not a command, exec as forward. cmdline = GroupCmdParser::Cmd::ForwardMessage + " " + cmdline; } int rc = cmdParser->parse(carrier, cmdline, friendCode, timestamp); CHECK_RETVAL(rc); } /* =========================================== */ /* === class protected function implement === */ /* =========================================== */ /* =========================================== */ /* === class private function implement ===== */ /* =========================================== */ } // namespace elastos
29.305556
80
0.484044
492e26e67ca7f81605a361d64d4f8a44e9a0e845
847
cpp
C++
HW2/Part2/Question4/main.cpp
Coslate/Data_Structures
d839e2d24c15b1ba20c772fc232b1a98b1b6dedf
[ "MIT" ]
null
null
null
HW2/Part2/Question4/main.cpp
Coslate/Data_Structures
d839e2d24c15b1ba20c772fc232b1a98b1b6dedf
[ "MIT" ]
null
null
null
HW2/Part2/Question4/main.cpp
Coslate/Data_Structures
d839e2d24c15b1ba20c772fc232b1a98b1b6dedf
[ "MIT" ]
null
null
null
//main.cpp #include <iostream> #include <Stack.h> #include <solution.h> #include <cstring> std::vector<std::vector<bool>> tmp_maze; std::vector<std::vector<bool>> maze; int rows=0; int cols=0; int m = 0, p = 0; std::string input_maze = "NO-INPUT"; int main(int argc, char*argv[]){ if(argc < 3){ std::cerr<<"Error: There should be at least one input argument like ./main -input_maze arg1."<<std::endl; return EXIT_FAILURE; } if( (argc > 1) && (strcmp(argv[1], "-input_maze") == 0)){ input_maze = argv[2]; } ReadFile(input_maze, tmp_maze, rows, cols); std::cout<<"> Initialization..."<<std::endl; AugmentedMazeBuildWall(tmp_maze, maze, rows, cols, m, p); PrintMatrix("maze", maze, rows+2, cols+2); std::cout<<"> Path..."<<std::endl; Path(maze, m, p); return EXIT_SUCCESS; }
24.2
113
0.612751
492e48c335a5776954c066f04cfc5aaf40673a54
69
cpp
C++
JPMorgan/JPMorgan.cpp
awoimbee/superberniebros
728531ad82817b8f9778d8fc72b2c72f1a90ae0b
[ "MIT" ]
2
2020-06-30T06:15:57.000Z
2020-06-30T06:25:12.000Z
JPMorgan/JPMorgan.cpp
awoimbee/superberniebros
728531ad82817b8f9778d8fc72b2c72f1a90ae0b
[ "MIT" ]
null
null
null
JPMorgan/JPMorgan.cpp
awoimbee/superberniebros
728531ad82817b8f9778d8fc72b2c72f1a90ae0b
[ "MIT" ]
1
2022-03-02T18:45:13.000Z
2022-03-02T18:45:13.000Z
// // Created by Eli Winkelman on 6/13/17. // #include "JPMorgan.h"
11.5
39
0.637681
4932ae43ff6878714d2571b92108f6a202b5473d
2,095
cpp
C++
MAX/library/test/Core/Transformer/AgentTransferManagerTransformerTest.cpp
isabella232/max-toolkit
6fc0b416efa064094ffc98daf6ee8755c3ec73fe
[ "Apache-2.0" ]
4
2021-09-10T18:35:11.000Z
2022-01-07T11:33:10.000Z
MAX/library/test/Core/Transformer/AgentTransferManagerTransformerTest.cpp
alexa/max-toolkit
6fc0b416efa064094ffc98daf6ee8755c3ec73fe
[ "Apache-2.0" ]
1
2022-02-08T19:22:12.000Z
2022-02-08T20:42:28.000Z
MAX/library/test/Core/Transformer/AgentTransferManagerTransformerTest.cpp
isabella232/max-toolkit
6fc0b416efa064094ffc98daf6ee8755c3ec73fe
[ "Apache-2.0" ]
3
2021-09-20T22:11:32.000Z
2022-02-08T17:26:53.000Z
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 "Core/Transformer/AgentTransferManagerTransformer.h" #include "Agent/AgentTransferManager.h" #include "MultiAgentExperience/Agent/Agent.h" #include "Core/Mocks/MockAgentStoreInterface.h" #include "Integration/TestAgent.h" #include <gmock/gmock.h> #include <memory> namespace multiAgentExperience { namespace library { namespace core { namespace transformer { namespace test { using namespace ::testing; class AgentTransferManagerTransformerTest : public ::testing::Test { protected: std::shared_ptr<AgentTransferManagerTransformer> m_transformer; std::shared_ptr<MockAgentStoreInterface> m_mockAgentStore; virtual void SetUp() override { m_mockAgentStore = std::make_shared<NiceMock<MockAgentStoreInterface>>(); auto agentTransferManager = std::make_shared<agent::AgentTransferManager>(); m_transformer = std::make_shared<AgentTransferManagerTransformer>( multiAgentExperience::actor::ActorId("agent"), agentTransferManager, m_mockAgentStore); } }; TEST_F(AgentTransferManagerTransformerTest, test_invoke_agent_invokes_the_agent) { auto id = actor::ActorId("id"); auto agent = std::make_shared<library::test::TestAgent>(id); EXPECT_CALL(*m_mockAgentStore, getAgentById(id)).WillRepeatedly(Return(agent)); m_transformer->invokeAgent(agent->getId()); ASSERT_TRUE(agent->wasTransferredTo()); } } // namespace test } // namespace transformer } // namespace core } // namespace library } // namespace multiAgentExperience
32.734375
99
0.75179
4933ed9f9d4110a5473f465f757547973d61aa35
1,027
cpp
C++
python/popart._internal.ir/bindings/transforms/mergeexchange.cpp
graphcore/popart
15ce5b098638dc34a4d41ae2a7621003458df798
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
python/popart._internal.ir/bindings/transforms/mergeexchange.cpp
graphcore/popart
15ce5b098638dc34a4d41ae2a7621003458df798
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
python/popart._internal.ir/bindings/transforms/mergeexchange.cpp
graphcore/popart
15ce5b098638dc34a4d41ae2a7621003458df798
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2021 Graphcore Ltd. All rights reserved. #include "bindings/transforms/autodiff.hpp" #include "bindings/transforms/transform.hpp" #include <pybind11/cast.h> #include <pybind11/functional.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <popart/graph.hpp> #include <popart/transforms/mergeexchange.hpp> #include <popart/transforms/transform.hpp> namespace py = pybind11; namespace popart { namespace _internal { namespace ir { namespace transforms { void bindMergeExchange(py::module &m) { py::class_<MergeExchange, Transform, PyTransform<MergeExchange>>( m, "MergeExchange") .def(py::init<>()) .def("id", &MergeExchange::id) .def("apply", &MergeExchange::apply) .def("applyToOps", &MergeExchange::applyToOps, py::return_value_policy::reference) .def("getId", &MergeExchange::getId) .def("getName", &MergeExchange::getName); } } // namespace transforms } // namespace ir } // namespace _internal } // namespace popart
26.333333
67
0.701071
49349850ebfb8542f3cc77a64fea0828cdd3fc4b
443
cpp
C++
PAT/PAT Basic/1016.cpp
Accelerator404/Algorithm-Demonstration
e40a499c23a56d363c743c76ac967d9c4247a4be
[ "Apache-2.0" ]
1
2019-09-18T23:45:27.000Z
2019-09-18T23:45:27.000Z
PAT/PAT Basic/1016.cpp
Accelerator404/Algorithm-Demonstration
e40a499c23a56d363c743c76ac967d9c4247a4be
[ "Apache-2.0" ]
null
null
null
PAT/PAT Basic/1016.cpp
Accelerator404/Algorithm-Demonstration
e40a499c23a56d363c743c76ac967d9c4247a4be
[ "Apache-2.0" ]
1
2019-09-18T23:45:28.000Z
2019-09-18T23:45:28.000Z
#include <iostream> #include <string> using namespace std; //PAT Basic No.1016 “部分A+B” int P(string K, int Dk) { int count = 0; for (int i = 0; i < K.length(); ++i) if (K.at(i) - '0' == Dk) count++; if (count == 0) return 0; else { string Pk(count, Dk + '0'); return strtol(Pk.c_str(), nullptr, 10); } } int main() { int Da,Db; string A, B; cin >> A >> Da >> B >> Db; cout << P(A, Da) + P(B, Db) << endl;; return 0; }
16.407407
41
0.532731
49388536df90b4ec85bfc27343dc87a9fb12632d
870
cc
C++
src/util/rename.cc
matt-gretton-dann/gd-posix-apps
3abf398269203883c8e13511d811c7d6f0cb1cf8
[ "Apache-2.0" ]
null
null
null
src/util/rename.cc
matt-gretton-dann/gd-posix-apps
3abf398269203883c8e13511d811c7d6f0cb1cf8
[ "Apache-2.0" ]
164
2020-12-30T11:35:34.000Z
2021-05-24T12:58:26.000Z
src/util/rename.cc
matt-gretton-dann/gd-posix-apps
3abf398269203883c8e13511d811c7d6f0cb1cf8
[ "Apache-2.0" ]
null
null
null
/** \file src/util/rename.cc * \brief Platform independent version of rename() * \author Copyright 2021, Matthew Gretton-Dann * SPDX-License-Identifier: Apache-2.0 */ #include "util/file.hh" #ifdef _WIN32 # include "util/utils.hh" # include <Windows.h> # include <cerrno> # include <cstddef> extern "C" void __support_log(char const* format, ...); // NOLINT auto GD::Util::rename(char const* _old, char const* _new) __NOEXCEPT -> int { BOOL success = ::ReplaceFileA(_new, _old, nullptr, 0, nullptr, nullptr); if (success == 0) { errno = EINVAL; DWORD error = ::GetLastError(); __support_log("ReplaceFileA(%s, %s) failed: %lx\n", _new, _old, error); return -1; } return 0; } #else # include <cstdio> auto GD::Util::rename(char const* _old, char const* _new) __NOEXCEPT -> int { return ::rename(_old, _new); } #endif
24.166667
75
0.652874
4938c2f3c1232ac88668257f33deb437724fcb0e
35,222
cpp
C++
src/mat_vec_fns_II.cpp
zzalscv2/FFEA
da8a09dadb1b3978a3d230dc79d9b163d7889242
[ "Apache-2.0" ]
null
null
null
src/mat_vec_fns_II.cpp
zzalscv2/FFEA
da8a09dadb1b3978a3d230dc79d9b163d7889242
[ "Apache-2.0" ]
null
null
null
src/mat_vec_fns_II.cpp
zzalscv2/FFEA
da8a09dadb1b3978a3d230dc79d9b163d7889242
[ "Apache-2.0" ]
1
2021-04-03T16:08:21.000Z
2021-04-03T16:08:21.000Z
// // This file is part of the FFEA simulation package // // Copyright (c) by the Theory and Development FFEA teams, // as they appear in the README.md file. // // FFEA 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 3 of the License, or // (at your option) any later version. // // FFEA 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 FFEA. If not, see <http://www.gnu.org/licenses/>. // // To help us fund FFEA development, we humbly ask that you cite // the research papers on the package. // #include "mat_vec_fns_II.h" #include <iostream> using std::cout; using std::endl; ///////////////// SECTION 0 //////////////////// //////// Constants and scalar functions /////// //////////////////////////////////////////////// // /// check whether two scalars have the same sign template <class t_scalar> bool sameSign(t_scalar a, t_scalar b){ // return a <= ffea_const::zero == b <= ffea_const::zero; if (a*b >= 0) return true; return false; } /** Given 3 integers n0, n1, n2 * return the index missing in the list [0,1,2,3] */ int getMissingNode(int n0, int n1, int n2) { if ((n0 == 0) || (n1 == 0) || (n2 ==0)) { if ((n0 == 1) || (n1 == 1) || (n2 ==1)) { if ((n0 == 2) || (n1 == 2) || (n2 ==2)) { return 3; } else { return 2; } } else { return 1; } } else { return 0; } } /** Given 1 integers iN, * return the index missing indices of the list [0,1,2,3] */ void getRestOfNodes(int iN, int &iO0, int &iO1, int &iO2) { if (iN == 0) { iO0 = 1; iO1 = 2; iO2 = 3; } else if (iN == 1) { iO0 = 0; iO1 = 2; iO2 = 3; } else if (iN == 2) { iO0 = 0; iO1 = 1; iO2 = 3; } else { iO0 = 0; iO1 = 1; iO2 = 2; } } /** Given 1 integers iN, * return the index missing indices of the list [0,1,2,3] */ void getMissingPair(int in0, int in1, int &on0, int &on1) { for (int i=0; i<4; i++) { if ((i != in0) && (i != in1)) { on0 = i; on1 = getMissingNode(in0, in1, on0); break; } } } ////////////////// SECTION 1 /////////////////////// /// Basic operations for arr3, i. e., scalar v[3]// //////////////////////////////////////////////////// /** Add vectors vecA and vecB into res. */ /** res can also be vecA or vecB */ template <class t_scalar, class brr3> void arr3arr3Add(arr3_view<t_scalar,brr3> vecA, arr3_view<t_scalar,brr3> vecB, arr3_view<t_scalar,brr3> res){ for (int i=0; i<3; i++) { res[i] = vecA[i] + vecB[i]; } } /** res = vecA - vecB */ /** res can be either vecA or vecB */ // void arr3arr3Substract(arr3 &vecA, arr3 &vecB, arr3 &res){ // template <class brr3> void arr3arr3Substract(brr3 &vecA, brr3 &vecB, brr3 &res){ template <class t_scalar, class brr3> void arr3arr3Substract(arr3_view<t_scalar,brr3> vecA, arr3_view<t_scalar,brr3> vecB, arr3_view<t_scalar,brr3> res){ for (int i=0; i<3; i++) { res[i] = vecA[i] - vecB[i]; } } /** w = u x v */ /** (w != u) && (w != v) */ // void arr3arr3VectorProduct(arr3 (&u), arr3 (&v), arr3 (&w)){ template <class t_scalar, class brr3> void arr3arr3VectorProduct(arr3_view<t_scalar,brr3> u, arr3_view<t_scalar,brr3> v, arr3_view<t_scalar,brr3> w){ w[0] = u[1]*v[2] - v[1]*u[2]; w[1] = -u[0]*v[2] + v[0]*u[2]; w[2] = u[0]*v[1] - v[0]*u[1]; } /** return the dot product for arrays vecA and vecB */ // scalar arr3arr3DotProduct(arr3 &vecA, arr3 &vecB) { template <class t_scalar, class brr3> t_scalar arr3arr3DotProduct(arr3_view<t_scalar,brr3> vecA, arr3_view<t_scalar,brr3> vecB) { t_scalar result = 0.0; for (int i=0; i<3; i++) { // cout << "vecA[" << i << "]: " << vecA[i] << " vecB[" << i << "]: " << vecB[i] << endl; result += vecA[i] * vecB[i]; } return result; } /** Normalise vector arr3 e */ template <class t_scalar, class brr3> void arr3Normalise(arr3_view<t_scalar,brr3> e){ t_scalar norm = 0.0; for (int i=0; i<3; i++) { norm += e[i]*e[i]; } norm = sqrt(norm); for (int i=0; i<3; i++) { e[i] /= norm; } } /** get the normalised vector of arr3 e into arr3 n */ // template <class t_scalar, class brr3> void arr3Normalise2(brr3 &e, brr3 &n){ template <class t_scalar, class brr3> void arr3Normalise2(arr3_view<t_scalar,brr3> e, arr3_view<t_scalar,brr3> n){ t_scalar norm = 0.0; for (int i=0; i<3; i++) { norm += e[i]*e[i]; } if (norm == 0.0) throw -1; norm = sqrt(norm); for (int i=0; i<3; i++) { n[i] = e[i]/norm; } } /** resize vector u, given scalar f */ template <class t_scalar, class brr3> void arr3Resize(t_scalar f, arr3_view<t_scalar,brr3> u){ for (int i=0; i<3; i++) { u[i] = f*u[i]; } } /** resize vector u into vector v, given scalar f */ template <class t_scalar, class brr3> void arr3Resize2(t_scalar f, arr3_view<t_scalar,brr3> u, arr3_view<t_scalar,brr3> v){ #pragma omp simd for (int i=0; i<3; i++) { v[i] = f*u[i]; } } /** Given a scalar f, change v so that v += f*u */ template <class t_scalar, class brr3> void arr3Resize3(t_scalar f, arr3_view<t_scalar,brr3> u, arr3_view<t_scalar,brr3> v){ #pragma omp simd for (int i=0; i<3; i++) { v[i] += f*u[i]; } } /** cp arr3 u into arr3 v */ template <class t_scalar, class brr3> void arr3Store(arr3_view<t_scalar,brr3> u, arr3_view<t_scalar,brr3> v){ #pragma omp simd for (int i=0; i<3; i++) { v[i] = u[i]; } } /** return the distance from vecA to vecB */ template <class t_scalar, class brr3> t_scalar arr3arr3Distance(arr3_view<t_scalar,brr3> vecA, arr3_view<t_scalar,brr3> vecB){ t_scalar d=0.0; for (int i=0; i<3; i++){ d += (vecA[i] - vecB[i])*(vecA[i] - vecB[i]); } return sqrt(d); } /** Return the length of a vector v */ template <class t_scalar, class brr3> t_scalar mag(arr3_view<t_scalar,brr3> v) { t_scalar s=0.0; #pragma omp simd reduction(+:s) for (int i=0; i<3; i++) { s += v[i] * v[i]; } return sqrt(s); } /** Return the squared length of a vector v */ template <class t_scalar, class brr3> t_scalar mag2(arr3_view<t_scalar,brr3> v) { t_scalar s=0.0; for (int i=0; i<3; i++) { s += v[i] * v[i]; } return s; } template <class brr3> void arr3Initialise(brr3 &v){ for (int i=0; i<3; i++) { v[i] = ffea_const::zero; } } template <class t_scalar, class brr3> t_scalar detByRows(arr3_view<t_scalar,brr3> a, arr3_view<t_scalar,brr3> b, arr3_view<t_scalar,brr3> c){ t_scalar det = 0; det = a[0] * (b[1] * c[2] - b[2] * c[1]); det += a[1] * (b[2] * c[0] - b[0] * c[2]); det += a[2] * (b[0] * c[1] - b[1] * c[0]); return det; } template <class t_scalar, class brr3> t_scalar detByCols(arr3_view<t_scalar,brr3> a, arr3_view<t_scalar,brr3> b, arr3_view<t_scalar,brr3> c){ t_scalar det = 0; det = a[0] * (b[1] * c[2] - b[2] * c[1]); det += b[0] * (c[1] * a[2] - c[2] * a[1]); det += c[0] * (a[1] * b[2] - a[2] * b[1]); return det; } //////////////////////////////////////////////// ////////////// END OF SECTION 1 //////////////// //////////////////////////////////////////////// ///////////////// SECTION 2 //////////////////// ////// Geometric functions for arr3 types ////// //////////////////////////////////////////////// /** t = unit(vecA - vecB) */ /** t can be either vecA or vecB */ // void tangent(arr3 &vecA, arr3 &vecB, arr3 &t){ template <class t_scalar, class brr3> void tangent(brr3 &vecA, brr3 &vecB, brr3 &t){ t_scalar w=0; for (int i=0; i<3; i++) { t[i] = vecA[i] - vecB[i]; w += t[i] * t[i]; } w = sqrt(w); for (int i=0; i<3; i++) { t[i] /= w; } } /** w = unit(u x v) */ /** (w != u) && (w != v) */ template <class t_scalar, class brr3> void getUnitNormal(brr3 &u, brr3 &v, brr3 &w){ w[0] = u[1]*v[2] - v[1]*u[2]; w[1] = -u[0]*v[2] + v[0]*u[2]; w[2] = u[0]*v[1] - v[0]*u[1]; t_scalar l; l = sqrt( w[0]*w[0] + w[1]*w[1] + w[2]*w[2] ); for (int i=0; i<3; i++) { w[i] /= l; } } /** calculate the normal vector n to the plane defined by the three points */ template <class t_scalar, class brr3> void getNormal(brr3 &v1, brr3 &v2, brr3 &v3, brr3 &n){ brr3 pl1, pl2; arr3arr3Substract<t_scalar,brr3>(v2, v1, pl1); arr3arr3Substract<t_scalar,brr3>(v3, v1, pl2); getUnitNormal<t_scalar,brr3>(pl1, pl2, n); } /* Given the face formed by tetA[0]:tetA[1]:tetA[2] * get n, the normal to a face pointing inwards. */ template <class t_scalar, class brr3> void getNormalInwards(brr3 (&tetA)[4], int n0, int n1, int n2, brr3 (&n)){ // pl1 and pl2 are the unit vectors (tetA[n1] - tetA[n0]) and (tetA[n2] - tetA[n0]), brr3 pl1, pl2, aux; arr3arr3Substract<t_scalar,brr3>(tetA[n1], tetA[n0], pl1); arr3arr3Substract<t_scalar,brr3>(tetA[n2], tetA[n0], pl2); // n is a unit vector normal to the face: arr3arr3VectorProduct<t_scalar,brr3>(pl1, pl2, aux); arr3Normalise2<t_scalar,brr3>(aux, n); // but it must be inwards, i. e., on the same side of the plane than n3. int n3 = getMissingNode(n0, n1, n2); arr3arr3Add<t_scalar,brr3>(aux, tetA[n0], aux); t_scalar d = - arr3arr3DotProduct<t_scalar,brr3>(n, tetA[n0]); t_scalar t1 = arr3arr3DotProduct<t_scalar,brr3>(tetA[n3], n) + d; t_scalar t2 = arr3arr3DotProduct<t_scalar,brr3>(aux, n) + d; if (!sameSign(t1,t2)) arr3Resize<t_scalar,brr3>(ffea_const::mOne, n); } /** Given the face formed by f0, f1, and f2, * and knowing the remaining p3 for a tetrahedron, * get n, the normal to a face pointing inwards. */ template <class t_scalar, class brr3> void getNormalInwards(brr3 &f0, brr3 &f1, brr3 &f2, brr3 &p3, brr3 (&n)){ // pl1 and pl2 are the unit vectors (tetA[n1] - tetA[n0]) and (tetA[n2] - tetA[n0]), brr3 pl1, pl2, aux; arr3arr3Substract<t_scalar,brr3>(f1, f0, pl1); arr3arr3Substract<t_scalar,brr3>(f2, f0, pl2); // n is a unit vector normal to the face: arr3arr3VectorProduct<t_scalar,brr3>(pl1, pl2, aux); arr3Normalise2<t_scalar,brr3>(aux, n); // but it must be inwards, i. e., on the same side of the plane than n3. arr3arr3Add<t_scalar,brr3>(aux, f0, aux); t_scalar d = - arr3arr3DotProduct<t_scalar,brr3>(n, f0); t_scalar t1 = arr3arr3DotProduct<t_scalar,brr3>(p3, n) + d; t_scalar t2 = arr3arr3DotProduct<t_scalar,brr3>(aux, n) + d; if (!sameSign(t1,t2)) arr3Resize<t_scalar,brr3>(ffea_const::mOne, n); } /** check if points vec and test are at the same side * of the plane formed by p1, p2 and p3 */ template <class t_scalar, class brr3> bool sameSidePlane(brr3 &vec, brr3 &test, brr3 &p1, brr3 &p2, brr3 &p3){ brr3 pl1, pl2, n; arr3arr3Substract<t_scalar,brr3>(p2, p1, pl1); arr3arr3Substract<t_scalar,brr3>(p3, p1, pl2); arr3arr3VectorProduct<t_scalar,brr3>(pl1, pl2, n); arr3Normalise<t_scalar,brr3>(n); t_scalar d = - arr3arr3DotProduct<t_scalar,brr3>(n, p1); t_scalar t1 = arr3arr3DotProduct<t_scalar,brr3>(vec, n) + d; t_scalar t2 = arr3arr3DotProduct<t_scalar,brr3>(test, n) + d; // if ((t1 * t2) >= 0 ) return true; // cout << "t1: " << t1 << " t2: " << t2 << endl; if (sameSign(t1,t2)) return true; else return false; } /** Given 4 co-planar points, check if ip and p1 lay on the same side * of the of the line formed by p2 and p3. * More specifically we check whether pl23 x pl21 and pl23 x pl2e * are parallel or antiparallel. */ template <class t_scalar, class brr3> bool sameSideLine(brr3 &e, brr3 &p1, brr3 &p2, brr3 &p3) { // if (!samePlane(e, p1, p2, p3)) cout << "alarm" << endl; brr3 pl23, pl21, pl2e, v1, ve; arr3arr3Substract<t_scalar,brr3>(p3, p2, pl23); arr3arr3Substract<t_scalar,brr3>(p1, p2, pl21); arr3arr3Substract<t_scalar,brr3>(e, p2, pl2e); arr3arr3VectorProduct<t_scalar,brr3>(pl21, pl23, v1); arr3arr3VectorProduct<t_scalar,brr3>(pl2e, pl23, ve); if (arr3arr3DotProduct<t_scalar,brr3>(v1,ve) >= 0) return true; return false; } /** check whether vector vec is in tetrahedron B. */ /** more specifically, it will be there if * for each plane of the tetrahedron, * the point is on the same side as the remaining vertex */ template <class t_scalar,class brr3> bool nodeInTet(brr3 &vec, brr3 (tet)[4]){ if (!sameSidePlane<t_scalar,brr3>(vec, tet[0], tet[1], tet[2], tet[3])) return false; if (!sameSidePlane<t_scalar,brr3>(vec, tet[1], tet[2], tet[3], tet[0])) return false; if (!sameSidePlane<t_scalar,brr3>(vec, tet[2], tet[3], tet[0], tet[1])) return false; if (!sameSidePlane<t_scalar,brr3>(vec, tet[3], tet[0], tet[1], tet[2])) return false; return true; } template <class t_scalar,class brr3> bool nodeInTet(brr3 &vec, brr3 &tet0, brr3 &tet1, brr3 &tet2, brr3 &tet3){ if (!sameSidePlane<t_scalar,brr3>(vec, tet0, tet1, tet2, tet3)) return false; if (!sameSidePlane<t_scalar,brr3>(vec, tet1, tet2, tet3, tet0)) return false; if (!sameSidePlane<t_scalar,brr3>(vec, tet2, tet3, tet0, tet1)) return false; if (!sameSidePlane<t_scalar,brr3>(vec, tet3, tet0, tet1, tet2)) return false; return true; } /** find the intersection point of the line that passes through the points e1 and e2, * and the plane defined by points p1, p2 and p3. * \warning {this function should be called ONLY in the case * that intersection is known to occur.} */ template <class t_scalar, class brr3> void linePlaneIntersectionPoint(brr3 &ip, brr3 &e1, brr3 &e2, brr3 &p1, brr3 &p2, brr3 &p3) { // v is the vector of the line L(t) = e1 + v*t brr3 v; arr3arr3Substract<t_scalar,brr3>(e2, e1, v); // now we need the unit vector that defines the plane, pn: brr3 pl1, pl2, pn; arr3arr3Substract<t_scalar,brr3>(p2, p1, pl1); arr3arr3Substract<t_scalar,brr3>(p3, p2, pl2); getUnitNormal<t_scalar,brr3>(pl1, pl2, pn); // the plane is defined through: ax + by + cz + d = 0; // (a,b,c) = pn // so to find d we simply: t_scalar d = - arr3arr3DotProduct<t_scalar,brr3>(pn, p1); // now find t and the point: t_scalar t = - (arr3arr3DotProduct<t_scalar,brr3>(pn, e1) + d) / arr3arr3DotProduct<t_scalar,brr3>(pn, v); arr3Resize<t_scalar,brr3>(t, v); arr3arr3Add<t_scalar,brr3>(e1, v, ip); } /** Return true and * the intersection point of the line that passes through the points e1 and e2 * and the plane defined by points p1, p2, p3 if this intersection actually occurs, * and false otherwise. * \warning p1, p2, and p3 are assumed to be non-colinear. */ template <class t_scalar, class brr3> bool safeLinePlaneIntersectionPoint(brr3 &ip, brr3 &e1, brr3 &e2, brr3 &p1, brr3 &p2, brr3 &p3) { // v is the vector of the line L(t) = e1 + v*t brr3 v; arr3arr3Substract<t_scalar,brr3>(e2, e1, v); // now we need the unit vector that defines the plane, pn: brr3 pl1, pl2, pn; arr3arr3Substract<t_scalar,brr3>(p2, p1, pl1); arr3arr3Substract<t_scalar,brr3>(p3, p2, pl2); getUnitNormal<t_scalar,brr3>(pl1, pl2, pn); // CHECK! scalar pnv = arr3arr3DotProduct<t_scalar,brr3>(pn, v); if ( abs(pnv) < ffea_const::threeErr ) return false; // the line won't intersect the plane! // the plane is defined through: ax + by + cz + d = 0; // (a,b,c) = pn // so to find d we simply: t_scalar d = - arr3arr3DotProduct<t_scalar,brr3>(pn, p1); // now find t and the point: t_scalar t = - (arr3arr3DotProduct<t_scalar,brr3>(pn, e1) + d) / arr3arr3DotProduct<t_scalar,brr3>(pn, v); arr3Resize<t_scalar,brr3>(t, v); arr3arr3Add<t_scalar,brr3>(e1, v, ip); return true; } /** Return true and * the intersection point ip of the line that passes through the points e1 and e2 * and face defined by points p1, p2, p3 if this intersection actually occurs, * and false otherwise. * \warning p1, p2, and p3 are assumed to be non-colinear. */ template <class t_scalar,class brr3> bool lineFaceIntersectionPoint(brr3 (&ip), brr3 (&e1), brr3 (&e2), brr3 (&p1), brr3 (&p2), brr3 (&p3)){ // look for the intersection point... if it exists if ( not safeLinePlaneIntersectionPoint<t_scalar,brr3>(ip, e1, e2, p1, p2, p3)) return false; // and finally check whether this point ip belongs to the triangular face: if ( (isPointInFace<t_scalar,brr3>(ip, p1, p2, p3)) ) return true; return false; } /** Check whether point ip is * inside of the three half-planes formed by the triangle's edges p1, p2, p3. */ template <class t_scalar, class brr3> bool isPointInFace(brr3 &ip, brr3 &p1, brr3 &p2, brr3 &p3) { if (! sameSideLine<t_scalar,brr3>(ip, p1, p2, p3) ) return false; if (! sameSideLine<t_scalar,brr3>(ip, p3, p1, p2) ) return false; if (! sameSideLine<t_scalar,brr3>(ip, p2, p3, p1) ) return false; return true; } /** Check whether an edge and a plane intersect, * and return the intersection point ip and true if found, false otherwise. * more specifically check that both: * - both ends of the edge (e1 and e2) are on different sides * of the plane defined by the vectors (tet[f2] - tet[f1]) and (tet[f3] - tet[f1]). * - the intersection of a line is a point in the plane */ // bool intersectionPoint(arr3 &(ip), arr3 (&e1), arr3 (&e2), arr3 (&tet)[4], int f1, int f2, int f3){ template <class t_scalar,class brr3> bool intersectionPoint(brr3 &(ip), brr3 (&e1), brr3 (&e2), brr3 (&tet)[4], int f1, int f2, int f3){ // check it e1 and e2 are on the same side of the plane: if ( sameSidePlane<t_scalar,brr3>(e1, e2, tet[f1], tet[f2], tet[f3]) ) return false; // given that they are on different sides of the plane look for the intersection point. linePlaneIntersectionPoint<t_scalar,brr3>(ip, e1, e2, tet[f1], tet[f2], tet[f3]); // and finally check whether this point ip belongs to the triangular face: if ( (isPointInFace<t_scalar,brr3>(ip, tet[f1], tet[f2], tet[f3])) ) return true; return false; } /** Check whether an edge and a plane intersect, * and return the intersection point ip and true if found, false otherwise. * more specifically check that both: * - both ends of the edge (e1 and e2) are on different sides * of the plane defined by the vectors (f2 - f1) and (f3 - f1). * - the intersection of a line is a point in the plane */ template <class t_scalar,class brr3> bool intersectionPoint(brr3 &ip, brr3 &e1, brr3 &e2, brr3 &f1, brr3 &f2, brr3 &f3){ // check it e1 and e2 are on the same side of the plane: if ( sameSidePlane<t_scalar,brr3>(e1, e2, f1, f2, f3) ) return false; // given that they are on different sides of the plane look for the intersection point. linePlaneIntersectionPoint<t_scalar,brr3>(ip, e1, e2, f1, f2, f3); // and finally check whether this point ip belongs to the triangular face: if ( (isPointInFace<t_scalar,brr3>(ip, f1, f2, f3)) ) return true; return false; } template <class t_scalar, class brr3> void intersectingPointToLine(arr3_view<t_scalar,brr3> p0, arr3_view<t_scalar,brr3> p1, arr3_view<t_scalar,brr3> p2p1, arr3_view<t_scalar,brr3> p3) { brr3 p0p1, cp3p0, v2, v1v2; t_scalar c; arr3arr3Substract<t_scalar,brr3>(p0, p1, p0p1); arr3arr3VectorProduct<t_scalar,brr3>(p0p1, p2p1, v2); // CHECK! if the cross product is null, then distance is zero, and p3 is p0 itself. if (mag<t_scalar,brr3>(v2) < ffea_const::threeErr) { arr3Store(p0, p3); return; } // get cp3p0, the vector to (or from) to the line p2p1: arr3arr3VectorProduct<t_scalar,brr3>(p2p1, v2, cp3p0); // now calculate c, the amount of cp3p0 from p0 to the intersection point p3. arr3arr3VectorProduct<t_scalar,brr3>(p2p1, cp3p0, v1v2); c = detByRows<t_scalar, brr3>(p0p1, p2p1, v1v2); c /= ( v1v2[0]*v1v2[0] + v1v2[1]*v1v2[1] + v1v2[2]*v1v2[2]); // and finally calculate the intersection point: arr3Resize<t_scalar,brr3>(c, cp3p0); arr3arr3Add<t_scalar,brr3>(p0, cp3p0, p3); /* // CHECKS START HERE! // brr3 p3p0; arr3arr3Substract<t_scalar,brr3>(p3, p0, p3p0); c = mag<t_scalar,brr3>(p3p0); // check the distance: t_scalar d = distanceFromPointToLine<t_scalar, brr3>(p0, p1, p2); if (abs (d - abs(c)) > ffea_const::threeErr) { cout << "something is wrong: d = " << d << " differs from c = " << c << endl; } */ return; } template <class t_scalar, class brr3> void intersectingPointToLine(vector3 &p0, arr3_view<t_scalar,brr3> p1, arr3_view<t_scalar,brr3> p2p1, arr3_view<t_scalar,brr3> p3) { brr3 p0p1, cp3p0, v2, v1v2; t_scalar c; // arr3arr3Substract<t_scalar,brr3>(p2, p1, p2p1); // arr3arr3Substract<t_scalar,brr3>(p0, p1, p0p1); p0p1[0] = p0.x - p1[0]; p0p1[1] = p0.y - p1[1]; p0p1[2] = p0.z - p1[2]; arr3arr3VectorProduct<t_scalar,brr3>(p0p1, p2p1, v2); // CHECK! if the cross product is null, then distance is zero, and p3 is p0 itself. if (mag<t_scalar,brr3>(v2) < ffea_const::threeErr) { // arr3Store(p0, p3); p3[0] = p0.x; p3[1] = p0.y; p3[2] = p0.z; return; } // get cp3p0, the vector to (or from) to the line p2p1: arr3arr3VectorProduct<t_scalar,brr3>(p2p1, v2, cp3p0); // now calculate c, the amount of cp3p0 from p0 to the intersection point p3. arr3arr3VectorProduct<t_scalar,brr3>(p2p1, cp3p0, v1v2); c = detByRows<t_scalar, brr3>(p0p1, p2p1, v1v2); c /= ( v1v2[0]*v1v2[0] + v1v2[1]*v1v2[1] + v1v2[2]*v1v2[2]); // and finally calculate the intersection point: arr3Resize<t_scalar,brr3>(c, cp3p0); p3[0] = p0.x + cp3p0[0]; p3[1] = p0.y + cp3p0[1]; p3[2] = p0.z + cp3p0[2]; /* // CHECKS START HERE! // brr3 p3p0; arr3arr3Substract<t_scalar,brr3>(p3, p0, p3p0); c = mag<t_scalar,brr3>(p3p0); // check the distance: t_scalar d = distanceFromPointToLine<t_scalar, brr3>(p0, p1, p2); if (abs (d - c) > ffea_const::threeErr) { cout << "something is wrong: d = " << d << " differs from c = " << c << endl; } */ return; } template <class t_scalar, class brr3> t_scalar distanceFromPointToLine(arr3_view<t_scalar,brr3> p0, arr3_view<t_scalar,brr3> p1, arr3_view<t_scalar,brr3> p2) { brr3 p2p1, p0p1, p0p2, tmp1; arr3arr3Substract<t_scalar,brr3>(p2, p1, p2p1); arr3arr3Substract<t_scalar,brr3>(p0, p2, p0p2); arr3arr3Substract<t_scalar,brr3>(p0, p1, p0p1); arr3arr3VectorProduct<t_scalar,brr3>(p0p1, p0p2, tmp1); scalar d = mag<t_scalar,brr3>(tmp1) / mag<t_scalar,brr3>(p2p1); return d; } /* template <class t_scalar, class brr3> t_scalar getTetrahedraVolume(arr3_view<t_scalar,brr3> p0, arr3_view<t_scalar,brr3> p1, arr3_view<t_scalar,brr3> p2, arr3_view<t_scalar,brr3> p3){ scalar v = 0; v += detByCols<scalar,arr3>(p1, p2, p3); v -= detByCols<scalar,arr3>(p0, p2, p3); v += detByCols<scalar,arr3>(p0, p1, p3); v -= detByCols<scalar,arr3>(p0, p1, p2); return v/6.; }*/ template <class t_scalar, class brr3> t_scalar getTetrahedraVolume(arr3_view<t_scalar,brr3> p0, arr3_view<t_scalar,brr3> p1, arr3_view<t_scalar,brr3> p2, arr3_view<t_scalar,brr3> p3){ return (p1[0] - p0[0])*( (p1[1] - p2[1])*(p2[2] - p3[2]) - (p2[1] - p3[1])*(p1[2] - p2[2]) ) + (p2[0] - p1[0])*( (p2[1] - p3[1])*(p0[2] - p1[2]) - (p0[1] - p1[1])*(p2[2] - p3[2]) ) + (p3[0] - p2[0])*( (p0[1] - p1[1])*(p1[2] - p2[2]) - (p1[1] - p2[1])*(p0[2] - p1[2]) ); } template <class brr3> void getTetrahedraCM(brr3 &p1, brr3 &p2, brr3 &p3, brr3 &p4, brr3 &c){ for (int i=0; i<3; i++){ c[i] = 0.25 * (p1[i] + p2[i] + p3[i] + p4[i]); } } template <class t_scalar, class brr3, class brr4> void getLocalCoordinatesForLinTet(arr3_view<t_scalar,brr3> t0, arr3_view<t_scalar,brr3> t1, arr3_view<t_scalar,brr3> t2, arr3_view<t_scalar,brr3> t3, arr3_view<t_scalar,brr3> p, brr4 &phi){ phi[0] = getTetrahedraVolume(p, t1, t2, t3); phi[1] = - getTetrahedraVolume(p, t0, t2, t3); phi[2] = getTetrahedraVolume(p, t0, t1, t3); phi[3] = - getTetrahedraVolume(p, t0, t1, t2); t_scalar v = getTetrahedraVolume(t0, t1, t2, t3); for (int i=0; i<4; i++) { phi[i] /= v; } /* // CHECK!! for the time: arr3 tmp, pc; arr3Initialise<arr3>(pc); // WT*? arr3Resize2<scalar,arr3>(phi[0], t0, tmp); arr3arr3Add<scalar,arr3>(pc, tmp, pc); arr3Resize2<scalar,arr3>(phi[1], t1, tmp); arr3arr3Add<scalar,arr3>(pc, tmp, pc); arr3Resize2<scalar,arr3>(phi[2], t2, tmp); arr3arr3Add<scalar,arr3>(pc, tmp, pc); arr3Resize2<scalar,arr3>(phi[3], t3, tmp); arr3arr3Add<scalar,arr3>(pc, tmp, pc); arr3arr3Substract<scalar,arr3>(p, pc, tmp); if (mag<scalar,arr3>(tmp) > 1e-6) { cout << "local coordinates were not correctly calculated!" << endl; cout << "p: " << p[0] << ", " << p[1] << ", " << p[2] << endl; cout << "pc: " << pc[0] << ", " << pc[1] << ", " << pc[2] << endl; cout << "diff: " << mag<scalar,arr3>(tmp) << endl; } */ } //////////////////////////////////////////////// ////////////// END OF SECTION 2 //////////////// //////////////////////////////////////////////// ///////////////// SECTION 3 //////////////////// /// Transition functions from vector3 to arr3 // //////////////////////////////////////////////// template <class brr3> void vec3Vec3SubsToArr3(vector3 &u, vector3 &v, brr3 (&w)){ w[0] = u.x - v.x; w[1] = u.y - v.y; w[2] = u.z - v.z; } void vec3Arr3SubsToArr3(vector3 &u, arr3 (&v), arr3 (&w)){ w[0] = u.x - v[0]; w[1] = u.y - v[1]; w[2] = u.z - v[2]; } void arr3Vec3SubsToArr3(arr3 (&u), vector3 &v, arr3 (&w)){ w[0] = u[0] - v.x; w[1] = u[1] - v.y; w[2] = u[2] - v.z; } void vec3Arr3AddToArr3(vector3 &u, arr3 (&v), arr3 (&w)){ w[0] = u.x + v[0]; w[1] = u.y + v[1]; w[2] = u.z + v[2]; } void vec3ResizeToArr3(scalar f, vector3 &u, arr3 (&v)){ v[0] = f*u.x; v[1] = f*u.y; v[2] = f*u.z; } scalar vec3Arr3DotProduct(vector3 &u, arr3 &v) { scalar s; s = u.x * v[0]; s += u.y * v[1]; s += u.z * v[2]; return s; } //////////////////////////////////////////////// ////////////// END OF SECTION 3 //////////////// //////////////////////////////////////////////// ///////////////// SECTION 4 //////////////////// // // // // Instantiate templates // // // // // //////////////////////////////////////////////// template bool sameSign<scalar>(scalar a, scalar b); template void arr3arr3Add<scalar, arr3>(arr3_view<scalar,arr3> vecA, arr3_view<scalar,arr3> vecB, arr3_view<scalar,arr3> res); template void arr3arr3Substract<scalar,arr3>(arr3_view<scalar,arr3> vecA, arr3_view<scalar,arr3> vecB, arr3_view<scalar,arr3> res); template void arr3arr3VectorProduct<scalar,arr3>(arr3_view<scalar,arr3> u, arr3_view<scalar,arr3> v, arr3_view<scalar,arr3> w); template scalar arr3arr3DotProduct<scalar,arr3>(arr3_view<scalar,arr3> vecA, arr3_view<scalar,arr3> vecB); template void arr3Normalise<scalar,arr3>(arr3_view<scalar,arr3> e); template void arr3Normalise2<scalar,arr3>(arr3_view<scalar,arr3> e, arr3_view<scalar,arr3> n); template void arr3Resize<scalar,arr3>(scalar f, arr3_view<scalar,arr3> u); template void arr3Resize2<scalar,arr3> (scalar f, arr3_view<scalar,arr3> u, arr3_view<scalar,arr3> v); template void arr3Resize3<scalar,arr3> (scalar f, arr3_view<scalar,arr3> u, arr3_view<scalar,arr3> v); template void arr3Store<scalar,arr3>(arr3_view<scalar,arr3> u, arr3_view<scalar,arr3> v); template scalar arr3arr3Distance<scalar,arr3>(arr3_view<scalar,arr3> vecA, arr3_view<scalar,arr3> vecB); template scalar mag<scalar,arr3>(arr3_view<scalar,arr3> v); template scalar mag2<scalar,arr3>(arr3_view<scalar,arr3> v); template void arr3Initialise<arr3>(arr3 &v); template scalar detByRows<scalar,arr3>(arr3_view<scalar,arr3> a, arr3_view<scalar,arr3> b, arr3_view<scalar,arr3> c); template scalar detByCols<scalar,arr3>(arr3_view<scalar,arr3> a, arr3_view<scalar,arr3> b, arr3_view<scalar,arr3> c); #ifndef USE_DOUBLE template bool sameSign<geoscalar>(geoscalar a, geoscalar b); template void arr3arr3Add<geoscalar, grr3>(arr3_view<geoscalar,grr3> vecA, arr3_view<geoscalar,grr3> vecB, arr3_view<geoscalar,grr3> res); template void arr3arr3Substract<geoscalar,grr3>(arr3_view<geoscalar,grr3> vecA, arr3_view<geoscalar,grr3> vecB, arr3_view<geoscalar,grr3> res); template void arr3arr3VectorProduct<geoscalar,grr3>(arr3_view<geoscalar,grr3> u, arr3_view<geoscalar,grr3> v, arr3_view<geoscalar,grr3> w); template geoscalar arr3arr3DotProduct<geoscalar,grr3>(arr3_view<geoscalar,grr3> vecA, arr3_view<geoscalar,grr3> vecB); template void arr3Normalise<geoscalar,grr3>(arr3_view<geoscalar,grr3> e); template void arr3Normalise2<geoscalar,grr3>(arr3_view<geoscalar,grr3> e, arr3_view<geoscalar,grr3> n); template void arr3Resize<geoscalar,grr3>(geoscalar f, arr3_view<geoscalar,grr3> u); template void arr3Resize2<geoscalar,grr3> (geoscalar f, arr3_view<geoscalar,grr3> u, arr3_view<geoscalar,grr3> v); template void arr3Resize3<geoscalar,grr3> (geoscalar f, arr3_view<geoscalar,grr3> u, arr3_view<geoscalar,grr3> v); template void arr3Store<geoscalar,grr3>(arr3_view<geoscalar,grr3> u, arr3_view<geoscalar,grr3> v); template geoscalar arr3arr3Distance<geoscalar,grr3>(arr3_view<geoscalar,grr3> vecA, arr3_view<geoscalar,grr3> vecB); template geoscalar mag<geoscalar,grr3>(arr3_view<geoscalar,grr3> v); template geoscalar mag2<geoscalar,grr3>(arr3_view<geoscalar,grr3> v); template void arr3Initialise<grr3>(grr3 &v); template geoscalar detByRows<geoscalar,grr3>(arr3_view<geoscalar,grr3> a, arr3_view<geoscalar,grr3> b, arr3_view<geoscalar,grr3> c); template geoscalar detByCols<geoscalar,grr3>(arr3_view<geoscalar,grr3> a, arr3_view<geoscalar,grr3> b, arr3_view<geoscalar,grr3> c); #endif template void tangent<scalar,arr3>(arr3 &vecA, arr3 &vecB, arr3 &t); template void getUnitNormal<scalar,arr3>(arr3 &u, arr3 &v, arr3 &w); template void getNormal<scalar,arr3>(arr3 &v1, arr3 &v2, arr3 &v3, arr3 &n); template void getNormalInwards<scalar,arr3>(arr3 (&tetA)[4], int n0, int n1, int n2, arr3 (&n)); template void getNormalInwards<scalar,arr3>(arr3 &f0, arr3 &f1, arr3 &f2, arr3 &p3, arr3 (&n)); template bool sameSidePlane<scalar,arr3>(arr3 &vec, arr3 &test, arr3 &p1, arr3 &p2, arr3 &p3); template bool sameSideLine<scalar,arr3>(arr3 &e, arr3 &p1, arr3 &p2, arr3 &p3); template bool nodeInTet<scalar,arr3>(arr3 &vec, arr3 (tet)[4]); template bool nodeInTet<scalar,grr3>(arr3 &vec, arr3 &tet0, arr3 &tet1, arr3 &tet2, arr3 &tet3); template void linePlaneIntersectionPoint<scalar,arr3>(arr3 &ip, arr3 &e1, arr3 &e2, arr3 &p1, arr3 &p2, arr3 &p3); template bool safeLinePlaneIntersectionPoint<scalar,arr3>(arr3 &ip, arr3 &e1, arr3 &e2, arr3 &p1, arr3 &p2, arr3 &p3); template bool lineFaceIntersectionPoint<scalar,arr3>(arr3 (&ip), arr3 (&e1), arr3 (&e2), arr3 (&p1), arr3 (&p2), arr3 (&p3)); template bool isPointInFace<scalar,arr3>(arr3 &ip, arr3 &p1, arr3 &p2, arr3 &p3); template bool intersectionPoint<scalar,arr3>(arr3 &(ip), arr3 (&e1), arr3 (&e2), arr3 (&tet)[4], int f1, int f2, int f3); template bool intersectionPoint<scalar,arr3>(arr3 &ip, arr3 &e1, arr3 &e2, arr3 &f1, arr3 &f2, arr3 &f3); // template void intersectingPointToLine<scalar, arr3>(arr3 &p0, arr3 &p1, arr3 &p2, arr3 &p3); template void intersectingPointToLine<scalar, arr3>(arr3_view<scalar, arr3> p0, arr3_view<scalar,arr3> p1, arr3_view<scalar,arr3> p2p1, arr3_view<scalar,arr3> p3); template void intersectingPointToLine<scalar, arr3>(vector3 &p0, arr3_view<scalar,arr3> p1, arr3_view<scalar,arr3> p2p1, arr3_view<scalar,arr3> p3); template scalar distanceFromPointToLine<scalar,arr3>(arr3_view<scalar, arr3> p0, arr3_view<scalar, arr3> p1, arr3_view<scalar, arr3> p2); template scalar getTetrahedraVolume<scalar,arr3>(arr3_view<scalar,arr3> p0, arr3_view<scalar,arr3> p1, arr3_view<scalar,arr3> p2, arr3_view<scalar,arr3> p3); template void getTetrahedraCM<arr3>(arr3 &p1, arr3 &p2, arr3 &p3, arr3 &p4, arr3 &c); template void getLocalCoordinatesForLinTet<scalar,arr3,arr4>(arr3_view<scalar,arr3> t0, arr3_view<scalar,arr3> t1, arr3_view<scalar,arr3> t2, arr3_view<scalar,arr3> t3, arr3_view<scalar,arr3> p, arr4 &phi); ////////////// template void vec3Vec3SubsToArr3<arr3>(vector3 &u, vector3 &v, arr3 (&w)); #ifndef USE_DOUBLE template void tangent<geoscalar,grr3>(grr3 &vecA, grr3 &vecB, grr3 &t); template void getUnitNormal<geoscalar,grr3>(grr3 &u, grr3 &v, grr3 &w); template void getNormal<geoscalar,grr3>(grr3 &v1, grr3 &v2, grr3 &v3, grr3 &n); template void getNormalInwards<geoscalar,grr3>(grr3 (&tetA)[4], int n0, int n1, int n2, grr3 (&n)); template void getNormalInwards<geoscalar,grr3>(grr3 &f0, grr3 &f1, grr3 &f2, grr3 &p3, grr3 (&n)); template bool sameSidePlane<geoscalar,grr3>(grr3 &vec, grr3 &test, grr3 &p1, grr3 &p2, grr3 &p3); template bool sameSideLine<geoscalar,grr3>(grr3 &e, grr3 &p1, grr3 &p2, grr3 &p3); template bool nodeInTet<geoscalar,grr3>(grr3 &vec, grr3 (tet)[4]); template bool nodeInTet<geoscalar,grr3>(grr3 &vec, grr3 &tet0, grr3 &tet1, grr3 &tet2, grr3 &tet3); template void linePlaneIntersectionPoint<geoscalar,grr3>(grr3 &ip, grr3 &e1, grr3 &e2, grr3 &p1, grr3 &p2, grr3 &p3); template bool safeLinePlaneIntersectionPoint<geoscalar,grr3>(grr3 &ip, grr3 &e1, grr3 &e2, grr3 &p1, grr3 &p2, grr3 &p3); template bool lineFaceIntersectionPoint<geoscalar,grr3>(grr3 (&ip), grr3 (&e1), grr3 (&e2), grr3 (&p1), grr3 (&p2), grr3 (&p3)); template bool isPointInFace<geoscalar,grr3>(grr3 &ip, grr3 &p1, grr3 &p2, grr3 &p3); template bool intersectionPoint<geoscalar,grr3>(grr3 &(ip), grr3 (&e1), grr3 (&e2), grr3 (&tet)[4], int f1, int f2, int f3); template bool intersectionPoint<geoscalar,grr3>(grr3 &ip, grr3 &e1, grr3 &e2, grr3 &f1, grr3 &f2, grr3 &f3); template void intersectingPointToLine<geoscalar, grr3>(arr3_view<geoscalar, grr3> p0, arr3_view<geoscalar,grr3> p1, arr3_view<geoscalar,grr3> p2p1, arr3_view<geoscalar,grr3> p3); template void intersectingPointToLine<geoscalar, grr3>(vector3 &p0, arr3_view<geoscalar,grr3> p1, arr3_view<geoscalar,grr3> p2p1, arr3_view<geoscalar,grr3> p3); template geoscalar distanceFromPointToLine<geoscalar,grr3>(arr3_view<geoscalar, grr3> p0, arr3_view<geoscalar, grr3> p1, arr3_view<geoscalar, grr3> p2); template geoscalar getTetrahedraVolume<geoscalar,grr3>(arr3_view<geoscalar,grr3> p0, arr3_view<geoscalar,grr3> p1, arr3_view<geoscalar,grr3> p2, arr3_view<geoscalar,grr3> p3); template void getTetrahedraCM<grr3>(grr3 &p1, grr3 &p2, grr3 &p3, grr3 &p4, grr3 &c); template void getLocalCoordinatesForLinTet<geoscalar,grr3,grr4>(arr3_view<geoscalar,grr3> t0, arr3_view<geoscalar,grr3> t1, arr3_view<geoscalar,grr3> t2, arr3_view<geoscalar,grr3> t3, arr3_view<geoscalar,grr3> p, grr4 &phi); template void vec3Vec3SubsToArr3<grr3>(vector3 &u, vector3 &v, grr3 (&w)); #endif
36.843096
239
0.640622
493a4227a94f21bab9b11ee133da6af36d8f41a0
66,031
cpp
C++
FrameWorkCode/slpNPatternDict.cpp
ayushbits/udaan-post-editing
499303a641598978d89cf0210776e80d98d2212a
[ "BSD-3-Clause" ]
1
2022-01-25T19:27:55.000Z
2022-01-25T19:27:55.000Z
FrameWorkCode/slpNPatternDict.cpp
ayushbits/udaan-post-editing
499303a641598978d89cf0210776e80d98d2212a
[ "BSD-3-Clause" ]
null
null
null
FrameWorkCode/slpNPatternDict.cpp
ayushbits/udaan-post-editing
499303a641598978d89cf0210776e80d98d2212a
[ "BSD-3-Clause" ]
null
null
null
#include <string> #include <sstream> #include <fstream> #include <iostream> #include <map> #include <set> #include <vector> #include <algorithm> #include <iterator> #include <vector> #include <QMessageBox> #include <iostream> #include "qdebug.h" #include "qtextstream.h" #include <cassert> #include <cmath> #include <string> #include <unordered_map> #include <QFile> #include "eddis.h" #include "slpNPatternDict.h" //#include <boost/serialization/map.hpp> //#include <boost/serialization/vector.hpp> //#include <boost/serialization/serialization.hpp> //#include <boost/serialization/unordered_map.hpp> //#include <boost/archive/text_iarchive.hpp> //#include <boost/archive/text_oarchive.hpp> //#include "toFromslp1.h" using namespace std; bool HinFlag = 0, SanFlag = 1; string slpNPatternDict :: ReplaceString(string subject, const string& search, const string& replace) { size_t pos=0; while((pos=subject.find(search, pos)) != string::npos) { subject.replace(pos, search.length(),replace); pos+=1; } return subject; } string slpNPatternDict :: ReplaceStringRestricted(string subject, const string& search, const string& replace) { size_t pos=0; char c; string replace_new=replace+"a"; // replace_new=replace_new+m; //cout<<"here "<<subject<<endl; while((pos=subject.find(search, pos)) != string::npos) { if(pos == subject.size()) break; //cout << subject<< " "<<pos <<" "<<subject.size()<< endl; if( subject.size() == pos + 3) c=subject.at(pos+2); else c=subject.at(pos+3); //CHANGE TO 3 IF EVERYTHING DOES NOT WORK if(c=='A' || c=='i' || c=='I' || c=='u' || c=='U' || c=='f' || c=='F' || c=='x' || c=='X' || c=='e' || c=='E' || c=='o' || c=='O') subject.replace(pos, search.length(),replace); else subject.replace(pos, search.length(),replace_new); pos+=1; } //cout<<"here21 "<<subject<<endl; return subject; } void slpNPatternDict :: loadFileCSV(map<string, vector<int>>& synonym, vector<vector<string>>& synrows, const string filename){ QString fn = QString::fromStdString(filename); QFile file(fn); if (!file.open(QIODevice::ReadOnly)) { qDebug() << file.errorString(); return; } QTextStream in(&file); QStringList wordList; int j = 0; while (!in.atEnd()) { QString line = in.readLine(); QList<QString> L = line.split(','); qDebug() << L.first() << endl; vector<string> V; synrows.push_back(V); for(int i=0 ; i < L.size(); i++){ string S = L[i].toUtf8().constData(); if(S != "" && j){ S.erase(remove(S.begin(), S.end(), ' '), S.end()); if(S.substr(0, 1) == "\""){ S = S.substr(1, S.size()-1); } if(S.substr(S.size()-1, 1) == "\""){ S = S.substr(0, S.size()-1); } cout << S << endl; synrows[j].push_back(S); synonym[S].push_back(j); } } cout << j << endl; j++; } } string slpNPatternDict :: toDev(string s) { //Hin:- if (HinFlag){ string vowel_dn[]={"अ","आ","इ","ई","उ","ऊ","ऋ","ए","ऐ","ओ","औ","ऑ","ं","ः","ँ","ॅ"}; string vowel_dn_joiner[]={"","ा","ि","ी","ु","ू","ृ","े","ै","ो","ौ","ॉ"}; string vowel_slp1[]={"a","A","i","I","u","U","f","e","E","o","O","Z","M","H","~","*"}; string consonants_dn[]={"क","ख","ग","घ","ङ","च","छ","ज","झ","ञ","ट","ठ","ड","ढ","ण","त","थ","द","ध","न","प","फ","ब","भ","म","य","र","ल","व","श","ष","स","ह","क़","ख़","ग़","ज़","ड़","ढ़","ऩ","फ़","य़","ऱ","ळ"}; string consonants_dn_halanta[]={"क्","ख्","ग्","घ्","ङ्","च्","छ्","ज्","झ्","ञ्","ट्","ठ्","ड्","ढ्","ण्","त्","थ्","द्","ध्","न्","प्","फ्","ब्","भ्","म्","य्","र्","ल्","व्","श्","ष्","स्","ह्","क़्","ख़्","ग़्","ज़्","ड़्","ढ़्","ऩ्","फ़्","य़्","ऱ्","ळ्"}; string consonants_slp1[]={"k","K","g","G","N","c","C","j","J","Y","w","W","q","Q","R","t","T","d","D","n","p","P","b","B","m","y","r","l","v","S","z","s","h","@","#","$","F","x","X","%","^","&","V","L"}; string no_dn[]={"०","१","२","३","४","५","६","७","८","९","॥","।","–","—"}; string no_slp1[]={"0","1","2","3","4","5","6","7","8","9","||","|","-","-"}; for(int i=0;i<44;i++) { s=ReplaceString(s,consonants_slp1[i],consonants_dn_halanta[i]); } for(int i=0;i<12;i++) { s=ReplaceString(s,"्"+vowel_slp1[i],vowel_dn_joiner[i]); } for(int i=0;i<16;i++) { s=ReplaceString(s,vowel_slp1[i],vowel_dn[i]); } for(int i=0;i<13;i++) { s=ReplaceString(s,no_slp1[i],no_dn[i]); } } else if(SanFlag ){ string vowel_dn[]={"अ","आ","इ","ई","उ","ऊ","ऋ","ॠ","ऌ","ॡ","ए","ऐ","ओ","औ","ं","ः","ँ","ᳲ","ᳳ","ऽ","ॐ"}; string vowel_dn_joiner[]={"","ा","ि","ी","ु","ू","ृ","ॄ","ॢ","ॣ","े","ै","ो","ौ"}; //string consonants_dn[]={"क","ख","ग","घ","ङ","च","छ","ज","झ","ञ","ट","ठ","ड","ढ","ण","त","थ","द","ध","न","प","फ","ब","भ","म","य","र","ल","व","श","ष","स","ह","ळ"}; string consonants_dn_halanta[]={"क्","ख्","ग्","घ्","ङ्","च्","छ्","ज्","झ्","ञ्","ट्","ठ्","ड्","ढ्","ण्","त्","थ्","द्","ध्","न्","प्","फ्","ब्","भ्","म्","य्","र्","ल्","व्","श्","ष्","स्","ह्","ळ्"}; string vowel_slp1[]={"a","A","i","I","u","U","f","F","x","X","e","E","o","O","M","H","~","Z","V","$","%"}; string consonants_slp1[]={"k","K","g","G","N","c","C","j","J","Y","w","W","q","Q","R","t","T","d","D","n","p","P","b","B","m","y","r","l","v","S","z","s","h","L"}; string numbers_etc_dn[]={"॥","।","॰","ऽ","‘","’","“","”","ॐ","१","२","३","४","५","६","७","८","९","०"}; string numbers_eng[]={"||","|","^0","$","-'","'","-\"","\"","%","1","2","3","4","5","6","7","8","9","0"}; for(int i=0;i<34;i++) { s=ReplaceString(s,consonants_slp1[i],consonants_dn_halanta[i]); } //cout << "here1 " << s <<endl; for(int i=0;i<14;i++) { s=ReplaceString(s,"्"+vowel_slp1[i],vowel_dn_joiner[i]); } //cout << "here2 " << s <<endl; for(int i=0;i<21;i++) { s=ReplaceString(s,vowel_slp1[i],vowel_dn[i]); } //cout << "here3 " << s <<endl; for(unsigned int i=0;i<(sizeof(numbers_etc_dn)/sizeof(numbers_etc_dn[0]));i++) { s=ReplaceString(s,numbers_eng[i],numbers_etc_dn[i]); } //cout << "here3 " << s <<endl; //cout<<s<<endl; } return s; } string slpNPatternDict :: toslp1(string s) { //Hin:- if (HinFlag){ string vowel_dn[]={"अ","आ","इ","ई","उ","ऊ","ऋ","ए","ऐ","ओ","औ","ऑ","ं","ः","ँ","ॅ"}; string vowel_dn_joiner[]={"ा","ि","ी","ु","ू","ृ","े","ै","ो","ौ","ॉ"}; string vowel_slp1[]={"a","A","i","I","u","U","f","e","E","o","O","Z","M","H","*","~"}; string consonants_dn[]={"क","ख","ग","घ","ङ","च","छ","ज","झ","ञ","ट","ठ","ड","ढ","ण","त","थ","द","ध","न","प","फ","ब","भ","म","य","र","ल","व","श","ष","स","ह","क़","ख़","ग़","ज़","ड़","ढ़","ऩ","फ़","य़","ऱ","ळ"}; string consonants_dn_halanta[]={"क्","ख्","ग्","घ्","ङ्","च्","छ्","ज्","झ्","ञ्","ट्","ठ्","ड्","ढ्","ण्","त्","थ्","द्","ध्","न्","प्","फ्","ब्","भ्","म्","य्","र्","ल्","व्","श्","ष्","स्","ह्","क़्","ख़्","ग़्","ज़्","ड़्","ढ़्","ऩ्","फ़्","य़्","ऱ्","ळ्"}; string consonants_slp1[]={"k","K","g","G","N","c","C","j","J","Y","w","W","q","Q","R","t","T","d","D","n","p","P","b","B","m","y","r","l","v","S","z","s","h","@","#","$","F","x","X","%","^","&","V","L"}; string no_dn[]={"०","१","२","३","४","५","६","७","८","९","॥","।","–","—"}; string no_slp1[]={"0","1","2","3","4","5","6","7","8","9","||","|","-","-"}; for(int i=0;i<44;i++) { s=ReplaceString(s,consonants_dn_halanta[i],consonants_slp1[i]); } for(int i=0;i<11;i++) { s=ReplaceString(s,vowel_dn_joiner[i],vowel_slp1[i+1]); } for(int i=0;i<16;i++) { s=ReplaceString(s,vowel_dn[i],vowel_slp1[i]); } for(int i=0;i<43;i++) { s=ReplaceStringRestricted(s,consonants_dn[i],consonants_slp1[i]); } for(int i=0;i<14;i++) { s=ReplaceString(s,no_dn[i],no_slp1[i]); } } else if(SanFlag){ //San:- string vowel_dn[]={"अ","आ","इ","ई","उ","ऊ","ऋ","ॠ","ऌ","ॡ","ए","ऐ","ओ","औ","ं","ः","ँ","ᳲ","ᳳ"}; string vowel_dn_joiner[]={"ा","ि","ी","ु","ू","ृ","ॄ","ॢ","ॣ","े","ै","ो","ौ"}; string consonants_dn[]={"क","ख","ग","घ","ङ","च","छ","ज","झ","ञ","ट","ठ","ड","ढ","ण","त","थ","द","ध","न","प","फ","ब","भ","म","य","र","ल","व","श","ष","स","ह","ळ"}; string consonants_dn_halanta[]={"क्","ख्","ग्","घ्","ङ्","च्","छ्","ज्","झ्","ञ्","ट्","ठ्","ड्","ढ्","ण्","त्","थ्","द्","ध्","न्","प्","फ्","ब्","भ्","म्","य्","र्","ल्","व्","श्","ष्","स्","ह्","ळ्"}; string vowel_slp1[]={"a","A","i","I","u","U","f","F","x","X","e","E","o","O","M","H","~","Z","V"}; string consonants_slp1[]={"k","K","g","G","N","c","C","j","J","Y","w","W","q","Q","R","t","T","d","D","n","p","P","b","B","m","y","r","l","v","S","z","s","h","L"}; //cout<<s<<endl; size_t pos = 0; while((pos=s.find("ॆ", pos)) != string::npos) s.replace(pos, 3,"े"); pos = 0; while((pos=s.find("ऎ", pos)) != string::npos) s.replace(pos, 3,"एे"); size_t pos1 = 0; while((pos1=s.find("ॊ", pos1)) != string::npos) s.replace(pos1, 3,"ो"); //cout<<s<<endl; pos1 = 0; //cout<<s<<" "<<s.find("ऴ्", pos1)<<endl; while((pos1=s.find("ऴ्", pos1)) != string::npos)//"ळ" is valid, dot below "ळ" is invalid char {s.replace(pos1, 6,"ळ्"); } //cout<<s<<endl; pos1 = 0; //cout<<s<<" "<<s.find("ऴ", pos1)<<endl; while((pos1=s.find("ऴ", pos1)) != string::npos)//"ळ" is valid, dot below "ळ" is invalid char {s.replace(pos1, 6,"ळ"); } //cout<<s<<endl; for(int i=0;i<34;i++) { s=ReplaceString(s,consonants_dn_halanta[i],consonants_slp1[i]); } for(int i=0;i<13;i++) { s=ReplaceString(s,vowel_dn_joiner[i],vowel_slp1[i+1]); } for(int i=0;i<19;i++) { s=ReplaceString(s,vowel_dn[i],vowel_slp1[i]); } //cout<<"here "<< s<<endl; for(int i=0;i<34;i++) { //cout<< i << " " << consonants_dn[i] << " " << consonants_slp1[i] << endl; s=ReplaceStringRestricted(s,consonants_dn[i],consonants_slp1[i]); } //cout<<"here1 "<< s<<endl; //cout<<s<<"…"<<s.find("…", pos1)<<endl; string numbers_etc_dn[]={"॥","।","॰","ऽ","‘","’","“","”","ॐ","१","२","३","४","५","६","७","८","९","०"}; string numbers_eng[]={"||","|","^0","$","-'","'","-\"","\"","%","1","2","3","4","5","6","7","8","9","0"}; for(uint i=0;i<(sizeof(numbers_etc_dn)/sizeof(numbers_etc_dn[0]));i++) { s=ReplaceString(s,numbers_etc_dn[i],numbers_eng[i]); } } //ifSanflag over return s; } void slpNPatternDict :: printmapinDev(map<string,int> m1){ /*std::ofstream ss1("ppi.bin"); boost::archive::text_oarchive oarch1(ss1); oarch1 << PatWInst;*/ for( map<string,int>::const_iterator eptr=m1.begin(); eptr!=m1.end(); eptr++) cout << toDev(eptr->first) << endl; } void slpNPatternDict :: printmap(map<string,int>& m1){ /*std::ofstream ss1("ppi.bin"); boost::archive::text_oarchive oarch1(ss1); oarch1 << PatWInst;*/ for( map<string,int>::const_iterator eptr=m1.begin(); eptr!=m1.end(); eptr++) cout << (eptr->first) << endl; } void slpNPatternDict :: printmapstrstr(map<string,string>& m1){ /*std::ofstream ss1("ppi.bin"); boost::archive::text_oarchive oarch1(ss1); oarch1 << PatWInst;*/ for( map<string,string>::const_iterator eptr=m1.begin(); eptr!=m1.end(); eptr++) cout << (eptr->first) << " " <<(eptr->second) << endl; } void slpNPatternDict :: printmapWFreq(map<string,int>& m1){ /*std::ofstream ss1("ppi.bin"); boost::archive::text_oarchive oarch1(ss1); oarch1 << PatWInst;*/ for( map<string,int>::const_iterator eptr=m1.begin(); eptr!=m1.end(); eptr++) cout << (eptr->first) << " " <<(eptr->second) << endl; } void slpNPatternDict :: loadCwordsPair(string wordL,string wordR, map<string, string>& CPair,map<string,int>& Dict,map<string,int>& PWords){ if ((Dict[wordL] ==0) && (PWords[wordL] == 0)) CPair[wordL] = wordR; } void loadCPair(string filename, map<string, string>& CPair,map<string,int>& Dict, map<string,int>& PWords){ ifstream myfile(filename); slpNPatternDict slnp; if (myfile.is_open()) { string str1, str2; while (myfile >> str1 ) {myfile >> str2; slnp.loadCwordsPair(slnp.toslp1(str1),slnp.toslp1(str2),CPair,Dict,PWords);} cout <<"CPairs " << CPair.size() << " loaded" << endl; } else cout <<"Error:" << filename << "CPair NOT there/loaded" << endl; } void slpNPatternDict :: loadCwordsPairs(string wordL,string wordR, map<string, set<string> >& CPairs,map<string,int>& Dict,map<string,int>& PWords) { //cout<< "hello"<<wordR<<endl; std::replace(wordR.begin(), wordR.end(), ',', ' '); stringstream ss(wordR); string setwords; set<string> setstring; while (ss >> setwords) { //cout << setwords << endl; setstring.insert(setwords); } //set<string> wordRs = wordR; CPairs[wordL] = setstring; } void slpNPatternDict :: loadCPairs(string filename, map<string, set<string> >& CPairs,map<string,int>& Dict, map<string,int>& PWords) { ifstream myfile(filename); if (myfile.is_open()) { string line; while(getline(myfile, line)) { //cout << "String 1"<<line<<endl; //!Making CPair formatting into Correct format upto max extent QString line1 = QString::fromStdString(line); line1.replace(" ","\t"); //dealing with incorrect format QStringList m = line1.split("\t"); if(m[1] == "") { //continue; QMessageBox::information(0, "File Error", "Make sure CPair contains correct file format\nIncorrect_Word(tab)Correct_Word"); break; } line = line1.toStdString(); // Vector of string to save tokens vector <string> tokens; // stringstream class check1 stringstream check1(line); string intermediate; // Tokenizing w.r.t. space 'tab' while(getline(check1, intermediate, '\t')) { tokens.push_back(intermediate); } // Printing the token vector for(int i = 0; i < tokens.size(); i++) { string str1 = tokens[0]; string str2 = tokens[1]; loadCwordsPairs(toslp1(str1),toslp1(str2),CPairs,Dict,PWords); } } cout <<"CPairs " << CPairs.size() << " loaded" << endl; } else cout <<"Error:" << filename << "CPair NOT there/loaded" << endl; } void slpNPatternDict :: loadMapNV(string fileName, map<string,int>& OCRWords, vector<string>& vec, string GBook){ ifstream myfile(fileName); if (myfile.is_open()) { string str1; while (myfile >> str1 ) { str1 = toslp1(str1); OCRWords[str1] = OCRWords[str1] + 1;vec.push_back(str1);} cout <<GBook <<" " <<OCRWords.size() <<" Words Loaded in mapNvector" << endl; } else cout <<"Error:" << GBook<< "Words NOT Loaded in mapNvector" << endl; } int slpNPatternDict :: minIG(int a, int b){ if(a>b)return b; else return a;} int slpNPatternDict :: maxIG(int a, int b){ if(a<b)return b; else return a;} void slpNPatternDict :: loadMapPWords(vector<string>& vGBook,vector<string>& vIBook, map<string,int>& PWords){ int vGsz = vGBook.size(), vIsz = vIBook.size(); int win = vGsz - vIsz; if(win<0) win = -1*win; // search for a word(pre space, post space as well) in Indsenz within win sized window in GDocs and if found then add to PWords for(int t = 0; t < vIsz;t++){ for(int t1 = maxIG(t-win,0); t1 < min(t+win,vGsz); t1++){ string s1 = vIBook[t]; //(vGBook[t1].find(s1) != string::npos) || (vGBook[t1] == s1) if( (vGBook[t1].find(s1) != string::npos)|| (vGBook[t1].find(s1 + " ") != string::npos) || (vGBook[t1].find(" " + s1) != string::npos)) {PWords[s1]++; break;} } } cout << PWords.size() << " words loaded in PWords" << endl; } string slpNPatternDict :: findDictEntries1(string s1, map<string, int>& m2, map<string, int>& m1, int size) { //unordered_ if((s1.size() == 0) || (s1 == "")) return ""; //cout << "s1 "<< s1 << endl; //cout << s1 << endl; //rAmaAnand for(size_t j =0; j < s1.size() ; j++){ //- i +1 j= 0:8 for(size_t i = s1.size() - j; i > 0; i--){// j0 i = 9:1 rAmaAnand rAmaAnan rAmaAna.. , j1 8:2 string str = s1.substr(j,i); //&&((str.size() >= 3)|| ( (str.size()==2) && (str[1] != 'a') &&( size< 3) ) || ((str.size() ==1)&&( size< 2) ) )) //cout << "str "<< str << endl; if((m2[str]>0)||(m1[str]>0)) { //cout << "here "<< str << "L " << s1.substr(0,j) << "R " << s1.substr(j+i,s1.size()-i) << endl; //colorFlag = !colorFlag; //string strcolor = color[colorFlag];// << endl; //cout << "str "<< str << endl; return findDictEntries1(s1.substr(0,j),m2,m1,size) + "<font color=\'" + "green" + "\'>" + toDev(str) + "</font>" + findDictEntries1(s1.substr(j+i,s1.size()-i),m2,m1,size); } } } //cout << "here2 "<< str << "sd"<< endl; return ("<font color=\'red\'>" + toDev(s1) + "</font>"); } string slpNPatternDict :: findDictEntries(string s1, map<string, int>& m2, map<string, int>& m1, int size) { //unordered_ m2["rAma"]++; m2["rAm"]++; string s = findDictEntries1(s1,m2,m1, size); string vowel_dn[]={"आ","इ","ई","उ","ऊ","ऋ","ॠ","ऌ","ॡ","ए","ऐ","ओ","औ"}; string vowel_dn_joiner[]={"ा","ि","ी","ु","ू","ृ","ॄ","ॢ","ॣ","े","ै","ो","ौ"}; //cout << s << endl; size_t t1 = s.find("\'>"); string sL = s.substr(0,t1+3); string sR = s.substr(t1+3,s.size()-t1-3); //cout << sL << " " << sR << endl; for(size_t t =0; t< 12; t++){ string tofind = "\'>" + vowel_dn[t]; while((sR.find(tofind) != string::npos)){ //cout << s << endl; cout << s.find(tofind) << endl; sR.replace(sR.find(tofind),tofind.size(), "\'>" + vowel_dn_joiner[t]); //cout << s << endl; } } return sL + sR; } bool slpNPatternDict :: hasM40PerAsci(string word1){ if(SanFlag||HinFlag){ string asc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; size_t sz = word1.size(); double cnt = 0; for(size_t t =0; t < sz; t++){ if(asc.find(word1.substr(t,1)) != string::npos) cnt ++; if (cnt/(0.4) >= sz) return 1; } } return 0; } bool slpNPatternDict :: hasNoAsci(string word1){ string asc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; size_t sz = word1.size(); for(size_t t =0; t < sz; t++){ if(asc.find(word1.substr(t,1)) != string::npos) {return 0; } } return 1; } void slpNPatternDict :: loadMap(string fileName, map<string,int>& OCRWords, string GBook){ size_t szp = OCRWords.size(); ifstream myfile(fileName); if (myfile.is_open()) { string str1; while (myfile >> str1 ) { if(!hasM40PerAsci(str1)) {str1 = toslp1(str1); /*cout <<str1<<endl;*/ OCRWords[str1] = OCRWords[str1] + 1;}} cout << GBook <<" " <<OCRWords.size() - szp<<" Words Loaded" << endl; } else cout <<"Error:" << GBook<< "Words NOT Loaded" << endl; } // ADDED FOR FEATYRE EXTRACTION bool slpNPatternDict :: insertPatternstoMap(string str, map<string,int>& TPWordsP, size_t& count ,size_t& count6){ //map<string,int >& PWordsP size_t sz = str.size(); if(sz == 0) return 1; for(size_t i = 0; i < (sz+1); i++){ string s1 = str.substr(0,i); if (s1.size()<9) count6++; TPWordsP[s1]++; count++;//PWordsP[s1]++; } return insertPatternstoMap(str.substr(1,sz-1),TPWordsP,count,count6);//PWordsP } // ADDED FOR FEATYRE EXTRACTION //loadPWordsPatternstoTrie(TPWordsP,PWordsP,PWords); size_t slpNPatternDict :: loadDictPatternstoMap(map<string,int >& TPWordsP, map<string,int >& PWords,size_t& count6){ // arg1(strt from 0) ,map<string,int >& PWordsP size_t count = 0,maxsiz = 0; for( map<string,int >::const_iterator ptr=PWords.begin(); ptr!=PWords.end(); ptr++) { insertPatternstoMap(ptr->first, TPWordsP,count,count6); if (ptr->first.size() > maxsiz) maxsiz = ptr->first.size(); } cout << count <<" patterns loaded " << endl; //cout << "m2 size " << m2.size() << endl; return maxsiz; } // ADDED FOR FEATYRE EXTRACTION bool slpNPatternDict :: getNgramFeaturesinVect(string str,map<string,int>& Dict,vector<bool>& vb,vector<size_t>& vbf, size_t& count){ size_t sz = str.size(); //cout<<sz<<endl; if(sz == 1) return 1; for(size_t i = 2; i < (sz+1); i++){ string s1 = str.substr(0,i); //cout<<s1<<endl; if(s1.size() < 9){ if (Dict[s1]>0){vb.push_back(1); vbf.push_back(Dict[s1]);} else {vb.push_back(0); vbf.push_back(0);} count++; } //cout << vb[count]<<endl; } return getNgramFeaturesinVect(str.substr(1,sz-1),Dict,vb,vbf, count);//PWordsP } // ADDED FOR FEATYRE EXTRACTION //https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c bool slpNPatternDict :: endsWith(const std::string& s, const std::string& suffix) { return s.size() >= suffix.size() && s.substr(s.size() - suffix.size()) == suffix; } // ADDED FOR FEATYRE EXTRACTION std::vector<std::string> slpNPatternDict :: split(const std::string& s, const std::string& delimiter, const bool& removeEmptyEntries) { std::vector<std::string> tokens; for (size_t start = 0, end; start < s.length(); start = end + delimiter.length()) { size_t position = s.find(delimiter, start); end = position != string::npos ? position : s.length(); std::string token = s.substr(start, end - start); if (!removeEmptyEntries || !token.empty()) { tokens.push_back(token); } } if (!removeEmptyEntries && (s.empty() || endsWith(s, delimiter))) { tokens.push_back(""); } return tokens; } //ADDED FOR ERROR DETECTION REPORT bool slpNPatternDict :: searchS1inGVec(string s1,size_t iocrdone,vector<string>& gocr,size_t winig){ for(int t1 = maxIG(iocrdone-winig,0); t1 < min(iocrdone+winig,gocr.size()); t1++){ if (s1 == gocr[t1]) return 1; } return 0; } string slpNPatternDict :: findDictEntries(string s1, map<string, int>& m2, map<string, int>& m1) {//unordered_ if((s1.size() == 0) || (s1 == "")) return ""; //cout << s1 << endl; for(size_t i = s1.size(); i > 0; i --){ for(size_t j =0; j < s1.size() - i +1; j++){ string str = s1.substr(j,i); if((m1[str]>0) ) { //cout << "here "<< str << "L " << s1.substr(0,j) << "R " << s1.substr(j+i,s1.size()-i) << endl; return findDictEntries(s1.substr(0,j),m2,m1) + "<font color=\'" + "green" + "\'>" + toDev(str) + "</font>" + findDictEntries(s1.substr(j+i,s1.size()-i),m2,m1); } else if(m2[str]>4) {//cout << "here "<< str << "L " << s1.substr(0,j) << "R " << s1.substr(j+i,s1.size()-i) << endl; return findDictEntries(s1.substr(0,j),m2,m1) + "<font color=\'" + "cyan" + "\'>" + toDev(str) + "</font>" + findDictEntries(s1.substr(j+i,s1.size()-i),m2,m1); } } } //cout << "here2 "<< str << "sd"<< endl; return ("<font color=\'red\'>" + toDev(s1) + "</font>");//("#" + s1 + "#");// } void slpNPatternDict :: find_and_replace(string& source, string const& find, string const& replace) { for(string::size_type i = 0; (i = source.find(find, i)) != string::npos;) { source.replace(i, find.length(), replace); i += replace.length(); } } string slpNPatternDict :: find_and_replace_oddInstancesblue(string source) { string find = "green"; string replace = "blue"; for(string::size_type i = 0; (i = source.find(find, i)) != string::npos;) { source.replace(i, find.length(), replace); //cout << source << endl; if ( replace == "blue") replace = "green"; else replace = "blue"; i += replace.length(); } return source; } string slpNPatternDict :: find_and_replace_oddInstancesorange(string source) { string find = "cyan"; string replace = "orange"; for(string::size_type i = 0; (i = source.find(find, i)) != string::npos;) { source.replace(i, find.length(), replace); //cout << source << endl; if ( replace == "orange") replace = "cyan"; else replace = "orange"; i += replace.length(); } return source; } using namespace std; void slpNPatternDict :: allignlcsnew(string& str1,string& str2,string& str3){ string str1new, str2new; size_t t1 = 0; size_t t2 =0; size_t t3 =0; string s1,s2,s3; // while1 // a) addition if s1 == s3, and s2 differs add space to s1n, append t2 only so that we can reach close to s1 == s3 == s2 // b) deletion if s2 == s3, and s1 differs add space to s2n, append t1 only so that we can reach close to s2 == s3 == s1 // substitution if s1 != s2 != s3 s1n += s1, s2n += s2 append t1 and t2 // nothing if s1 == s2 == s3 s1n += s1, s2n += s2 append t1 and t2 and t3; if t3 == str3.size() Up3Flag = 1 break; // if Up3Flag find which is smaller, add spaces in end of smaller smallstr = min(str1.size() - t1,str2.size() - t2); while(1){ s1 = str1.substr(t1,1); s2 = str2.substr(t2,1); s3 = str3.substr(t3,1); //a) add //cout << t1 << " " << t2 << " " << t3<< endl; //cout << s1 << " " << s2 << " " << s3<< endl; if((s1 == s3) && (s2 != s3)) {str1new += " "; str2new += s2; t2++; /*cout << "a growing str1new " << str1new <<endl;*/ } if((s2 == s3) && (s1 != s3)) {str2new += " "; str1new += s1; t1++; /*cout << "d growing str2new " << str2new <<endl;*/ } // b) if((s2 != s3) && (s1 != s3)) {str1new += s1; str2new += s2; t1++; t2++; /*cout << "s growing str12new " << str1new<<" " <<str2new <<endl;*/ } //c) if((s2 == s3) && (s1 == s3)) {str1new += s1; str2new += s2; t1++; t2++;t3++; /*cout << "n growing str12new " << str1new<<" " <<str2new <<endl;*/ if(t3 == str3.size()) {break;}} //d) } //cout << " " << str1new << " " << str2new << endl; uint max = str1.size() ; if(max < str2.size() ) max = str2.size() ; //cout << t1 << " " << t2 << " " << max<< endl; while(1) { if((t1>=max) && (t2>=max)) break; if(t1<str1.size()) s1 = str1.substr(t1,1); else s1 = " "; if(t2<str2.size()) s2 = str2.substr(t2,1); else s2 = " "; //cout << t1 << " " << t2 << " " << max<< endl; //cout << s1 << " " << s2 << " " << endl; if(t1 < max) str1new += s1; else str1new += " "; if(t2 < max) str2new += s2; else str2new += " "; t1++; t2++; } str1 = str1new; str2 = str2new; } typedef std::vector<int> lengths; /* The "members" type is used as a sparse set for LCS calculations. Given a sequence, xs, and members, m, then if m[i] is true, xs[i] is in the LCS. */ typedef std::vector<bool> members; /* Fill the LCS sequence from the members of a sequence, xs x - an iterator into the sequence xs xs_in_lcs - members of xs lcs - an output results iterator */ template <typename it, typename ot> void slpNPatternDict :: set_lcs(it x, members const & xs_in_lcs, ot lcs) { for (members::const_iterator xs_in = xs_in_lcs.begin(); xs_in != xs_in_lcs.end(); ++xs_in, ++x) { if (*xs_in) { *lcs++ = *x; } } } /* Calculate LCS row lengths given iterator ranges into two sequences. On completion, `lens` holds LCS lengths in the final row. */ template <typename it> void slpNPatternDict :: lcs_lens(it xlo, it xhi, it ylo, it yhi, lengths & lens) { // Two rows of workspace. // Careful! We need the 1 for the leftmost column. lengths curr(1 + distance(ylo, yhi), 0); lengths prev(curr); for (it x = xlo; x != xhi; ++x) { swap(prev, curr); int i = 0; for (it y = ylo; y != yhi; ++y, ++i) { curr[i + 1] = *x == *y ? prev[i] + 1 : std::max(curr[i], prev[i + 1]); } } swap(lens, curr); } /* Recursive LCS calculation. See Hirschberg for the theory! This is a divide and conquer algorithm. In the recursive case, we split the xrange in two. Then, by calculating lengths of LCSes from the start and end corners of the [xlo, xhi] x [ylo, yhi] grid, we determine where the yrange should be split. xo is the origin (element 0) of the xs sequence xlo, xhi is the range of xs being processed ylo, yhi is the range of ys being processed Parameter xs_in_lcs holds the members of xs in the LCS. */ template <typename it> void slpNPatternDict :: calculate_lcs(it xo, it xlo, it xhi, it ylo, it yhi, members & xs_in_lcs) { unsigned const nx = distance(xlo, xhi); if (nx == 0) { // empty range. all done } else if (nx == 1) { // single item in x range. // If it's in the yrange, mark its position in the LCS xs_in_lcs[distance(xo, xlo)] = find(ylo, yhi, *xlo) != yhi; } else { // split the xrange it xmid = xlo + nx / 2; // Find LCS lengths at xmid, working from both ends of the range lengths ll_b, ll_e; std::reverse_iterator<it> hix(xhi), midx(xmid), hiy(yhi), loy(ylo); lcs_lens(xlo, xmid, ylo, yhi, ll_b); lcs_lens(hix, midx, hiy, loy, ll_e); // Find the optimal place to split the y range lengths::const_reverse_iterator e = ll_e.rbegin(); int lmax = -1; it y = ylo, ymid = ylo; for (lengths::const_iterator b = ll_b.begin(); b != ll_b.end(); ++b, ++e) { if (*b + *e > lmax) { lmax = *b + *e; ymid = y; } // Care needed here! // ll_b and ll_e contain one more value than the range [ylo, yhi) // As b and e range over dereferenceable values of ll_b and ll_e, // y ranges over iterator positions [ylo, yhi] _including_ yhi. // That's fine, y is used to split [ylo, yhi), we do not // dereference it. However, y cannot go beyond ++yhi. if (y != yhi) { ++y; } } // Split the range and recurse calculate_lcs(xo, xlo, xmid, ylo, ymid, xs_in_lcs); calculate_lcs(xo, xmid, xhi, ymid, yhi, xs_in_lcs); } } // Calculate an LCS of (xs, ys), returning the result in an_lcs. template <typename seq> void slpNPatternDict :: lcs(seq const & xs, seq const & ys, seq & an_lcs) { members xs_in_lcs(xs.size(), false); calculate_lcs(xs.begin(), xs.begin(), xs.end(), ys.begin(), ys.end(), xs_in_lcs); set_lcs(xs.begin(), xs_in_lcs, back_inserter(an_lcs)); } bool slpNPatternDict :: isNonVowel(string ocrp){ string a = "aeiouAEIOU"; for(size_t t =0; t< a.size(); t ++){ if (ocrp == a.substr(t,1)) return 0; } return 1; } string slpNPatternDict :: removeSpaces(string input) { string output; int length = input.length(); for (int i = 0; i < length; i++) { if(input[i] != ' ') output+= input[i]; } return output; } void slpNPatternDict :: findConfisions(string ocr, string correct, vector<string>& vec){ //vector<string> vec; //ocrp = “”; correctp = “”; // for( t = 0 t< s.size) // load ocrp correctp if t > 0 with substr(t-1,1) //ocr == “”; correct = “” // while(s1 != s2) ocr += s1; correct += s2; t++;// s1 s2 are chars from each word // of ocrp == “”load ocrnext in ocrp wiht substr(t,1) // subss add if ocr != “” :- // if ocrp is a non-vowel vec.push_back(ocrp+ocr, correctp+correct) else vec.push_back(ocr, correct) //ocrp = s1; correctp = s2; size_t sz = ocr.size(); string ocrp = ""; size_t t = 0; while(1){ string ocrn =""; string correctn =""; string s1 = ocr.substr(t,1), s2 = correct.substr(t,1); //cout << "t = " << t << " " << sz << endl; // deletion if(s2 == " ") { while(s1 != s2) {ocrn += s1; correctn += s2; t++; if(t >= sz) break; s1 = ocr.substr(t,1); s2 = correct.substr(t,1);} if(ocrp != "") vec.push_back(removeSpaces(ocrp+ocrn) + " " + removeSpaces(ocrp+correctn)); else if(t < sz) vec.push_back(removeSpaces(ocrn + s1) + " " + removeSpaces(correctn + s1)); else vec.push_back(removeSpaces(ocrn) + " " + removeSpaces(correctn)); } // addition else if(s1 == " ") { while(s1 != s2) {ocrn += s1; correctn += s2; t++; if(t >= sz) break; s1 = ocr.substr(t,1); s2 = correct.substr(t,1);} if((ocrp != "")&&(isNonVowel(ocrp))) vec.push_back(removeSpaces(ocrp+ocrn) + " " + removeSpaces(ocrp+correctn)); else if(t < sz) vec.push_back(removeSpaces(ocrn + s1) + " " + removeSpaces(correctn + s1)); else vec.push_back(removeSpaces(ocrn) + " " + removeSpaces(correctn)); } else if(s1 != s2) { while(s1 != s2) {ocrn += s1; correctn += s2; t++; if(t >= sz) break; s1 = ocr.substr(t,1); s2 = correct.substr(t,1);} if((ocrp != "")&&(isNonVowel(ocrp))) vec.push_back(removeSpaces(ocrp+ocrn) + " " + removeSpaces(ocrp+correctn));/*else if(t < sz) cout << "s " << ocrn + s1 << " " << correctn + s1<< endl;*/ else vec.push_back(removeSpaces(ocrn) + " " + removeSpaces(correctn)); } else t++; ocrp = s1; if(t >= sz) break; } //return vec; } void slpNPatternDict :: findConfisionsNindex(string ocr, string correct, vector<string>& vec, vector<int>& vind){ //vector<string> vec; //ocrp = “”; correctp = “”; // for( t = 0 t< s.size) // load ocrp correctp if t > 0 with substr(t-1,1) //ocr == “”; correct = “” // while(s1 != s2) ocr += s1; correct += s2; t++;// s1 s2 are chars from each word // of ocrp == “”load ocrnext in ocrp wiht substr(t,1) // subss add if ocr != “” :- // if ocrp is a non-vowel vec.push_back(ocrp+ocr, correctp+correct) else vec.push_back(ocr, correct) //ocrp = s1; correctp = s2; size_t sz = ocr.size(); string ocrp = ""; size_t t = 0; int s1p; while(1){ string ocrn =""; string correctn =""; string s1 = ocr.substr(t,1), s2 = correct.substr(t,1); int s1t = t; //cout << "t = " << t << " " << sz << endl; // deletion if(s2 == " ") { while(s1 != s2) {ocrn += s1; correctn += s2; t++; if(t >= sz) break; s1 = ocr.substr(t,1); s2 = correct.substr(t,1);} if(ocrp != "") {vec.push_back(removeSpaces(ocrp+ocrn) + " " + removeSpaces(ocrp+correctn)); vind.push_back(s1p);}else if(t < sz) {vec.push_back(removeSpaces(ocrn + s1) + " " + removeSpaces(correctn + s1)); vind.push_back(s1t);} else {vec.push_back(removeSpaces(ocrn) + " " + removeSpaces(correctn)); vind.push_back(s1t);} } // addition else if(s1 == " ") { while(s1 != s2) {ocrn += s1; correctn += s2; t++; if(t >= sz) break; s1 = ocr.substr(t,1); s2 = correct.substr(t,1);} if((ocrp != "")&&(isNonVowel(ocrp))) {vec.push_back(removeSpaces(ocrp+ocrn) + " " + removeSpaces(ocrp+correctn)); vind.push_back(s1p);} else if(t < sz) {vec.push_back(removeSpaces(ocrn + s1) + " " + removeSpaces(correctn + s1)); vind.push_back(s1t);} else {vec.push_back(removeSpaces(ocrn) + " " + removeSpaces(correctn)); vind.push_back(s1t);} } else if(s1 != s2) { while(s1 != s2) {ocrn += s1; correctn += s2; t++; if(t >= sz) break; s1 = ocr.substr(t,1); s2 = correct.substr(t,1);} if((ocrp != "")&&(isNonVowel(ocrp))) {vec.push_back(removeSpaces(ocrp+ocrn) + " " + removeSpaces(ocrp+correctn)); vind.push_back(s1p);}/*else if(t < sz) cout << "s " << ocrn + s1 << " " << correctn + s1<< endl;*/ else {vec.push_back(removeSpaces(ocrn) + " " + removeSpaces(correctn)); vind.push_back(s1t);} } else {t++;} ocrp = s1; s1p = s1t; if(t >= sz) break; } //return vec; } void slpNPatternDict :: removeEndCommonSpaces(string& str1, string& str2){ size_t t = str1.size(); string s1 = str1.substr(t-1,1), s2 = str1.substr(t-1,1); while((s1 == " ") && (s2 == " ")) {str1 = str1.substr(0,t-1); str2 = str2.substr(0,t-1); t = str1.size(); s1 = str1.substr(t-1,1), s2 = str1.substr(t-1,1);} } /* vector<string> findConfisionsPair(string str1, string str2){ string str3; lcs(str1,str2,str3); allignlcsnew(str1,str2,str3); removeEndCommonSpaces(str1,str2); vector<string> vec = findConfisions(str1,str2); return vec; }*/ void slpNPatternDict :: appendConfusionsPairs(string str1, string str2, vector<string>& vec){ str1 = "@" + toslp1(str1) + "#"; str2 = "@" + toslp1(str2) + "#"; string str3; lcs(str1,str2,str3); allignlcsnew(str1,str2,str3); removeEndCommonSpaces(str1,str2); findConfisions(str1,str2,vec); //return vec; } string slpNPatternDict :: appendConfusionsPairsNindex(string str1, string str2, vector<string>& vec, vector<int>& vecind){ str1 = "@" + toslp1(str1) + "#"; str2 = "@" + toslp1(str2) + "#"; string str3; lcs(str1,str2,str3); allignlcsnew(str1,str2,str3); removeEndCommonSpaces(str1,str2); findConfisionsNindex(str1,str2,vec,vecind); return str1; //return vec; } void slpNPatternDict :: loadvectomap(vector<string> ConfP, map<string,int>& ConfPmap){ for(size_t t = 0; t<ConfP.size(); t++) ConfPmap[ConfP[t]]++; } void slpNPatternDict :: printvecstr(vector<string> ConfP){ for(size_t t = 0; t<ConfP.size(); t++) cout << ConfP[t] << endl; } void slpNPatternDict :: printvecint(vector<int> ConfP){ for(size_t t = 0; t<ConfP.size(); t++) cout << ConfP[t] << endl; } //loadConfusions("1kECPairs",ConfPmap) void slpNPatternDict :: loadConfusions(string fileName,map<string,int>& ConfPmap){ vector<string> ConfP; string str1, str2; ifstream myfile(fileName); if (myfile.is_open()) { while(myfile >> str1){ myfile >> str2; appendConfusionsPairs((str1),(str2),ConfP);//toslp1 //cout << str1 << " " << str2 << endl; //vec.clear(); } cout << ConfP.size() << " Confusions Loaded" << endl;} else cout <<"Error Confusions NOT Loaded" << endl; loadvectomap(ConfP,ConfPmap); } void slpNPatternDict :: loadConfusions2(string fileName1,string fileName2,map<string,int>& ConfPmap){ vector<string> ConfP; string str1, str2; ifstream myfile(fileName1); ifstream myfile2(fileName2); if ((myfile.is_open()) && (myfile2.is_open())) { while(myfile >> str1){ myfile2 >> str2; appendConfusionsPairs((str1),(str2),ConfP);//toslp1 //cout << str1 << " " << str2 << endl; //vec.clear(); } cout <<ConfP.size() << " Confusions Loaded" << endl;} else cout <<"Error Confusions NOT Loaded" << endl; loadvectomap(ConfP,ConfPmap); } void slpNPatternDict :: loadConfusionsFont(vector<string> fileName1,vector<string> fileName2,map<string,int>& ConfPmap){ vector<string> ConfP; if (fileName1.size() > 0) { for(size_t i =0;i < fileName1.size(); i++ ){ appendConfusionsPairs(fileName1[i],fileName2[i],ConfP);//toslp1 } cout << ConfP.size() << " Confusions Loaded from" << fileName1.size() <<" pairs"<< endl;} else cout <<"Error Confusions NOT Loaded" << endl; loadvectomap(ConfP,ConfPmap); } void slpNPatternDict :: generateCorrectionPairs(vector<string> &wrong,vector<string> &right,string localFilenameI,string localFilenameC){ vector<string> vecpI, vecpC; std::ifstream sIpage(localFilenameI); if (!(sIpage.is_open())) {cout << "cannot open inds/corrected file" <<endl; return;} // break the while loop for page_no string localstr; map<string, bool> isEngOrNOT; while(sIpage >> localstr) vecpI.push_back(toslp1(localstr)); sIpage.close(); std::ifstream sCpage(localFilenameC); while(sCpage >> localstr) { vecpC.push_back(toslp1(localstr)); sIpage.close(); if(hasM40PerAsci(localstr)) isEngOrNOT[toslp1(localstr)] = 1;} int sizew = wrong.size(); // if 1st word is wrong generate suggestions int vGsz = vecpC.size(), vIsz = vecpI.size(); //if (vGsz >vIsz ) mapTyping[page_no] = vGsz - vIsz; //cout << vGsz << " " << vIsz << endl; int win = vGsz - vIsz; if(win<0) win = -1*win; win = maxIG(win,5); //cout << win << endl; //float WER = 0; // search for a word(pre space, post space as well) in Indsenz within win sized window in GDocs and if found then add to PWords for(int t = 0; t < vIsz;t++){ size_t minedit = 1000; string s1 = vecpI[t]; //(vGBook[t1].find(s1) != string::npos) || (vGBook[t1] == s1) string sC; for(int t1 = maxIG(t-win,0); t1 < min(t+win,vGsz); t1++){ string sCt1 = vecpC[t1]; eddis e; size_t mineditIC = e.editDist(s1,sCt1); if(mineditIC < minedit) {minedit = mineditIC; sC = sCt1; } if (sCt1 == s1) {/*WER++;*/ break;} } if((s1 != sC) && (/*isEngOrNOT[sC] != */1)) {wrong.push_back(s1); right.push_back(sC); /*cout << s1 <<" " << sC << endl;*/} } cout << wrong.size() - sizew << " new correction pairs loaded" << endl; } void slpNPatternDict :: generatePairs(vector<string> &wrong,vector<string> &right,string localFilenameI,string localFilenameC){ vector<string> vecpI, vecpC; std::ifstream sIpage(localFilenameI); if (!(sIpage.is_open())) {cout << "cannot open inds/corrected file" <<endl; return;} // break the while loop for page_no string localstr; map<string, bool> isEngOrNOT; while(sIpage >> localstr) vecpI.push_back(toslp1(localstr)); sIpage.close(); std::ifstream sCpage(localFilenameC); while(sCpage >> localstr) { vecpC.push_back(toslp1(localstr)); sIpage.close(); if(hasM40PerAsci(localstr)) isEngOrNOT[toslp1(localstr)] = 1;} int sizew = wrong.size(); // if 1st word is wrong generate suggestions int vGsz = vecpC.size(), vIsz = vecpI.size(); //if (vGsz >vIsz ) mapTyping[page_no] = vGsz - vIsz; //cout << vGsz << " " << vIsz << endl; int win = vGsz - vIsz; if(win<0) win = -1*win; win = maxIG(win,5); //cout << win << endl; //float WER = 0; // search for a word(pre space, post space as well) in Indsenz within win sized window in GDocs and if found then add to PWords for(int t = 0; t < vIsz;t++){ size_t minedit = 1000,minediti; string s1 = vecpI[t]; //(vGBook[t1].find(s1) != string::npos) || (vGBook[t1] == s1) string sC; for(int t1 = maxIG(t-win,0); t1 < min(t+win,vGsz); t1++){ string sCt1 = vecpC[t1]; eddis e; size_t mineditIC = e.editDist(s1,sCt1); if(mineditIC < minedit) {minedit = mineditIC; sC = sCt1; minediti = t1; } if (sCt1 == s1) {/*WER++;*/ sC = s1; vecpC[t1] = ""; break;} /*size_t szt = sCt1.find(s1); size_t sCt1sz = sCt1.size(); if((szt != string::npos) && (szt == 0)){/WER++;/ sC = s1; vecpC[t1] = sCt1.substr(s1.size(),sCt1sz - s1.size()); break;} if((szt != string::npos) && (szt == sCt1sz - s1.size())){ sC = s1; vecpC[t1] = sCt1.substr(0,sCt1sz - s1.size()); break;} */ } if(sC != s1) vecpC[minediti] = ""; if( (/*isEngOrNOT[sC] != */1)) {wrong.push_back(s1); right.push_back(sC); /*cout << s1 <<" " << sC << endl;*/} //(s1 != sC) && } cout << wrong.size() - sizew << " new correction pairs loaded" << endl; if(wrong.size() != right.size()) cout <<"ERROR (wrong.size() != right.size() ) "<<endl; } void slpNPatternDict :: generatePairsIEROCR(string localFilenameI,string localFilenameC, string Rep, string Repy){ vector<string> vecpI, vecpC; std::ofstream repPair(Rep); std::ofstream repPairy(Repy); std::ifstream sIpage(localFilenameI); if (!(sIpage.is_open())) {cout << "cannot open inds/corrected file" <<endl; return;} // break the while loop for page_no string localstr; map<string, bool> isEngOrNOT; while(sIpage >> localstr) vecpI.push_back(toslp1(localstr)); sIpage.close(); std::ifstream sCpage(localFilenameC); while(sCpage >> localstr) { vecpC.push_back(toslp1(localstr)); sIpage.close(); if(hasM40PerAsci(localstr)) isEngOrNOT[toslp1(localstr)] = 1;} //int sizew = wrong.size(); // if 1st word is wrong generate suggestions int vGsz = vecpC.size(), vIsz = vecpI.size(); //if (vGsz >vIsz ) mapTyping[page_no] = vGsz - vIsz; //cout << vGsz << " " << vIsz << endl; int win = vGsz - vIsz; if(win<0) win = -1*win; win = maxIG(win,20); //cout << win << endl; //float WER = 0; // search for a word(pre space, post space as well) in Indsenz within win sized window in GDocs and if found then add to PWords for(int t = 0; t < vIsz;t++){ size_t minedit = 1000,minediti; string s1 = vecpI[t]; //(vGBook[t1].find(s1) != string::npos) || (vGBook[t1] == s1) string sC; for(int t1 = maxIG(t-win,0); t1 < min(t+win,vGsz); t1++){ string sCt1 = vecpC[t1]; eddis e; size_t mineditIC = e.editDist(s1,sCt1); if(mineditIC < minedit) {minedit = mineditIC; sC = sCt1; minediti = t1; } if (sCt1 == s1) {/*WER++;*/ sC = s1; vecpC[t1] = ""; break;} /*size_t szt = sCt1.find(s1); size_t sCt1sz = sCt1.size(); if((szt != string::npos) && (szt == 0)){/WER++;/ sC = s1; vecpC[t1] = sCt1.substr(s1.size(),sCt1sz - s1.size()); break;} if((szt != string::npos) && (szt == sCt1sz - s1.size())){ sC = s1; vecpC[t1] = sCt1.substr(0,sCt1sz - s1.size()); break;} */ } if( (/*isEngOrNOT[sC] != */1) && (sC != "")) { repPair << s1 << endl; repPairy << sC << endl; } } repPairy.close(); repPair.close(); sIpage.close();sCpage.close(); } void slpNPatternDict :: generatePairsSpaced(vector<string> &wrong,vector<string> &right,string localFilenameI,string localFilenameC){ vector<string> vecpI, vecpC; std::ifstream sIpage(localFilenameI); if (!(sIpage.is_open())) {cout << "cannot open inds/corrected file" <<endl; return;} // break the while loop for page_no string localstr; map<string, bool> isEngOrNOT; while(sIpage >> localstr) vecpI.push_back(toslp1(localstr)); sIpage.close(); std::ifstream sCpage(localFilenameC); while(sCpage >> localstr) { vecpC.push_back(toslp1(localstr)); sIpage.close(); if(hasM40PerAsci(localstr)) isEngOrNOT[toslp1(localstr)] = 1;} int sizew = wrong.size(); // if 1st word is wrong generate suggestions int vGsz = vecpC.size(), vIsz = vecpI.size(); //if (vGsz >vIsz ) mapTyping[page_no] = vGsz - vIsz; //cout << vGsz << " " << vIsz << endl; int win = vGsz - vIsz; if(win<0) win = -1*win; win = maxIG(win,5); //cout << win << endl; //float WER = 0; // search for a word(pre space, post space as well) in Indsenz within win sized window in GDocs and if found then add to PWords for(int t = 0; t < vIsz;t++){ size_t minedit = 1000,minediti; string s1 = vecpI[t]; //(vGBook[t1].find(s1) != string::npos) || (vGBook[t1] == s1) string sC; for(int t1 = maxIG(t-win,0); t1 < min(t+win,vGsz); t1++){ string sCt1 = vecpC[t1]; eddis e; size_t mineditIC = e.editDist(s1,sCt1); if(mineditIC < minedit) {minedit = mineditIC; sC = sCt1; minediti = t1; } if (sCt1 == s1) {/*WER++;*/ sC = s1; vecpC[t1] = ""; break;} /*size_t szt = sCt1.find(s1); size_t sCt1sz = sCt1.size(); if((szt != string::npos) && (szt == 0)){/WER++;/ sC = s1; vecpC[t1] = sCt1.substr(s1.size(),sCt1sz - s1.size()); break;} if((szt != string::npos) && (szt == sCt1sz - s1.size())){ sC = s1; vecpC[t1] = sCt1.substr(0,sCt1sz - s1.size()); break;} */ } if(sC != s1) {vecpC[minediti] = "";} if( (/*isEngOrNOT[sC] != */1)) {wrong.push_back(s1); right.push_back(sC); /*cout << s1 <<" " << sC << endl;*/} else {wrong.push_back(s1); right.push_back("");}//(s1 != sC) && } cout << wrong.size() - sizew << " new correction pairs loaded" << endl; if(wrong.size() != right.size()) cout <<"ERROR (wrong.size() != right.size() ) "<<endl; } void slpNPatternDict :: loadCPair(string fileName1,string fileName2,map<string,string>& CPair){ string str1, str2; ifstream myfile(fileName1); ifstream myfile2(fileName2); if ((myfile.is_open()) && (myfile2.is_open())) { while(myfile >> str1){ myfile2 >> str2; CPair[str1] = str2;//toslp1 //cout << str1 << " " << str2 << endl; //vec.clear(); } cout <<CPair.size() << " CPairs Loaded" << endl;} else cout <<"Error CPairs NOT Loaded" << endl; //loadvectomap(ConfP,ConfPmap); } void slpNPatternDict :: loadTopConfusions(map<string,int>& ConfPmap,map<string, string>& TopConfusions,map<string, int>& TopConfusionsMask){ map<string, int> TopSuggFreq; for(map<string, int >::const_iterator it = ConfPmap.begin(); it != ConfPmap.end(); ++it) { //std::cout << it->first << " " << it->second<< "\n"; string rule = it->first; istringstream s(rule);string l,r; s>>l; s>>r; //if(TopSuggFreq[l] < it->second){ TopSuggFreq[l] = it->second; TopConfusions[l] = r; TopConfusionsMask[l] ++; //} l.clear(); r.clear(); } } std::string slpNPatternDict :: tokenize(const std::string& s) { if (!s.size()) { return ""; } std::stringstream ss; ss << s[0]; for (uint i = 1; i < s.size(); i++) { ss << ' ' << s[i]; } return ss.str(); } // print only rules in Pattern Miner's Rule Input form void slpNPatternDict :: printConfusionRulesmap(map<string,int>& ConfPmap){ map<string,vector<string> > rulesCorrectFormat; // print the Map rule and correct the format for(map<string, int >::const_iterator it = ConfPmap.begin(); it != ConfPmap.end(); ++it) { //std::cout << it->first << " " << it->second<< "\n"; string rule = it->first; istringstream s(rule); string l,r; s>>l; s>>r; if((l.size() < 3) && (r.size() < 3)) rulesCorrectFormat[r].push_back(l); } //file.close(); // print in correct format for( map<string,vector<string> >::const_iterator ptr=rulesCorrectFormat.begin(); ptr!=rulesCorrectFormat.end(); ptr++) { string s = (ptr->first); cout << tokenize(s) << " -> "; for( vector<string>::const_iterator eptr=ptr->second.begin(); eptr!=ptr->second.end(); eptr++){ string s1 = *eptr; cout << tokenize(s1) << " ! "; } cout << endl; } } //for choosing best out of nearest suggestions:- int slpNPatternDict :: loadWConfusionsNindex1(string str1,string str2,map<string,int>& ConfPmap,vector<string>& wordConfusions,vector<int>& wCindex){ string str1New = appendConfusionsPairsNindex(str1,str2,wordConfusions,wCindex); int szold = wordConfusions.size();// more confusions more szold //filter confusions:- //cout<< str1New << endl; for(size_t t = 0; t<wordConfusions.size(); t++) { if(ConfPmap[wordConfusions[t]]>0) {/*cout << wCindex[t] << " "<< toDev(wordConfusions[t]) << endl;*/} else {wordConfusions.erase(wordConfusions.begin() + t); wCindex.erase(wCindex.begin() + t); t--;}} return (szold - wordConfusions.size());// more confusions are Indsenz OCR Confusions, less will be difference } // for alligning OCR Pair words string slpNPatternDict :: loadWConfusionsNindex(string str1,string str2,map<string,int>& ConfPmap,vector<string>& wordConfusions,vector<int>& wCindex){ string str1New = appendConfusionsPairsNindex(str1,str2,wordConfusions,wCindex); //filter confusions:- //cout<< str1New << endl; for(size_t t = 0; t<wordConfusions.size(); t++) { if(ConfPmap[wordConfusions[t]]>0) {/*cout << wCindex[t] << " "<< toDev(wordConfusions[t]) << endl;*/} else {wordConfusions.erase(wordConfusions.begin() + t); wCindex.erase(wCindex.begin() + t); t--;}} return str1New; } void slpNPatternDict :: replacestrcnf(string& newstring,size_t i,string cnfn) { istringstream s(cnfn); string lhs,rhs; s >> lhs; s >> rhs; newstring = newstring.replace(i,lhs.length(),rhs); } // parts from SamasBreakComb.hpp bool slpNPatternDict :: endswithHalanta(string str) { if (str.size() <= 2) return 1; //ALSO INCLUDING ONE/TWO CHARS if (str.size() >= 4) return 0; //ignoring Words with Halanta having more than 4 chars string lastchar = str.substr(str.size()-1,1); string str1 = "aeiouAEIOUH"; for(size_t i = 0; i < str1.size(); i++) { if(str1.substr(i,1) == lastchar) return 0; } return 1; } void slpNPatternDict :: removeEndSpaces(string& str1){ size_t t = str1.size(); string s1 = str1.substr(t-1,1); //cout << "1 s1 " << s1<< endl; while((s1 == " ")) {str1 = str1.substr(0,t-1); t = str1.size(); s1 = str1.substr(t-1,1);} //cout << "2 s1 " << s1<< endl; s1 = str1.substr(0,1); //cout << "3 s1 " << s1<< endl; while((s1 == " ")) {str1 = str1.substr(1,t-1); t = str1.size(); s1 = str1.substr(0,1);} //cout << "4 s1 " << s1<< endl; } // parts from SamasBreakComb.hpp // samas corrector.h starts string slpNPatternDict :: deletePoornaVirams(string input){ string out; for(size_t t = 0; t < input.size(); t++){ string s; s += input[t]; if( s != "|") out += s; } return out; } /* applicable when trieeditdisone is used as searchTrie will give str as output, else it give vector<string> string SamasBreakLRCorrect(string s1, unordered_map<string, int>& m1, unordered_map<string, int>& PWordsNew) { if((s1.size() == 0) || (s1 == "")) return ""; if((m1[s1]>0)||PWordsNew[s1]>0) return " " + s1 + " "; //cout << "s1 "<< s1 << endl; for(size_t i = s1.size(); i > 0; i --){// DASOAHAM 8 for(size_t j =0; j < s1.size() - i+1; j++){ // i determinze size of substring string str = s1.substr(j,i);// i = 8, j = 0:0 DASOAHAM ; i = 7, j = 0:1 DASOAHA ASOAHAM..... ;i =1, j = 0:7 D A S O A H A M // checking str //cout <<"str outside " << str << endl; if((m1[str]>0)||PWordsNew[str]>0) { //cout << "here "<< str << " L " << s1.substr(0,j) << "R " << s1.substr(j+i,s1.size()-i) << endl; //cout <<"str inside " << str << endl; //cout <<"left "<< s1.substr(0,j) << " nearest "<< searchTrie(s1.substr(0,j)) << endl; //cout <<"right "<< s1.substr(j+i,s1.size()-i) << " nearest "<< searchTrie(s1.substr(j+i,s1.size()-i)) << endl; return deletePoornaVirams(searchTrie(s1.substr(0,j)) + (str) + searchTrie(s1.substr(j+i,s1.size()-i)) ); } } } return ""; // //return ((s1));//("#" + s1 + "#");// }*/ size_t slpNPatternDict :: cntSamas(string in, string& out){ out = ""; size_t cnt = 0; string word; removeEndSpaces(in); istringstream s(in); while(s >> word) {out += word + " "; cnt ++; /*cout << cnt << " " << word << " " << out << endl;*/} if(endswithHalanta(word)) cnt++; return cnt; } string slpNPatternDict :: SamasLR(string s1, map<string, int>& m1) {//, map<string, int>& PWordsNew if((s1.size() == 0) || (s1 == "")) return ""; if((m1[s1]>0)) return " " + s1 + " ";//||PWordsNew[s1]>0 //cout << "s1 "<< s1 << endl; for(size_t i = s1.size(); i > 0; i --){// DASOAHAM 8 for(size_t j =0; j < s1.size() - i+1; j++){ // i determinze size of substring string str = s1.substr(j,i);// i = 8, j = 0:0 DASOAHAM ; i = 7, j = 0:1 DASOAHA ASOAHAM..... ;i =1, j = 0:7 D A S O A H A M // checking str //cout <<"str outside " << str << endl; if((m1[str]>0)) {//||PWordsNew[str]>0 //cout << "here "<< str << " L " << s1.substr(0,j) << "R " << s1.substr(j+i,s1.size()-i) << endl; //cout <<"str inside " << str << endl; //cout <<"left "<< s1.substr(0,j) << " nearest "<< searchTrie(s1.substr(0,j)) << endl; //cout <<"right "<< s1.substr(j+i,s1.size()-i) << " nearest "<< searchTrie(s1.substr(j+i,s1.size()-i)) << endl; return (SamasLR(s1.substr(0,j),m1) + " " + (str)+ " " + SamasLR(s1.substr(j+i,s1.size()-i),m1) ); //,PWordsNew,PWordsNew } } } return (" #" + s1 + "# "); // //return ((s1));//("#" + s1 + "#");// } string slpNPatternDict :: SamasRL(string s1, map<string, int>& m1) { //, map<string, int>& PWordsNew if((s1.size() == 0) || (s1 == "")) return ""; if((m1[s1]>0)) return " " + s1 + " ";//||PWordsNew[s1]>0 //cout << "s1 "<< s1 << endl; for(size_t i = s1.size(); i > 0; i --){// DASOAHAM 8 for(size_t j =0; j < s1.size() - i+1; j++){ // i determinze size of substring //cout << s1.size() << " " << j << endl; size_t jd =s1.size() - i - j; string str = s1.substr(jd,i); if((m1[str]>0)) {//||PWordsNew[str]>0 //cout << "here "<< str << " L " << s1.substr(0,j) << "R " << s1.substr(j+i,s1.size()-i) << endl; //cout <<"str inside " << str << endl; //cout <<"left "<< s1.substr(0,j) << " nearest "<< searchTrie(s1.substr(0,j)) << endl; //cout <<"right "<< s1.substr(j+i,s1.size()-i) << " nearest "<< searchTrie(s1.substr(j+i,s1.size()-i)) << endl; return (SamasRL(s1.substr(0,jd),m1) + " " + (str)+ " " + SamasRL(s1.substr(jd+i,s1.size()-i),m1) );//,PWordsNew,PWordsNew } } } return (" #" + s1 + "# "); // //return ((s1));//("#" + s1 + "#");// } // samas corrector.h ends // str1cnt = minsize_t(cntSamas(SamasLR(toslp1(str1),Dict,SmasWords),partsLR), cntSamas(SamasRL(toslp1(str1),Dict,SmasWords),partsRL),FlagLR); size_t slpNPatternDict :: minsize_t(size_t a,size_t b,bool& FlagLR){ if (b < a) {FlagLR = 0; return b;} else {FlagLR =1; return a;} } //print2OCRSugg("RemGOCR",ConfPmap,Dict,SmasWords) string slpNPatternDict :: print2OCRSugg(string str1, string str2, map<string,int>& ConfPmap,map<string,int>& Dict){//,map<string,int> SmasWords //cout << "generating Pair Sugg for "<<str1<< " ";//<<"suggestion for " << endl if((str2 == "") || (str2 == " ") || (str2 == " ")) {/*cout << "no suggestion" << endl;*/ return "";} string partsLR,partsRL; string twoOCRsugg = str1; bool FlagLR,Flag1stSuggGenerated; Flag1stSuggGenerated =1; //Flag1stSuggGenerated :- if cnt 8 for str1 and <=8 for a suggestion then look for cnt <8 hence forth size_t str1cnt = minsize_t(cntSamas(SamasLR(toslp1(str1),Dict),partsLR), cntSamas(SamasRL(toslp1(str1),Dict),partsRL),FlagLR);//,SmasWords,SmasWords vector<string> wordConfusions; vector<int> wCindex; string str1New = loadWConfusionsNindex(str1,str2,ConfPmap,wordConfusions,wCindex); //cout << str1New << endl; printvecint(wCindex); printvecstr(wordConfusions); //apply confusions wordConfusions.size() .. 2 1 // lcs can give index of confusions say left are 3 6 9 // we need to try 3 6 9, 3 6, 6 9 ,3 9, 3 , 6 ,9 if any dec no of parts through min(samasLR,samasRL) stop and give suggestion //cout << str1New << endl; size_t sz = wordConfusions.size(); //cout << sz<< endl; size_t max = pow(2,sz) - 1; for(size_t i =max; i > 0; i--){ size_t mask = pow(2,sz-1); string newstring = str1New; for(size_t j =sz; j > 0; j--){ //generate new string using mask say 101 i.e. 210 :- if((mask & i) != 0){ replacestrcnf(newstring,wCindex[log2(mask)],wordConfusions[log2(mask)]);} mask = mask >> 1 ; } string newstring1 = removeSpaces(newstring.substr(1,newstring.size()-2)); size_t cntSamasNew; if(FlagLR) cntSamasNew = cntSamas(SamasRL(newstring1,Dict),partsRL); // ,SmasWords else cntSamasNew = cntSamas(SamasLR(newstring1,Dict),partsLR); // ,SmasWords //cout << cntSamasNew <<" "<< str1cnt<< endl; //Flag1stSuggGenerated :- if cnt 8 for str1 and <=8 for a suggestion then look for cnt <8 hence forth if(Flag1stSuggGenerated){if(cntSamasNew <= str1cnt) {twoOCRsugg = (newstring1); str1cnt = cntSamasNew; Flag1stSuggGenerated = 0;}} else {if(cntSamasNew < str1cnt) {twoOCRsugg = (newstring1); str1cnt = cntSamasNew;}} } //cout << toDev(twoOCRsugg)<<endl; wordConfusions.clear(); wCindex.clear(); return twoOCRsugg; //break; } string slpNPatternDict :: bestIG(string s1,string s2,map<string, int>& m1){ string s11 = s1; string s21 = s2; s1 = toslp1(s1); s2=toslp1(s2); string RL1 = SamasRL(s1,m1); string RLout1; size_t cRL1 = cntSamas(RL1,RLout1); string RL2 = SamasRL(s2,m1); string RLout2; size_t cRL2 = cntSamas(RL2,RLout2); string LR1 = SamasLR(s1,m1); string LRout1; size_t cLR1 = cntSamas(LR1,LRout1); string LR2 = SamasLR(s2,m1); string LRout2; size_t cLR2 = cntSamas(LR2,LRout2); bool lolz; if(minsize_t(cRL1,cLR1,lolz) < minsize_t(cRL2,cLR2,lolz)) return s11; else return s21; } //Sandhi Top Confusions void slpNPatternDict :: loadSandhiRules(string fileName, map<string, vector<string>>& SRules){ ifstream s(fileName); string sR1,sRl1, sRr1; while(s>>sR1) {s>>sRl1; s>>sRr1; SRules[sR1].push_back(sRl1 + " " + sRr1);} } void slpNPatternDict :: printSandhiRUles(map<string,vector<string> >& SRules){ for( map<string,vector<string> >::const_iterator ptr=SRules.begin(); ptr!=SRules.end(); ptr++) { string s = (ptr->first); cout << (s) << " -> "; for( vector<string>::const_iterator eptr=ptr->second.begin(); eptr!=ptr->second.end(); eptr++){ string s1 = *eptr; cout << (s1) << " | "; } cout << endl; } } bool slpNPatternDict :: SamasCheck(string OCRNew, map<string, int>& Dict){ if (OCRNew == "") return 1; if (Dict[OCRNew] > 0) return 1; //cout << endl<< "heres " << OCRNew << endl; size_t sz = OCRNew.size(); for(size_t ts = sz ; ts > 0; ts--){// Bapyopetam Bapy 0 4 10 string s1 = OCRNew.substr(0,ts); string rem = OCRNew.substr(ts,sz-ts); //cout << "s1 " << s1 << " rem " << rem << endl; if((Dict[s1] > 0) &&(s1.size() >3) &&(rem.size() >3))/*try && rem.size >3*/ return SamasCheck(rem,Dict); // apply ending with a to aH, ending with consonants say c to ca etc // if not 1st leftstarting with a to remove a } return 0; } bool slpNPatternDict :: SandhiCheck(string OCRNew, map<string, int>& Dict,map<string, vector<string>>& SRules){ // Sandhi Check //if (OCRNew == "") return 1; if (Dict[OCRNew] > 0) return 1; //cout << endl<< "hereS " << OCRNew << endl; size_t sz = OCRNew.size(); for(size_t ts = sz ; ts > 0; ts--){// Bapyopetam Bapy 0 4 10 string s1 = OCRNew.substr(0,ts); string rem = OCRNew.substr(ts,sz-ts); //cout << "S1 " << s1 << " " << ts << " " << sz << endl; if( (s1.size() >3)&&(rem.size() >2)){ //as r of S -> l+r will be added to rem //cout << "s1 " << s1 << endl; // applying o -> a u Sandhi rules i.e. k =1 for o, k = 2 for yu in yu -> yu -> i u | I u | size_t k = 1; vector<string> v = SRules[s1.substr(ts-k,k)]; size_t vsz = v.size(); //cout << " vsz " << vsz << endl; if(vsz > 0) { bool SandhiFlag = 0; for(size_t vt =0; vt < vsz; vt++) { istringstream s(v[vt]); string l,r; s>>l; s>>r; string s1new = s1.substr(0,s1.size()-1)+l; if((Dict[s1new] > 0) ){ //cout << "found " << s1new << endl; SandhiFlag = (SandhiFlag | SamasCheck(r+rem,Dict)); } else { SandhiFlag = (SandhiFlag | (SandhiCheck(s1new,Dict,SRules) & SamasCheck(r+rem,Dict)) | (SamasCheck(s1new,Dict) & SamasCheck(r+rem,Dict)));} //else }// for return SandhiFlag; }// if vsz >0 } } return 0; } //Sandhi rules // OCR Word = BApyopetam string slpNPatternDict :: generatePossibilitesNsuggest(string OCRWord,map<string,string>& TopConfusions,map<string,int>& TopConfusionsMask,map<string, int>& Dict, map<string, vector<string>>& SRules){ string OCRWordOrig = OCRWord; size_t sz = OCRWord.size() + 2; // one confusion one sandhi at a time size_t tSandhi = 0; for( size_t t2 =1; t2 < 4 ; t2++){ for( size_t t =0; t <sz- t2 + 1 ; t++){ OCRWord = "@" + OCRWordOrig + "#"; // apply a confusion string OCRNew = OCRWord; //cout << "OCRWord " << OCRWord << endl; size_t tc = t; while( tc < sz - t2 + 1) { string s1 = OCRWord.substr(tc,t2); //cout << s1<< " "<< tc << " " << t2 << endl; if (TopConfusionsMask[s1] > 0) { OCRNew = OCRWord; OCRNew.replace(tc,s1.size(),TopConfusions[s1]); t = tc; break; } else tc++; } //cout << "OCRWord1 " << OCRNew << endl; // apply Samas s OCRNew = OCRNew.substr(0,OCRNew.size()-1); OCRNew = OCRNew.substr(1,OCRNew.size()-1); //cout << "OCRWord2 " << OCRNew << endl; if (SamasCheck(OCRNew, Dict)) return OCRNew; // apply Sandhi S Rules if (SandhiCheck(OCRNew, Dict,SRules)) return OCRNew; } } return ""; }
41.321026
356
0.550408
493e6aa31a226a2337839854bbb7f925721783ea
1,602
cpp
C++
tests/DBCParserTest.cpp
aiekick/dbcppp
8f433e7b3ce5ee11aa6061ba82ba3cc4ddbbbfbe
[ "MIT" ]
93
2019-12-26T08:35:22.000Z
2022-03-29T07:30:30.000Z
tests/DBCParserTest.cpp
Raufoon/dbcppp
f6db52bbca5a2272804ccdd8e38955e5b6cd7abd
[ "MIT" ]
54
2020-02-26T23:12:09.000Z
2022-03-13T18:21:20.000Z
tests/DBCParserTest.cpp
ozzdemir/dbcppp
c7ea82b799c3dd945b399c75a6cf38fff6d61a4e
[ "MIT" ]
26
2020-02-01T00:46:10.000Z
2022-03-29T12:40:37.000Z
#include <fstream> #include <iomanip> #include <filesystem> #include "dbcppp/Network.h" #include "dbcppp/Network2Functions.h" #include "Config.h" #include "Catch2.h" TEST_CASE("DBCParserTest", "[]") { std::size_t i = 0; for (const auto& dbc_file : std::filesystem::directory_iterator(std::filesystem::path(TEST_FILES_PATH) / "dbc")) { //BOOST_TEST_CHECKPOINT("DBCParserTest: Testing file '" + dbc_file.path().string() + "'"); if (dbc_file.path().extension() != ".dbc") { continue; } std::cout << "Testing DBC grammar with file: " << dbc_file.path() << std::endl; auto dbc_file_tmp = dbc_file.path().string() + ".tmp"; std::unique_ptr<dbcppp::INetwork> spec; std::unique_ptr<dbcppp::INetwork> test; { std::ifstream dbc(dbc_file.path()); spec = dbcppp::INetwork::LoadDBCFromIs(dbc); std::ofstream tmp_dbc(dbc_file_tmp); bool open = tmp_dbc.is_open(); using namespace dbcppp::Network2DBC; tmp_dbc << std::setprecision(10); tmp_dbc << *spec << std::endl; } { std::ifstream dbc(dbc_file_tmp); test = dbcppp::INetwork::LoadDBCFromIs(dbc); REQUIRE(test); } auto error_msg = "Failed for " + std::to_string(i) + "th file ('" + dbc_file.path().string() + "')"; if (*spec != *test) { std::cout << error_msg << std::endl; } REQUIRE(*spec == *test); std::filesystem::remove(dbc_file_tmp); i++; } }
31.411765
116
0.553059
493fd10a81981d0e507a93a416dd54a150223854
3,692
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/content/CIntentHelper.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/content/CIntentHelper.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/content/CIntentHelper.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/content/CIntentHelper.h" #include "elastos/droid/ext/frameworkdef.h" namespace Elastos { namespace Droid { namespace Content { CAR_INTERFACE_IMPL(CIntentHelper, Singleton, IIntentHelper) CAR_SINGLETON_IMPL(CIntentHelper) ECode CIntentHelper::CreateChooser( /* [in] */ IIntent* target, /* [in] */ ICharSequence* title, /* [out] */ IIntent** intent) { VALIDATE_NOT_NULL(intent) AutoPtr<IIntent> it = Intent::CreateChooser(target, title); *intent = it; REFCOUNT_ADD(*intent) return NOERROR; } ECode CIntentHelper::MakeMainActivity( /* [in] */ IComponentName* mainActivity, /* [out] */ IIntent** intent) { VALIDATE_NOT_NULL(intent) AutoPtr<IIntent> it = Intent::MakeMainActivity(mainActivity); *intent = it; REFCOUNT_ADD(*intent) return NOERROR; } ECode CIntentHelper::MakeMainSelectorActivity( /* [in] */ const String& selectorAction, /* [in] */ const String& selectorCategory, /* [out] */ IIntent** intent) { VALIDATE_NOT_NULL(intent) AutoPtr<IIntent> it = Intent::MakeMainSelectorActivity(selectorAction, selectorCategory); *intent = it; REFCOUNT_ADD(*intent) return NOERROR; } ECode CIntentHelper::MakeRestartActivityTask( /* [in] */ IComponentName* mainActivity, /* [out] */ IIntent** intent) { VALIDATE_NOT_NULL(intent) AutoPtr<IIntent> it = Intent::MakeRestartActivityTask(mainActivity); *intent = it; REFCOUNT_ADD(*intent) return NOERROR; } ECode CIntentHelper::GetIntent( /* [in] */ const String& uri, /* [out] */ IIntent** intent) { return Intent::GetIntent(uri, intent); } ECode CIntentHelper::ParseUri( /* [in] */ const String& uri, /* [in] */ Int32 flags, /* [out] */ IIntent** intent) { return Intent::ParseUri(uri, flags, intent); } ECode CIntentHelper::GetIntentOld( /* [in] */ const String& uri, /* [out] */ IIntent** intent) { return Intent::GetIntentOld(uri, intent); } ECode CIntentHelper::ParseIntent( /* [in] */ IResources* resources, /* [in] */ IXmlPullParser* parser, /* [in] */ IAttributeSet* attrs, /* [out] */ IIntent** intent) { return Intent::ParseIntent(resources, parser, attrs, intent); } ECode CIntentHelper::RestoreFromXml( /* [in] */ IXmlPullParser* in, /* [out] */ IIntent** intent) { VALIDATE_NOT_NULL(intent) AutoPtr<IIntent> temp = Intent::RestoreFromXml(in); *intent = temp; REFCOUNT_ADD(*intent) return NOERROR; } ECode CIntentHelper::NormalizeMimeType( /* [in] */ const String& type, /* [out] */ String* mimeType) { VALIDATE_NOT_NULL(mimeType) *mimeType = Intent::NormalizeMimeType(type); return NOERROR; } ECode CIntentHelper::IsAccessUriMode( /* [in] */ Int32 modeFlags, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = Intent::IsAccessUriMode(modeFlags); return NOERROR; } } } }
26.753623
93
0.647887
494023c248b5d96d68510482a00fbafad820c649
19,717
cpp
C++
aby3-DB_tests/PermutaitonTests.cpp
vincehong/aby3
1a5277b37249545e967fc58a9235666a2453c104
[ "MIT" ]
121
2019-06-25T01:35:50.000Z
2022-03-24T12:53:17.000Z
aby3-DB_tests/PermutaitonTests.cpp
vincehong/aby3
1a5277b37249545e967fc58a9235666a2453c104
[ "MIT" ]
33
2020-01-21T16:47:09.000Z
2022-01-23T12:41:22.000Z
aby3-DB_tests/PermutaitonTests.cpp
vincehong/aby3
1a5277b37249545e967fc58a9235666a2453c104
[ "MIT" ]
36
2019-09-05T08:35:09.000Z
2022-01-14T11:57:22.000Z
#include <cryptoTools/Network/IOService.h> #include <cryptoTools/Network/Session.h> #include <cryptoTools/Network/Channel.h> #include <cryptoTools/Common/Matrix.h> #include <aby3-DB/OblvPermutation.h> #include <aby3-DB/OblvSwitchNet.h> #include <cryptoTools/Crypto/PRNG.h> #include "PermutaitonTests.h" #include <iomanip> using namespace oc; void Perm3p_overwrite_Test() { IOService ios; Session s01(ios, "127.0.0.1", SessionMode::Server, "01"); Session s10(ios, "127.0.0.1", SessionMode::Client, "01"); Session s02(ios, "127.0.0.1", SessionMode::Server, "02"); Session s20(ios, "127.0.0.1", SessionMode::Client, "02"); Session s12(ios, "127.0.0.1", SessionMode::Server, "12"); Session s21(ios, "127.0.0.1", SessionMode::Client, "12"); Channel chl01 = s01.addChannel(); Channel chl10 = s10.addChannel(); Channel chl02 = s02.addChannel(); Channel chl20 = s20.addChannel(); Channel chl12 = s12.addChannel(); Channel chl21 = s21.addChannel(); int rows = 1 << 16; int bytes = 16; std::vector<u32> perm(rows); for (u32 i = 0; i < perm.size(); ++i) perm[i] = i; PRNG prng(OneBlock); std::random_shuffle(perm.begin(), perm.end(), prng); Matrix<u8> mtx(rows, bytes); Matrix<u8> s1(rows, bytes); Matrix<u8> s2(rows, bytes); prng.get(mtx.data(), mtx.size()); //std::cout << std::endl; //for (u32 i = 0; i < mtx.rows(); ++i) //{ // std::cout << i << " -> " << perm[i] << " : "; // for (u32 j = 0; j < mtx.cols(); ++j) // { // std::cout << " " << std::hex << int(mtx(i, j)); // } // std::cout << std::endl; //} //auto t0 = std::thread([&]() { OblvPermutation p; auto perm2 = perm; p.program(chl02, chl01, perm2, prng, s1, "test"); }//); //std::cout << std::endl; //auto t1 = std::thread([&]() { OblvPermutation p; p.send(chl10, chl12, mtx, "test"); }//); //std::cout << std::endl; OblvPermutation p; p.recv(chl20, chl21, s2, rows, "test"); //t0.join(); //t1.join(); //std::cout << std::endl; //for (u32 i = 0; i < mtx.rows(); ++i) //{ // std::cout << i << " : "; // for (u32 j = 0; j < mtx.cols(); ++j) // { // std::cout << " " << std::hex << int(s1(i, j) ^ s2(i, j)); // } // std::cout << std::endl; //} bool failed = false; for (u32 i = 0; i < mtx.rows(); ++i) { for (u32 j = 0; j < mtx.cols(); ++j) { auto val = s1(perm[i], j) ^ s2(perm[i], j); if (mtx(i, j) != val) { std::cout << "mtx(" << i << ", " << j << ") != s1(" << perm[i] << ", " << j << ") ^ s2(" << perm[i] << ", " << j << ")" << std::endl; std::cout << " " << int(mtx(i, j)) << " != " << int(s1(perm[i], j)) << " ^ " << int(s2(perm[i], j)) << std::endl; std::cout << " " << int(mtx(i, j)) << " != " << int(s1(perm[i], j) ^ s2(perm[i], j)) << std::endl; failed = true; } } } if (failed) throw std::runtime_error(LOCATION); } void Perm3p_additive_Test() { IOService ios; Session s01(ios, "127.0.0.1", SessionMode::Server, "01"); Session s10(ios, "127.0.0.1", SessionMode::Client, "01"); Session s02(ios, "127.0.0.1", SessionMode::Server, "02"); Session s20(ios, "127.0.0.1", SessionMode::Client, "02"); Session s12(ios, "127.0.0.1", SessionMode::Server, "12"); Session s21(ios, "127.0.0.1", SessionMode::Client, "12"); Channel chl01 = s01.addChannel(); Channel chl10 = s10.addChannel(); Channel chl02 = s02.addChannel(); Channel chl20 = s20.addChannel(); Channel chl12 = s12.addChannel(); Channel chl21 = s21.addChannel(); int rows = 100; int bytes = 16; std::vector<u32> perm(rows); for (u32 i = 0; i < perm.size(); ++i) perm[i] = i; PRNG prng(OneBlock); std::random_shuffle(perm.begin(), perm.end(), prng); Matrix<u8> mtx(rows, bytes); Matrix<u8> s1(rows, bytes); Matrix<u8> s2(rows, bytes); prng.get(mtx.data(), mtx.size()); prng.get(s1.data(), s1.size()); s2 = s1; //std::cout << std::endl; //for (u32 i = 0; i < mtx.rows(); ++i) //{ // std::cout << i << " -> " << perm[i] << " : "; // for (u32 j = 0; j < mtx.cols(); ++j) // { // std::cout << " " << std::hex << int(mtx(i, j)); // } // std::cout << std::endl; //} //auto t0 = std::thread([&]() { OblvPermutation p; auto perm2 = perm; p.program(chl02, chl01, perm2, prng, s1, "test", OutputType::Additive); }//); //std::cout << std::endl; //auto t1 = std::thread([&]() { OblvPermutation p; p.send(chl10, chl12, mtx, "test"); }//); //std::cout << std::endl; OblvPermutation p; p.recv(chl20, chl21, s2, rows, "test", OutputType::Additive); //t0.join(); //t1.join(); //std::cout << std::endl; //for (u32 i = 0; i < mtx.rows(); ++i) //{ // std::cout << i << " : "; // for (u32 j = 0; j < mtx.cols(); ++j) // { // std::cout << " " << std::hex << int(s1(i, j) ^ s2(i, j)); // } // std::cout << std::endl; //} bool failed = false; for (u32 i = 0; i < mtx.rows(); ++i) { for (u32 j = 0; j < mtx.cols(); ++j) { auto val = s1(perm[i], j) ^ s2(perm[i], j); if (mtx(i, j) != val) { std::cout << "mtx(" << i << ", " << j << ") != s1(" << perm[i] << ", " << j << ") ^ s2(" << perm[i] << ", " << j << ")" << std::endl; std::cout << " " << int(mtx(i, j)) << " != " << int(s1(perm[i], j)) << " ^ " << int(s2(perm[i], j)) << std::endl; std::cout << " " << int(mtx(i, j)) << " != " << int(s1(perm[i], j) ^ s2(perm[i], j)) << std::endl; failed = true; } } } if (failed) throw std::runtime_error(LOCATION); } void Perm3p_subset_Test() { IOService ios; Session s01(ios, "127.0.0.1", SessionMode::Server, "01"); Session s10(ios, "127.0.0.1", SessionMode::Client, "01"); Session s02(ios, "127.0.0.1", SessionMode::Server, "02"); Session s20(ios, "127.0.0.1", SessionMode::Client, "02"); Session s12(ios, "127.0.0.1", SessionMode::Server, "12"); Session s21(ios, "127.0.0.1", SessionMode::Client, "12"); Channel chl01 = s01.addChannel(); Channel chl10 = s10.addChannel(); Channel chl02 = s02.addChannel(); Channel chl20 = s20.addChannel(); Channel chl12 = s12.addChannel(); Channel chl21 = s21.addChannel(); int rows = 100; int destRows = 50; int bytes = 2; std::vector<u32> perm(rows, -1); for (u32 i = 0; i < destRows; ++i) perm[i] = i; PRNG prng(OneBlock); std::random_shuffle(perm.begin(), perm.end(), prng); Matrix<u8> mtx(rows, bytes); Matrix<u8> s1(destRows, bytes); Matrix<u8> s2(destRows, bytes); prng.get(mtx.data(), mtx.size()); //std::cout << std::endl; //for (u32 i = 0; i < mtx.rows(); ++i) //{ // std::cout << i << " -> " << perm[i] << " : "; // for (u32 j = 0; j < mtx.cols(); ++j) // { // std::cout << " " << std::hex << int(mtx(i, j)); // } // std::cout << std::endl; //} //auto t0 = std::thread([&]() { OblvPermutation p; auto perm2 = perm; p.program(chl02, chl01, perm2, prng, s1, "test"); }//); //std::cout << std::endl; //auto t1 = std::thread([&]() { OblvPermutation p; p.send(chl10, chl12, mtx, "test"); }//); //std::cout << std::endl; OblvPermutation p; p.recv(chl20, chl21, s2, rows, "test"); //t0.join(); //t1.join(); //std::cout << std::endl; //for (u32 i = 0; i < mtx.rows(); ++i) //{ // std::cout << i << " : "; // for (u32 j = 0; j < mtx.cols(); ++j) // { // std::cout << " " << std::hex << int(s1(i, j) ^ s2(i, j)); // } // std::cout << std::endl; //} bool failed = false; for (u32 i = 0; i < rows; ++i) { if (perm[i] != -1) { auto s = perm[i]; for (u32 j = 0; j < bytes; ++j) { auto val = s1(s, j) ^ s2(s, j); if (mtx(i, j) != val) { std::cout << "mtx(" << i << ", " << j << ") != s1(" << s << ", " << j << ") ^ s2(" << s << ", " << j << ")" << std::endl; std::cout << " " << int(mtx(i, j)) << " != " << int(s1(s, j)) << " ^ " << int(s2(s, j)) << std::endl; std::cout << " " << int(mtx(i, j)) << " != " << int(s1(s, j) ^ s2(s, j)) << std::endl; failed = true; } } } } if (failed) throw std::runtime_error(LOCATION); } void switch_select_test() { IOService ios; Session s01(ios, "127.0.0.1", SessionMode::Server, "01"); Session s10(ios, "127.0.0.1", SessionMode::Client, "01"); Session s02(ios, "127.0.0.1", SessionMode::Server, "02"); Session s20(ios, "127.0.0.1", SessionMode::Client, "02"); Session s12(ios, "127.0.0.1", SessionMode::Server, "12"); Session s21(ios, "127.0.0.1", SessionMode::Client, "12"); Channel chl01 = s01.addChannel(); Channel chl10 = s10.addChannel(); Channel chl02 = s02.addChannel(); Channel chl20 = s20.addChannel(); Channel chl12 = s12.addChannel(); Channel chl21 = s21.addChannel(); int trials = 100; int srcSize = 40; int destSize = 20; int bytes = 1; Matrix<u8> src(srcSize, bytes); Matrix<u8> dest0(destSize, bytes), dest1(destSize, bytes); for (auto t = 9; t < trials; ++t) { PRNG prng(toBlock(t)); prng.get(src.data(), src.size()); //for (auto i = 0; i < src.rows(); ++i) //{ // std::cout << "s[" << i << "] = "; // for (auto j = 0; j < src.cols(); ++j) // { // std::cout << " " << std::setw(2) << std::hex << int(src(i, j)); // } // std::cout << std::endl << std::dec; //} OblvSwitchNet::Program prog; prog.init(srcSize, destSize); for (u64 i = 0; i < destSize; ++i) { prog.addSwitch(prng.get<u32>() % srcSize, (u32)i); //std::cout << "switch[" << i << "] = " << prog.mSrcDests[i][0] << " -> " << prog.mSrcDests[i][1] << std::endl; } auto t0 = std::thread([&]() { OblvSwitchNet snet("test"); snet.programSelect(chl02, chl01, prog, prng, dest0); }); auto t1 = std::thread([&]() { OblvSwitchNet snet("test"); snet.sendSelect(chl10, chl12, src); }); auto t2 = std::thread([&]() { OblvSwitchNet snet("test"); snet.recvSelect(chl20, chl21, dest1, srcSize); }); t0.join(); t1.join(); t2.join(); auto last = -1; bool print = false; if (print) std::cout << std::endl; bool failed = false; for (u64 i = 0; i < prog.mSrcDests.size(); ++i) { auto s = prog.mSrcDests[i].mSrc; if (s != last) { for (auto j = 0; j < bytes; ++j) { if ((dest0(i, j) ^ dest1(i, j)) != src(s, j)) { failed = true; } } if (print) { std::cout << "d[" << i << "] = "; for (auto j = 0; j < bytes; ++j) { if ((dest0(i, j) ^ dest1(i, j)) != src(s, j)) std::cout << Color::Red; std::cout << ' ' << std::setw(2) << std::hex << int(dest0(i, j) ^ dest1(i, j)) << ColorDefault; } std::cout << "\ns[" << i << "] = "; for (auto j = 0; j < bytes; ++j) std::cout << ' ' << std::setw(2) << std::hex << int(src(s, j)); std::cout << std::endl << std::dec; } last = s; } } if (failed) throw std::runtime_error(""); } } void switch_duplicate_test() { IOService ios; Session s01(ios, "127.0.0.1", SessionMode::Server, "01"); Session s10(ios, "127.0.0.1", SessionMode::Client, "01"); Session s02(ios, "127.0.0.1", SessionMode::Server, "02"); Session s20(ios, "127.0.0.1", SessionMode::Client, "02"); Session s12(ios, "127.0.0.1", SessionMode::Server, "12"); Session s21(ios, "127.0.0.1", SessionMode::Client, "12"); Channel chl01 = s01.addChannel(); Channel chl10 = s10.addChannel(); Channel chl02 = s02.addChannel(); Channel chl20 = s20.addChannel(); Channel chl12 = s12.addChannel(); Channel chl21 = s21.addChannel(); int trials = 100; int srcSize = 50; int destSize = srcSize /2; int bytes = 1; Matrix<u8> src(srcSize, bytes); Matrix<u8> dest0(destSize, bytes), dest1(destSize, bytes); for (auto t = 0; t < trials; ++t) { PRNG prng(toBlock(t)); prng.get(src.data(), src.size()); //for (auto i = 0; i < src.rows(); ++i) //{ // std::cout << "s[" << i << "] = "; // for (auto j = 0; j < src.cols(); ++j) // { // std::cout << " " << std::setw(2) << std::hex << int(src(i, j)); // } // std::cout << std::endl << std::dec; //} OblvSwitchNet::Program prog; prog.init(srcSize, destSize); for (u64 i = 0; i < destSize; ++i) { prog.addSwitch(prng.get<u32>() % srcSize, (u32)i); //prog.addSwitch(0, i); //std::cout << "switch[" << i << "] = " << prog.mSrcDests[i][0] << " -> " << prog.mSrcDests[i][1] << std::endl; } auto t0 = std::thread([&]() { setThreadName("t0"); OblvSwitchNet snet("test"); snet.programSelect(chl02, chl01, prog, prng, dest0); snet.programDuplicate(chl02, chl01, prog, prng, dest0); }); auto t1 = std::thread([&]() { setThreadName("t1"); OblvSwitchNet snet("test"); snet.sendSelect(chl10, chl12, src); snet.helpDuplicate(chl10, destSize, bytes); }); auto t2 = std::thread([&]() { setThreadName("t2"); OblvSwitchNet snet("test"); snet.recvSelect(chl20, chl21, dest1, srcSize); PRNG prng2(toBlock(585643)); snet.sendDuplicate(chl20, prng2, dest1); }); t0.join(); t1.join(); t2.join(); bool print = false; if (print) std::cout << std::endl; bool failed = false; for (u64 i = 0; i < prog.mSrcDests.size(); ++i) { auto s = prog.mSrcDests[i].mSrc; for (auto j = 0; j < bytes; ++j) { if ((dest0(i, j) ^ dest1(i, j)) != src(s, j)) { failed = true; } } if (print) { std::cout << "d[" << i << "] = "; for (auto j = 0; j < bytes; ++j) { if ((dest0(i, j) ^ dest1(i, j)) != src(s, j)) std::cout << Color::Red; std::cout << ' ' << std::setw(2) << std::hex << int(dest0(i, j) ^ dest1(i, j)) << ColorDefault; } std::cout << "\ns[" << i << "] = "; for (auto j = 0; j < bytes; ++j) std::cout << ' ' << std::setw(2) << std::hex << int(src(s, j)); std::cout << std::endl << std::dec; } } if (failed) throw std::runtime_error(""); } } void switch_full_test() { IOService ios; Session s01(ios, "127.0.0.1", SessionMode::Server, "01"); Session s10(ios, "127.0.0.1", SessionMode::Client, "01"); Session s02(ios, "127.0.0.1", SessionMode::Server, "02"); Session s20(ios, "127.0.0.1", SessionMode::Client, "02"); Session s12(ios, "127.0.0.1", SessionMode::Server, "12"); Session s21(ios, "127.0.0.1", SessionMode::Client, "12"); Channel chl01 = s01.addChannel(); Channel chl10 = s10.addChannel(); Channel chl02 = s02.addChannel(); Channel chl20 = s20.addChannel(); Channel chl12 = s12.addChannel(); Channel chl21 = s21.addChannel(); int trials = 100; int srcSize = 50; int destSize = srcSize / 2; int bytes = 1; Matrix<u8> src(srcSize, bytes); Matrix<u8> dest0(destSize, bytes), dest1(destSize, bytes); for (auto t = 0; t < trials; ++t) { PRNG prng(toBlock(t)); prng.get(src.data(), src.size()); //for (auto i = 0; i < src.rows(); ++i) //{ // std::cout << "s[" << i << "] = "; // for (auto j = 0; j < src.cols(); ++j) // { // std::cout << " " << std::setw(2) << std::hex << int(src(i, j)); // } // std::cout << std::endl << std::dec; //} OblvSwitchNet::Program prog; prog.init(srcSize, destSize); for (u64 i = 0; i < destSize; ++i) { prog.addSwitch(prng.get<u32>() % srcSize, (u32)i); //prog.addSwitch(0, i); //std::cout << "switch[" << i << "] = " << prog.mSrcDests[i][0] << " -> " << prog.mSrcDests[i][1] << std::endl; } auto t0 = std::thread([&]() { setThreadName("t0"); OblvSwitchNet snet("test"); snet.program(chl02, chl01, prog, prng, dest0); }); auto t1 = std::thread([&]() { setThreadName("t1"); OblvSwitchNet snet("test"); snet.sendRecv(chl10, chl12, src, dest1); }); auto t2 = std::thread([&]() { setThreadName("t2"); OblvSwitchNet snet("test"); PRNG prng2(toBlock(44444)); snet.help(chl20, chl21, prng2, destSize, srcSize, bytes); }); t0.join(); t1.join(); t2.join(); bool print = false; if (print) std::cout << std::endl; bool failed = false; for (u64 i = 0; i < prog.mSrcDests.size(); ++i) { auto s = prog.mSrcDests[i].mSrc; auto d = prog.mSrcDests[i].mDest; for (auto j = 0; j < bytes; ++j) { if ((dest0(d, j) ^ dest1(d, j)) != src(s, j)) { failed = true; } } if (print) { std::cout << "d[" << d << "] = "; for (auto j = 0; j < bytes; ++j) { if ((dest0(d, j) ^ dest1(d, j)) != src(s, j)) std::cout << Color::Red; std::cout << ' ' << std::setw(2) << std::hex << int(dest0(i, j) ^ dest1(i, j)) << ColorDefault; } std::cout << "\ns[" << s << "] = "; for (auto j = 0; j < bytes; ++j) std::cout << ' ' << std::setw(2) << std::hex << int(src(s, j)); std::cout << std::endl << std::dec; } } if (failed) throw std::runtime_error(""); } }
28.95301
149
0.4417
4940c95479a0bf4cba16f33b2ea42b63ea8fff66
484
cpp
C++
mod04/ex03/Ice.cpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
null
null
null
mod04/ex03/Ice.cpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
null
null
null
mod04/ex03/Ice.cpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
2
2021-01-31T13:52:11.000Z
2021-05-19T18:36:17.000Z
#include "Ice.hpp" /* CONSTRUCTION DESTRUCTION */ Ice::Ice() : AMateria("ice") {} Ice::~Ice() {} Ice::Ice(const Ice& other) : AMateria("ice") { *this = other; } Ice& Ice::operator=(const Ice& other) { AMateria::operator=(other); return *this; } /* MEMBER FUNCTIONS */ void Ice::use(ICharacter& target) { AMateria::use(target); std::cout << "* shoots an ice bolt at " << target.getName() << " *" << std::endl; } AMateria* Ice::clone() const { return new Ice(); }
20.166667
85
0.60124
4942e2b43f35c35e90cd20df07c2e4609f1c64b5
571
hpp
C++
Labs/AI/TicTacToe/src/SuperHeader.hpp
jadnohra/jad-pre-2015-dabblings
368cbd39c6371b3e48b0c67d9a83fc20eee41346
[ "MIT" ]
null
null
null
Labs/AI/TicTacToe/src/SuperHeader.hpp
jadnohra/jad-pre-2015-dabblings
368cbd39c6371b3e48b0c67d9a83fc20eee41346
[ "MIT" ]
null
null
null
Labs/AI/TicTacToe/src/SuperHeader.hpp
jadnohra/jad-pre-2015-dabblings
368cbd39c6371b3e48b0c67d9a83fc20eee41346
[ "MIT" ]
null
null
null
#ifndef __SuperHeader_hpp #define __SuperHeader_hpp #include <stdlib.h> #include <tchar.h> #include <assert.h> #include <algorithm> #define NOMINMAX #ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. #define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif #include "windows.h" #ifdef _DEBUG inline void softAssert(bool cond) { if (!cond) DebugBreak(); } #else inline void softAssert(bool cond) { } #endif #endif
16.794118
105
0.66725
494363cf5e51c77fae1c46c961b84dfed7424c3c
2,230
hpp
C++
include/Aether/Screen.hpp
NightYoshi370/Aether
87d2b81f5d3143e39c363a9c81c195d440d7a4e8
[ "MIT" ]
1
2021-02-04T07:27:46.000Z
2021-02-04T07:27:46.000Z
libs/Aether/include/Aether/Screen.hpp
tkgstrator/SeedHack
227566d993bdea7a2851a8fc664b539186509697
[ "MIT" ]
null
null
null
libs/Aether/include/Aether/Screen.hpp
tkgstrator/SeedHack
227566d993bdea7a2851a8fc664b539186509697
[ "MIT" ]
null
null
null
#ifndef AETHER_SCREEN_HPP #define AETHER_SCREEN_HPP #include "Aether/base/Container.hpp" #include <unordered_map> namespace Aether { /** * @brief A class that represents a screen layout * Stores all screen elements for a specific screen. */ class Screen : public Container { private: /** @brief Mappings for button presses to callback functions */ std::unordered_map<Button, std::function<void()> > pressFuncs; /** @brief Mappings for button releases to callback functions */ std::unordered_map<Button, std::function<void()> > releaseFuncs; public: /** * @brief Construct a new Screen object */ Screen(); /** * @brief Callback function when the screen is loaded */ virtual void onLoad(); /** * @brief Callback function when the screen is unloaded */ virtual void onUnload(); /** * @brief Assigns callback function for button press * @note Setting a button callback will block the event from * going to any other elements * * @param btn button to assign callback to * @param func function to assign as callback for button press */ void onButtonPress(Button btn, std::function<void()> func); /** * @brief Assigns callback function for button release * @note Setting a button callback will block the event from * going to any other elements * * @param btn button to assign callback to * @param func function to assign as callback for button release */ void onButtonRelease(Button btn, std::function<void()> func); /** * @brief Attempt event handling for an event that occured * * @param event event to handle * @return true if event was handled * @return false if event was not handled */ bool handleEvent(InputEvent *event); }; }; #endif
33.283582
76
0.54843
49475a843c90a7d747467bf3adc361e17e5b2497
736
cpp
C++
archives-departementales/Vraamm/TuioPion.cpp
S0nzero/iCreate2019
4126c1da4fcf226d43a064e1cd0081491dfc71a5
[ "MIT" ]
null
null
null
archives-departementales/Vraamm/TuioPion.cpp
S0nzero/iCreate2019
4126c1da4fcf226d43a064e1cd0081491dfc71a5
[ "MIT" ]
null
null
null
archives-departementales/Vraamm/TuioPion.cpp
S0nzero/iCreate2019
4126c1da4fcf226d43a064e1cd0081491dfc71a5
[ "MIT" ]
null
null
null
#include "TuioPion.h" TuioPion::TuioPion() { } TuioPion::~TuioPion() { } void TuioPion::addTuioObject(TUIO::TuioObject *tobj) { } void TuioPion::updateTuioObject(TUIO::TuioObject *tobj) { } void TuioPion::removeTuioObject(TUIO::TuioObject *tobj) { } void TuioPion::addTuioCursor(TUIO::TuioCursor *tcur) { } void TuioPion::updateTuioCursor(TUIO::TuioCursor *tcur) { } void TuioPion::removeTuioCursor(TUIO::TuioCursor *tcur) { } void TuioPion::addTuioBlob(TUIO::TuioBlob *tblb) { } void TuioPion::updateTuioBlob(TUIO::TuioBlob *tblb) { } void TuioPion::removeTuioBlob(TUIO::TuioBlob *tblb) { } void TuioPion::refresh(TUIO::TuioTime frameTime) { }
11.323077
56
0.653533
4948220c7d9e62f081bb794035cc497751a9a6c2
1,338
cpp
C++
main/choose-and-swap/choose-and-swap.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/choose-and-swap/choose-and-swap.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/choose-and-swap/choose-and-swap.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
#include <iostream> #include <string> #include <unordered_set> namespace { bool get_swappable_chars(const std::string& s, char& high, char& low) { constexpr auto none = '\0'; high = low = none; if (s.size() < 2u) return true; const auto istop = s.size() - 1u; std::unordered_set<char> noswap; for (std::string::size_type i {0u}; i != istop; ++i) { if (noswap.find(s[i]) != noswap.end()) continue; for (auto j = i; ++j != s.size(); ) { if (s[i] > s[j] && noswap.find(s[j]) == noswap.end() && (s[j] < low || low == none)) low = s[j]; } if (low != none) { high = s[i]; return true; } noswap.insert(s[i]); } return false; } void swap_chars(std::string& s, const char first, const char second) { for (char& c : s) { if (c == first) c = second; else if (c == second) c = first; } } } int main() { auto t = 0; for (std::cin >> t; t > 0; --t) { std::string s; std::cin >> s; char high, low; if (get_swappable_chars(s, high, low)) swap_chars(s, high, low); std::cout << s << '\n'; } }
23.892857
73
0.434978
4948f63c5fa04d8ea292d283e330409a91d25e3a
1,360
hpp
C++
inc/sexpr-ident.hpp
ryanvbissell/dslang
65379ca7bbefff0161d11343b742ac58452d37e7
[ "BSD-2-Clause" ]
null
null
null
inc/sexpr-ident.hpp
ryanvbissell/dslang
65379ca7bbefff0161d11343b742ac58452d37e7
[ "BSD-2-Clause" ]
null
null
null
inc/sexpr-ident.hpp
ryanvbissell/dslang
65379ca7bbefff0161d11343b742ac58452d37e7
[ "BSD-2-Clause" ]
null
null
null
// vim: set tabstop=2 softtabstop=2 shiftwidth=2 expandtab : /* * Copyright (c) 2014-2017, Ryan V. Bissell * All rights reserved. * * SPDX-License-Identifier: BSD-2-Clause * See the enclosed "LICENSE" file for exact license terms. */ #ifndef DSLANG_SEXPR_IDENT_HPP #define DSLANG_SEXPR_IDENT_HPP #include "sexpr.hpp" #include <string> namespace DSL { class Dialect; namespace detail { class SexprIdent CX_FINAL : public Sexpr { friend class CX::IntrusivePtr<SexprIdent>; public: SexprIdent(Context* sc, char const** input); std::string Write() const; /* static bool Match(Dialect const& dialect, char const* text); static Sexpr::Type Skip(Dialect const& dialect, char const** input); static SEXPR Parse(Dialect const& dialect, char const** input); */ protected: Type type() const override { return Sexpr::Type::IDENT; } Sexpr const* transmute(char const** input) const override; Sexpr const* eval(SexprEnv const* env) const override; private: std::string name_; virtual ~SexprIdent(); }; bool SexprIdent__Match(char const* text); Sexpr::Type SexprIdent__Skip(char const** input); Sexpr const* SexprIdent__Parse(Context* sc, char const** input); } // namespace detail using SexprIDENT = CX::IntrusivePtr<detail::SexprIdent>; } // namespace DSL #endif // DSLANG_SEXPR_IDENT_HPP
21.935484
72
0.710294
494fb36c2c886326770309f15d09cb54105344e4
1,363
cpp
C++
C++(Adv_CompSci)/AdvCompSci/quiz2nd6weeks.cpp
zacswolf/CompSciProjects
9dc8ff4969d852d6c649c427032e16f068003658
[ "MIT" ]
1
2016-09-12T16:10:12.000Z
2016-09-12T16:10:12.000Z
C++(Adv_CompSci)/AdvCompSci/quiz2nd6weeks.cpp
zaccool30/CompSciProjects
9dc8ff4969d852d6c649c427032e16f068003658
[ "MIT" ]
null
null
null
C++(Adv_CompSci)/AdvCompSci/quiz2nd6weeks.cpp
zaccool30/CompSciProjects
9dc8ff4969d852d6c649c427032e16f068003658
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <stdlib.h> using namespace std; class Manufacturer{ public: Manufacturer() { cout<< "E \n"; } Manufacturer(char code) { cout<< "D " << code << endl; } }; class LCDPanel: public Manufacturer{ public: LCDPanel(): Manufacturer('F') { cout<< "C \n"; } }; class Backlight: public Manufacturer{ public: Backlight() { Manufacturer('G'); cout << "B \n"; } }; class Display: public Backlight, public LCDPanel{ public: Display() : Backlight(){ cout << "A \n"; } }; class Record{ public: int value; }; class Rock { int hardness; int size; public: Rock() { cout << "Rock contructed" << endl; } }; int main(){ int a [] = { 16, 2, 77, 40, 12071 }; int a_length = sizeof(a) / sizeof(int); //cout << a_length << endl; int foo[] = {2, 4, 6, 8, 10}; int length = 4; for (int i=0; i <= length; i++){ //cout << i << " " << endl; } //Display h; Record** rec = new Record*[10]; for(int i=0; i< 10; i++) { rec[i] = new Record(); rec[i]->value = 0; } for (int i=0; i < 10; i++){ delete rec[i]; } delete[] rec; Rock stone; Rock *boulder; boulder = new Rock(); return 0; }
13.362745
50
0.487161
4953016766edc08efab4acd6241229c0075c519d
3,474
cpp
C++
depends/acransac/conditioning.cpp
mmrwizard/RenderMatch-1
a427138e6823675eaa76c693bc31a28566b4dcd8
[ "MIT" ]
null
null
null
depends/acransac/conditioning.cpp
mmrwizard/RenderMatch-1
a427138e6823675eaa76c693bc31a28566b4dcd8
[ "MIT" ]
null
null
null
depends/acransac/conditioning.cpp
mmrwizard/RenderMatch-1
a427138e6823675eaa76c693bc31a28566b4dcd8
[ "MIT" ]
1
2020-05-12T08:19:14.000Z
2020-05-12T08:19:14.000Z
// Copyright (c) 2010 libmv 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. // Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "conditioning.hpp" namespace openMVG { // HZ 4.4.4 pag.109 void PreconditionerFromPoints(const Mat &points, Mat3 *T) { Vec mean, variance; MeanAndVarianceAlongRows(points, &mean, &variance); double xfactor = sqrt(2.0 / variance(0)); double yfactor = sqrt(2.0 / variance(1)); // If variance is equal to 0.0 set scaling factor to identity. // -> Else it will provide nan value (because division by 0). if (variance(0) < 1e-8) xfactor = mean(0) = 1.0; if (variance(1) < 1e-8) yfactor = mean(1) = 1.0; *T << xfactor, 0, -xfactor * mean(0), 0, yfactor, -yfactor * mean(1), 0, 0, 1; } void PreconditionerFromPoints(int width, int height, Mat3 *T) { // Build the normalization matrix double dNorm = 1.0 / sqrt(static_cast<double>(width * height)); (*T) = Mat3::Identity(); (*T)(0, 0) = (*T)(1, 1) = dNorm; (*T)(0, 2) = -.5f * width * dNorm; (*T)(1, 2) = -.5 * height * dNorm; } void ApplyTransformationToPoints(const Mat &points, const Mat3 &T, Mat *transformed_points) { const Mat::Index n = points.cols(); transformed_points->resize(2, n); for (Mat::Index i = 0; i < n; ++i) { Vec3 in, out; in << points(0, i), points(1, i), 1; out = T * in; (*transformed_points)(0, i) = out(0) / out(2); (*transformed_points)(1, i) = out(1) / out(2); } } void NormalizePoints(const Mat &points, Mat *normalized_points, Mat3 *T, int width, int height) { PreconditionerFromPoints(width, height, T); ApplyTransformationToPoints(points, *T, normalized_points); } void NormalizePoints(const Mat &points, Mat *normalized_points, Mat3 *T) { PreconditionerFromPoints(points, T); ApplyTransformationToPoints(points, *T, normalized_points); } // Denormalize the results. See HZ page 109. void UnnormalizerT::Unnormalize(const Mat3 &T1, const Mat3 &T2, Mat3 *H) { *H = T2.transpose() * (*H) * T1; } // Denormalize the results. See HZ page 109. void UnnormalizerI::Unnormalize(const Mat3 &T1, const Mat3 &T2, Mat3 *H) { *H = T2.inverse() * (*H) * T1; } } // namespace openMVG
39.477273
109
0.678181
4953051a9c59971d6ec2529ea8a90a8789ebb2eb
5,339
cpp
C++
src/utils.cpp
molendijk/InfoClock
98719495800cd930d51c495e83b08ddf9b99fc5b
[ "MIT" ]
null
null
null
src/utils.cpp
molendijk/InfoClock
98719495800cd930d51c495e83b08ddf9b99fc5b
[ "MIT" ]
null
null
null
src/utils.cpp
molendijk/InfoClock
98719495800cd930d51c495e83b08ddf9b99fc5b
[ "MIT" ]
null
null
null
/* * utils.cpp * * Created on: 04.01.2017 * Author: Bartosz Bielawski */ #include <time.h> #include <stdio.h> #include <vector> #include <memory> #include "utils.h" #include "config.h" #include "Client.h" #include "Arduino.h" #include "FS.h" #include "DataStore.h" #include "WiFiUdp.h" #include "SyslogSender.h" #include "ESP8266WiFi.h" #include "tasks_utils.h" #include "LambdaTask.hpp" extern "C" { #include "user_interface.h" } uint16_t operator"" _s(long double seconds) {return seconds * 1000 / MS_PER_CYCLE;} uint16_t operator"" _s(unsigned long long int seconds) {return seconds * 1000 / MS_PER_CYCLE;} static char dateTimeBuffer[] = "1970-01-01T00:00:00"; static uint32_t startUpTime = 0; uint32_t getUpTime() { return time(nullptr) - startUpTime; } String getTime() { time_t now = time(nullptr); if (now == 0) { return "??:??:??"; } //this saves the first timestamp when it was nonzero (it's near start-up time) if (startUpTime == 0) { startUpTime = now; } String r; char localBuffer[10]; auto lt = localtime(&now); snprintf(localBuffer, sizeof(localBuffer), "%02d:%02d:%02d", lt->tm_hour, lt->tm_min, lt->tm_sec); r = localBuffer; return r; } static const std::vector<const char*> dayNames{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; //static const std::vector<const char*> dayNames{"Nd", "Pn", "Wt", "Sr", "Cz", "Pt", "Sb"}; String getDate() { time_t now = time(nullptr); String r; if (now == 0) { return r; } char localBuffer[20]; auto lt = localtime(&now); snprintf(localBuffer, sizeof(localBuffer), "%s %02d/%02d", dayNames[lt->tm_wday], lt->tm_mday, lt->tm_mon+1); r = localBuffer; return r; } static time_t previousDateTime = 0; const char* getDateTime() { time_t now = time(nullptr); if (now == previousDateTime) return dateTimeBuffer; auto lt = localtime(&now); snprintf(dateTimeBuffer, 32, "%04d-%02d-%02dT%02d:%02d:%02d", lt->tm_year-100+2000, lt->tm_mon+1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec); previousDateTime = now; return dateTimeBuffer; } const static char UUID_FORMAT[] PROGMEM = "%08x-%04x-4%03x-8%03x-%04x%08x"; static char UUID[36]; const char* generateRandomUUID() { uint32_t r1 = os_random(); uint32_t r2 = os_random(); uint32_t r3 = os_random(); uint32_t r4 = os_random(); sprintf_P(UUID, UUID_FORMAT, r1, r2 >> 16, r2 & 0xFFF, r3 >> 20, r3 & 0xFFFF, r4); return UUID; } void logPPrintf(char* format, ...) { char localBuffer[256]; va_list argList; va_start(argList, format); Serial.printf("%s-%09u - ", getDateTime(), ESP.getCycleCount()); vsnprintf(localBuffer, sizeof(localBuffer), format, argList); Serial.println(localBuffer); va_end(argList); } void logPrintfX(const String& app, const String& format, ...) { char localBuffer[256]; String a(app); va_list argList; va_start(argList, format); uint32_t bytes = snprintf(localBuffer, sizeof(localBuffer), "%s - %s: ", getDateTime(), a.c_str()); vsnprintf(localBuffer+bytes, sizeof(localBuffer)-bytes, format.c_str(), argList); Serial.println(localBuffer); syslogSend(app, localBuffer+bytes); va_end(argList); } bool checkFileSystem() { bool alreadyFormatted = SPIFFS.begin(); if (not alreadyFormatted) SPIFFS.format(); SPIFFS.end(); return alreadyFormatted; } void readConfigFromFlash() { SPIFFS.begin(); auto dir = SPIFFS.openDir(F("/config")); while (dir.next()) { auto f = dir.openFile("r"); auto value = f.readStringUntil('\n'); //skip the /config/ part of the path auto name = dir.fileName().substring(8); DataStore::value(name) = value; //logPrintf(F("RCFF: %s = %s"), name.c_str(), value.c_str()); } } String readConfigWithDefault(const String& name, const String& def) { auto v = readConfig(name); return v.length() != 0 ? v: def; } String readConfig(const String& name) { static bool once = true; if (once) { readConfigFromFlash(); once = false; } return DataStore::value(name); } void writeConfig(const String& name, const String& value) { auto f = SPIFFS.open(String(F("/config/")) +name, "w+"); f.print(value); f.print('\n'); f.close(); DataStore::value(name) = value; } int32_t getTimeZone() { return readConfig("timezone").toInt(); } int32_t timezone = 0; static const char uptimeFormat[] PROGMEM = "%dd%dh%dm%ds"; String dataSource(const char* name) { String result; if (DataStore::hasValue(name)) { result = DataStore::value(name); if (result) return result; } if (strcmp(name, "heap") == 0) return String(ESP.getFreeHeap()) + " B"; if (strcmp(name, "version") == 0) return versionString; if (strcmp(name, "essid") == 0) return WiFi.SSID(); if (strcmp(name, "mac") == 0) return WiFi.macAddress(); if (strcmp(name, "uptime") == 0) { uint32_t ut = getUpTime(); uint32_t d = ut / (24 * 3600); ut -= d * 24 * 3600; uint32_t h = ut / 3600; ut -= h * 3600; uint32_t m = ut / 60; ut -= m * 60; uint32_t s = ut; char buf[64]; snprintf_P(buf, sizeof(buf), uptimeFormat, d, h, m, s); return String(buf); } return "?"; } void rebootClock() { getDisplayTask().pushMessage("Rebooting...", 5_s, false); logPrintfX(F("WS"), F("Rebooting in 5 seconds...")); LambdaTask* lt = new LambdaTask([](){ESP.restart();}); addTask(lt, TaskDescriptor::ENABLED); lt->sleep(5_s); }
19.067857
100
0.65649
495489fcb847b90b12ad90cef1f5bc51d903b3c3
691
cpp
C++
test/unit/api/terminal.cpp
jfalcou/nucog
186808bec04af4f1138bc5362510fffbe690fdd3
[ "MIT" ]
1
2022-02-13T20:11:06.000Z
2022-02-13T20:11:06.000Z
test/unit/api/terminal.cpp
jfalcou/nucog
186808bec04af4f1138bc5362510fffbe690fdd3
[ "MIT" ]
null
null
null
test/unit/api/terminal.cpp
jfalcou/nucog
186808bec04af4f1138bc5362510fffbe690fdd3
[ "MIT" ]
null
null
null
//================================================================================================== /** NuCoG - Numerical Code Generator Copyright : NuCoG Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include "test.hpp" #include <nucog/expr/terminal.hpp> TTS_CASE( "Check terminal properties" ) { using namespace nucog::literal; auto s1 = $(x_); TTS_EQUAL( s1.arity(), 0 ); TTS_EQUAL( s1.tag() , nucog::tags::terminal_{} ); TTS_EQUAL( s1.value(), "x_"_sym ); TTS_EQUAL( s1.value().str(), "x_" ); }
31.409091
100
0.413893
495848907d3023ec87db4db2dde46671f499404e
3,311
cpp
C++
src/chess/Loc.cpp
owengage/chess
777ba282c66ce750a1f1604483b14a99b0122eba
[ "Unlicense" ]
null
null
null
src/chess/Loc.cpp
owengage/chess
777ba282c66ce750a1f1604483b14a99b0122eba
[ "Unlicense" ]
null
null
null
src/chess/Loc.cpp
owengage/chess
777ba282c66ce750a1f1604483b14a99b0122eba
[ "Unlicense" ]
null
null
null
#include <chess/Loc.h> #include <perf/StackVector.h> #include <unordered_map> using chess::LocInvalid; using chess::Loc; using chess::Sign; namespace { std::vector<Loc> create_all_locs() { std::vector<Loc> all; all.reserve(static_cast<std::size_t>(Loc::board_size)); for (int y = 0; y < Loc::side_size; ++y) { for (int x = 0; x < Loc::side_size; ++x) { all.emplace_back(x, y); } } return all; } perf::StackVector<Loc, Loc::side_size> generate_direction(Loc origin, Sign x, Sign y) { auto locs = perf::StackVector<Loc, 8>{}; auto sign_to_hops = [](Sign sign, int start) { switch (sign) { case Sign::positive: return Loc::side_size - 1 - start; case Sign::none: return Loc::side_size - 1; case Sign::negative: return start; } }; auto max_hops_x = sign_to_hops(x, origin.x()); auto max_hops_y = sign_to_hops(y, origin.y()); auto max_hops = std::min(max_hops_x, max_hops_y); auto hop = static_cast<int>(y)*Loc::side_size + static_cast<int>(x); auto current = origin.index(); for (int i = 0; i < max_hops; ++i) { current += hop; locs.push_back(Loc{current}); } return locs; } std::size_t direction_lookup_index(Loc loc, Sign x, Sign y) { auto loc_part = loc.index() << 4; auto x_part = (static_cast<int>(x) + 1) << 2; auto y_part = (static_cast<int>(y) + 1); return loc_part | x_part | y_part; } static constexpr std::size_t direction_lookup_size = (64 << 4) + (2 << 2) + 2 + 1; std::array<perf::StackVector<Loc, 8>, direction_lookup_size> generate_direction_lookup_map() { std::array<perf::StackVector<Loc, 8>, direction_lookup_size> map; std::array<Sign, 3> signs = {Sign::positive, Sign::none, Sign::negative}; for (auto loc : Loc::all_squares()) { for (auto x : signs) { for (auto y : signs) { auto key = direction_lookup_index(loc, x, y); auto value = generate_direction(loc, x, y); map[key] = value; } } } return map; } auto direction_lookup = generate_direction_lookup_map(); } LocInvalid::LocInvalid(int x, int y) : std::runtime_error{"Invalid Loc m_x=" + std::to_string(x) + ", y=" + std::to_string(y)} {} std::vector<Loc> Loc::row(int y) { std::vector<Loc> locs; locs.reserve(side_size); for (int i = 0; i < side_size; ++i) { locs.emplace_back(i, y); } return locs; } std::vector<Loc> const& Loc::all_squares() { static std::vector<Loc> all = create_all_locs(); return all; } perf::StackVector<Loc, Loc::side_size> Loc::direction(Loc origin, Sign x, Sign y) { return direction_lookup[direction_lookup_index(origin, x, y)]; } bool chess::operator==(Loc lhs, Loc rhs) { return lhs.m_index == rhs.m_index; } bool chess::operator!=(Loc lhs, Loc rhs) { return !(lhs == rhs); }
26.488
126
0.536998
4958a96e54b627eab4400680cdac314ae51a30c0
9,803
cpp
C++
src/stellar/stellar.arg_parser.cpp
marehr/dream_stellar
03ffc33cba4336d585108a22c8e166d0fbd7ac4b
[ "BSD-3-Clause" ]
null
null
null
src/stellar/stellar.arg_parser.cpp
marehr/dream_stellar
03ffc33cba4336d585108a22c8e166d0fbd7ac4b
[ "BSD-3-Clause" ]
16
2021-11-12T16:42:35.000Z
2022-01-11T15:28:23.000Z
src/stellar/stellar.arg_parser.cpp
marehr/dream_stellar
03ffc33cba4336d585108a22c8e166d0fbd7ac4b
[ "BSD-3-Clause" ]
null
null
null
#include <stellar/app/stellar.arg_parser.hpp> #include <seqan/seq_io.h> namespace stellar { namespace app { /////////////////////////////////////////////////////////////////////////////// // Parses options from command line parser and writes them into options object ArgumentParser::ParseResult _parseOptions(ArgumentParser const & parser, StellarOptions & options) { getArgumentValue(options.databaseFile, parser, 0); getArgumentValue(options.queryFile, parser, 1); // output options getOptionValue(options.outputFile, parser, "out"); getOptionValue(options.disabledQueriesFile, parser, "outDisabled"); getOptionValue(options.noRT, parser, "no-rt"); CharString tmp = options.outputFile; toLower(tmp); if (endsWith(tmp, ".gff")) options.outputFormat = "gff"; else if (endsWith(tmp, ".txt")) options.outputFormat = "txt"; // main options getOptionValue(options.qGram, parser, "kmer"); getOptionValue(options.minLength, parser, "minLength"); getOptionValue(options.epsilon, parser, "epsilon"); getOptionValue(options.xDrop, parser, "xDrop"); getOptionValue(options.alphabet, parser, "alphabet"); getOptionValue(options.threadCount, parser, "threads"); if (isSet(parser, "forward") && !isSet(parser, "reverse")) options.reverse = false; if (!isSet(parser, "forward") && isSet(parser, "reverse")) options.forward = false; CharString verificationMethod; getOptionValue(verificationMethod, parser, "verification"); if (verificationMethod == to_string(StellarVerificationMethod{AllLocal{}})) options.verificationMethod = StellarVerificationMethod{AllLocal{}}; else if (verificationMethod == to_string(StellarVerificationMethod{BestLocal{}})) options.verificationMethod = StellarVerificationMethod{BestLocal{}}; else if (verificationMethod == to_string(StellarVerificationMethod{BandedGlobal{}})) options.verificationMethod = StellarVerificationMethod{BandedGlobal{}}; else if (verificationMethod == to_string(StellarVerificationMethod{BandedGlobalExtend{}})) options.verificationMethod = StellarVerificationMethod{BandedGlobalExtend{}}; else { std::cerr << "Invalid parameter value: Please choose one of the --verification={exact, bestLocal, bandedGlobal, bandedGlobalExtend}" << std::endl; return ArgumentParser::PARSE_ERROR; } getOptionValue(options.disableThresh, parser, "disableThresh"); getOptionValue(options.numMatches, parser, "numMatches"); getOptionValue(options.compactThresh, parser, "sortThresh"); getOptionValue(options.maxRepeatPeriod, parser, "repeatPeriod"); getOptionValue(options.minRepeatLength, parser, "repeatLength"); getOptionValue(options.qgramAbundanceCut, parser, "abundanceCut"); getOptionValue(options.verbose, parser, "verbose"); if (isSet(parser, "kmer") && options.qGram >= 1 / options.epsilon) { std::cerr << "Invalid parameter value: Please choose q-gram length lower than 1/epsilon." << std::endl; return ArgumentParser::PARSE_ERROR; } if (options.numMatches > options.compactThresh) { std::cerr << "Invalid parameter values: Please choose numMatches <= sortThresh." << std::endl; return ArgumentParser::PARSE_ERROR; } return ArgumentParser::PARSE_OK; } /////////////////////////////////////////////////////////////////////////////// // Set-Up of Argument Parser void _setParser(ArgumentParser & parser) { setShortDescription(parser, "the SwifT Exact LocaL AligneR"); setDate(parser, SEQAN_DATE); setVersion(parser, SEQAN_APP_VERSION " [" SEQAN_REVISION "]"); setCategory(parser, "Local Alignment"); addUsageLine(parser, "[\\fIOPTIONS\\fP] <\\fIFASTA FILE 1\\fP> <\\fIFASTA FILE 2\\fP>"); addDescription(parser, "STELLAR implements the SWIFT filter algorithm (Rasmussen et al., 2006) " "and a verification step for the SWIFT hits that applies local alignment, " "gapped X-drop extension, and extraction of the longest epsilon-match."); addDescription(parser, "Input to STELLAR are two files, each containing one or more sequences " "in FASTA format. Each sequence from file 1 will be compared to each " "sequence in file 2. The sequences from file 1 are used as database, the " "sequences from file 2 as queries."); addDescription(parser, "(c) 2010-2012 by Birte Kehr"); addArgument(parser, ArgParseArgument(ArgParseArgument::INPUT_FILE, "FASTA FILE 1")); setValidValues(parser, 0, "fa fasta"); // allow only fasta files as input addArgument(parser, ArgParseArgument(ArgParseArgument::INPUT_FILE, "FASTA FILE 2")); setValidValues(parser, 1, "fa fasta"); // allow only fasta files as input // Add threads option. addOption(parser, ArgParseOption("t", "threads", "Specify the number of threads to use.", ArgParseOption::INTEGER)); setMinValue(parser, "threads", "1"); setDefaultValue(parser, "threads", "1"); addSection(parser, "Main Options"); addOption(parser, ArgParseOption("e", "epsilon", "Maximal error rate (max 0.25).", ArgParseArgument::DOUBLE)); setDefaultValue(parser, "e", "0.05"); setMinValue(parser, "e", "0.0000001"); setMaxValue(parser, "e", "0.25"); addOption(parser, ArgParseOption("l", "minLength", "Minimal length of epsilon-matches.", ArgParseArgument::INTEGER)); setDefaultValue(parser, "l", "100"); setMinValue(parser, "l", "0"); addOption(parser, ArgParseOption("f", "forward", "Search only in forward strand of database.")); addOption(parser, ArgParseOption("r", "reverse", "Search only in reverse complement of database.")); addOption(parser, ArgParseOption("a", "alphabet", "Alphabet type of input sequences (dna, rna, dna5, rna5, protein, char).", ArgParseArgument::STRING)); setValidValues(parser, "a", "dna dna5 rna rna5 protein char"); addOption(parser, ArgParseOption("v", "verbose", "Set verbosity mode.")); addSection(parser, "Filtering Options"); addOption(parser, ArgParseOption("k", "kmer", "Length of the q-grams (max 32).", ArgParseArgument::INTEGER)); setMinValue(parser, "k", "1"); setMaxValue(parser, "k", "32"); addOption(parser, ArgParseOption("rp", "repeatPeriod", "Maximal period of low complexity repeats to be filtered.", ArgParseArgument::INTEGER)); setDefaultValue(parser, "rp", "1"); addOption(parser, ArgParseOption("rl", "repeatLength", "Minimal length of low complexity repeats to be filtered.", ArgParseArgument::INTEGER)); setDefaultValue(parser, "rl", "1000"); addOption(parser, ArgParseOption("c", "abundanceCut", "k-mer overabundance cut ratio.", ArgParseArgument::DOUBLE)); setDefaultValue(parser, "c", "1"); setMinValue(parser, "c", "0"); setMaxValue(parser, "c", "1"); addSection(parser, "Verification Options"); addOption(parser, ArgParseOption("x", "xDrop", "Maximal x-drop for extension.", ArgParseArgument::DOUBLE)); setDefaultValue(parser, "x", "5"); addOption(parser, ArgParseOption("vs", "verification", "Verification strategy: exact or bestLocal or bandedGlobal", ArgParseArgument::STRING)); //addHelpLine(parser, "exact = compute and extend all local alignments in SWIFT hits"); //addHelpLine(parser, "bestLocal = compute and extend only best local alignment in SWIFT hits"); //addHelpLine(parser, "bandedGlobal = banded global alignment on SWIFT hits"); setDefaultValue(parser, "vs", "exact"); setValidValues(parser, "vs", "exact bestLocal bandedGlobal"); addOption(parser, ArgParseOption("dt", "disableThresh", "Maximal number of verified matches before disabling verification for one query " "sequence (default infinity).", ArgParseArgument::INTEGER)); setMinValue(parser, "dt", "0"); addOption(parser, ArgParseOption("n", "numMatches", "Maximal number of kept matches per query and database. If STELLAR finds more matches, " "only the longest ones are kept.", ArgParseArgument::INTEGER)); setDefaultValue(parser, "n", "50"); addOption(parser, ArgParseOption("s", "sortThresh", "Number of matches triggering removal of duplicates. Choose a smaller value for saving " "space.", ArgParseArgument::INTEGER)); setDefaultValue(parser, "s", "500"); addSection(parser, "Output Options"); addOption(parser, ArgParseOption("o", "out", "Name of output file.", ArgParseArgument::OUTPUT_FILE)); setValidValues(parser, "o", "gff txt"); setDefaultValue(parser, "o", "stellar.gff"); addOption(parser, ArgParseOption("od", "outDisabled", "Name of output file for disabled query sequences.", ArgParseArgument::OUTPUT_FILE)); setValidValues(parser, "outDisabled", seqan::SeqFileOut::getFileExtensions()); setDefaultValue(parser, "od", "stellar.disabled.fasta"); addOption(parser, ArgParseOption("no-rt", "suppress-runtime-printing", "Suppress printing running time.")); hideOption(parser, "no-rt"); addTextSection(parser, "References"); addText(parser, "Kehr, B., Weese, D., Reinert, K.: STELLAR: fast and exact local alignments. BMC Bioinformatics, " "12(Suppl 9):S15, 2011."); } } // namespace stellar::app } // namespace stellar
50.530928
154
0.656738
4958e0e4495d1dcfdd543aa69b57e04b3080d15d
542
cpp
C++
leetcode/1328. Break a Palindrome/s1.cpp
joycse06/LeetCode-1
ad105bd8c5de4a659c2bbe6b19f400b926c82d93
[ "Fair" ]
1
2021-02-11T01:23:10.000Z
2021-02-11T01:23:10.000Z
leetcode/1328. Break a Palindrome/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
1
2021-08-08T18:44:24.000Z
2021-08-08T18:44:24.000Z
leetcode/1328. Break a Palindrome/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
1
2021-03-25T17:11:14.000Z
2021-03-25T17:11:14.000Z
// OJ: https://leetcode.com/problems/break-a-palindrome/ // Author: github.com/lzl124631x // Time: O(N) // Space: O(1) class Solution { public: string breakPalindrome(string palindrome) { int N = palindrome.size(), end = N / 2; for (int i = 0; i < end; ++i) { if (palindrome[i] != 'a') { palindrome[i] = 'a'; return palindrome; } } if (N > 1) { palindrome[N - 1] = 'b'; return palindrome; } return ""; } };
25.809524
56
0.46679
495ad89e432ab9f0af10b5534737b962cd0de0d5
441
cpp
C++
class/constructors.cpp
Abhilekhgautam/Cpp-college
3101cb061e36eee9d42226a8cfaf86ad5c695ef2
[ "CC0-1.0" ]
1
2021-07-22T08:38:25.000Z
2021-07-22T08:38:25.000Z
class/constructors.cpp
Abhilekhgautam/Cpp-college
3101cb061e36eee9d42226a8cfaf86ad5c695ef2
[ "CC0-1.0" ]
null
null
null
class/constructors.cpp
Abhilekhgautam/Cpp-college
3101cb061e36eee9d42226a8cfaf86ad5c695ef2
[ "CC0-1.0" ]
null
null
null
/* A c++ program to describe "objects are destroyed int reverse order of their creation"*/ #include<iostream> class Table{ public: Table(){std::cout<<"Object Created"<<'\n';} ~Table(){std::cout<<"Object Destoyed"<<'\n';} }; void f(int i) { Table aa; Table bb; if(i>0){ //cc will be created after bb and destroyed before dd is created Table cc; } Table dd; } int main(){ f(1); return 0; }
17.64
90
0.589569
495d1ce5531b5f88d17985d2c1a900531e11b56a
484
cpp
C++
src/core/test/src/net/test_Socket.cpp
SimpleTalkCpp/libsita
e0c13f16cebf799f0d57b8345d21de7407f59e2b
[ "MIT" ]
2
2021-03-19T13:19:27.000Z
2021-04-03T17:42:30.000Z
src/core/test/src/net/test_Socket.cpp
SimpleTalkCpp/libsita
e0c13f16cebf799f0d57b8345d21de7407f59e2b
[ "MIT" ]
null
null
null
src/core/test/src/net/test_Socket.cpp
SimpleTalkCpp/libsita
e0c13f16cebf799f0d57b8345d21de7407f59e2b
[ "MIT" ]
null
null
null
#include <sita_core/base/UnitTest.h> #include <sita_core/net/Socket.h> namespace sita { class Test_Socket : public UnitTestBase { public: void test_resolveIPv4() { Vector<int> a; IPv4 ip; ip.resolve("localhost"); SITA_DUMP_VAR(ip); SITA_TEST_CHECK(ip == IPv4(127,0,0,1)); SITA_TEST_CHECK_SLIENT(ip == IPv4(127,0,0,1)); } }; } // namespace void test_Socket() { using namespace sita; SITA_TEST_CASE(Test_Socket, test_resolveIPv4()); }
17.925926
50
0.663223
495d6d0beddca557ede7775b6206744dafd4081b
582
cpp
C++
snippets/cpp/VS_Snippets_Data/Classic WebData XmlElement.SetAttributeNode1 Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-03-12T19:26:36.000Z
2022-01-10T21:45:33.000Z
snippets/cpp/VS_Snippets_Data/Classic WebData XmlElement.SetAttributeNode1 Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_Data/Classic WebData XmlElement.SetAttributeNode1 Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
// <Snippet1> #using <System.Xml.dll> using namespace System; using namespace System::IO; using namespace System::Xml; int main() { XmlDocument^ doc = gcnew XmlDocument; doc->LoadXml( "<book xmlns:bk='urn:samples' bk:ISBN='1-861001-57-5'><title>Pride And Prejudice</title></book>" ); XmlElement^ root = doc->DocumentElement; // Add a new attribute. XmlAttribute^ attr = root->SetAttributeNode( "genre", "urn:samples" ); attr->Value = "novel"; Console::WriteLine( "Display the modified XML..." ); Console::WriteLine( doc->InnerXml ); } // </Snippet1>
25.304348
116
0.670103
495d74a4b2c72b6b43a2f4ca7d741b10949046a2
5,119
cpp
C++
src/modules/MouseUtils/FindMyMouse/dllmain.cpp
szlatkow/PowerToys
e62df46c6181551e80b7ce2cf85f03beccbfadf2
[ "MIT" ]
3
2021-11-21T03:03:41.000Z
2021-11-21T23:57:28.000Z
src/modules/MouseUtils/FindMyMouse/dllmain.cpp
szlatkow/PowerToys
e62df46c6181551e80b7ce2cf85f03beccbfadf2
[ "MIT" ]
9
2021-05-12T17:12:35.000Z
2021-10-30T14:57:56.000Z
src/modules/MouseUtils/FindMyMouse/dllmain.cpp
szlatkow/PowerToys
e62df46c6181551e80b7ce2cf85f03beccbfadf2
[ "MIT" ]
2
2021-05-26T09:02:21.000Z
2021-05-26T09:02:22.000Z
#include "pch.h" #include <interface/powertoy_module_interface.h> #include <common/SettingsAPI/settings_objects.h> #include "trace.h" #include "FindMyMouse.h" #include <thread> #include <common/utils/logger_helper.h> namespace { const wchar_t JSON_KEY_PROPERTIES[] = L"properties"; const wchar_t JSON_KEY_VALUE[] = L"value"; const wchar_t JSON_KEY_DO_NOT_ACTIVATE_ON_GAME_MODE[] = L"do_not_activate_on_game_mode"; } extern "C" IMAGE_DOS_HEADER __ImageBase; HMODULE m_hModule; BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { m_hModule = hModule; switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: Trace::RegisterProvider(); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: Trace::UnregisterProvider(); break; } return TRUE; } // The PowerToy name that will be shown in the settings. const static wchar_t* MODULE_NAME = L"FindMyMouse"; // Add a description that will we shown in the module settings page. const static wchar_t* MODULE_DESC = L"Focus the mouse pointer"; // Implement the PowerToy Module Interface and all the required methods. class FindMyMouse : public PowertoyModuleIface { private: // The PowerToy state. bool m_enabled = false; // Load initial settings from the persisted values. void init_settings(); // Helper function to extract the settings void parse_settings(PowerToysSettings::PowerToyValues& settings); public: // Constructor FindMyMouse() { LoggerHelpers::init_logger(MODULE_NAME, L"ModuleInterface", LogSettings::findMyMouseLoggerName); init_settings(); }; // Destroy the powertoy and free memory virtual void destroy() override { delete this; } // Return the localized display name of the powertoy virtual const wchar_t* get_name() override { return MODULE_NAME; } // Return the non localized key of the powertoy, this will be cached by the runner virtual const wchar_t* get_key() override { return MODULE_NAME; } // Return JSON with the configuration options. virtual bool get_config(wchar_t* buffer, int* buffer_size) override { HINSTANCE hinstance = reinterpret_cast<HINSTANCE>(&__ImageBase); // Create a Settings object. PowerToysSettings::Settings settings(hinstance, get_name()); settings.set_description(MODULE_DESC); return settings.serialize_to_buffer(buffer, buffer_size); } // Signal from the Settings editor to call a custom action. // This can be used to spawn more complex editors. virtual void call_custom_action(const wchar_t* action) override { } // Called by the runner to pass the updated settings values as a serialized JSON. virtual void set_config(const wchar_t* config) override { try { // Parse the input JSON string. PowerToysSettings::PowerToyValues values = PowerToysSettings::PowerToyValues::from_json_string(config, get_key()); parse_settings(values); values.save_to_settings_file(); } catch (std::exception&) { // Improper JSON. } } // Enable the powertoy virtual void enable() { m_enabled = true; Trace::EnableFindMyMouse(true); std::thread([]() { FindMyMouseMain(m_hModule); }).detach(); } // Disable the powertoy virtual void disable() { m_enabled = false; Trace::EnableFindMyMouse(false); FindMyMouseDisable(); } // Returns if the powertoys is enabled virtual bool is_enabled() override { return m_enabled; } }; // Load the settings file. void FindMyMouse::init_settings() { try { // Load and parse the settings file for this PowerToy. PowerToysSettings::PowerToyValues settings = PowerToysSettings::PowerToyValues::load_from_settings_file(FindMyMouse::get_key()); parse_settings(settings); } catch (std::exception&) { // Error while loading from the settings file. Let default values stay as they are. } } void FindMyMouse::parse_settings(PowerToysSettings::PowerToyValues& settings) { FindMyMouseSetDoNotActivateOnGameMode(true); auto settingsObject = settings.get_raw_json(); if (settingsObject.GetView().Size()) { try { auto jsonPropertiesObject = settingsObject.GetNamedObject(JSON_KEY_PROPERTIES).GetNamedObject(JSON_KEY_DO_NOT_ACTIVATE_ON_GAME_MODE); FindMyMouseSetDoNotActivateOnGameMode((bool)jsonPropertiesObject.GetNamedBoolean(JSON_KEY_VALUE)); } catch (...) { Logger::warn("Failed to get 'do not activate on game mode' setting"); } } else { Logger::info("Find My Mouse settings are empty"); } } extern "C" __declspec(dllexport) PowertoyModuleIface* __cdecl powertoy_create() { return new FindMyMouse(); }
27.521505
145
0.671616
4962d1a74ef7c19f1b044641bc6bbca98bedcb01
2,311
cc
C++
solutions/001-025/11/main.cc
PysKa-Ratzinger/personal_project_euler_solutions
ff05c38f3c9cbcd4d6f09f81034bc299c7144476
[ "MIT" ]
1
2019-04-19T01:05:07.000Z
2019-04-19T01:05:07.000Z
solutions/001-025/11/main.cc
PysKa-Ratzinger/personal_project_euler_solutions
ff05c38f3c9cbcd4d6f09f81034bc299c7144476
[ "MIT" ]
null
null
null
solutions/001-025/11/main.cc
PysKa-Ratzinger/personal_project_euler_solutions
ff05c38f3c9cbcd4d6f09f81034bc299c7144476
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFER_SZ 512 #define ROWS 20 #define COLS 20 bool isNumber(int character){ return character >= '0' && character <= '9'; } unsigned long magic2(int grid[ROWS][COLS]){ unsigned long res = 0; unsigned long temp; for(int i=0; i<ROWS; i++){ for(int j=0; j<COLS; j++){ if(j<COLS-4){ temp = grid[i][j] * grid[i][j+1] * grid[i][j+2] * grid[i][j+3]; if(temp > res) res = temp; } if(i<ROWS-4){ temp = grid[i][j] * grid[i+1][j] * grid[i+2][j] * grid[i+3][j]; if(temp > res) res = temp; } if(i<ROWS-4 && j<COLS-4){ temp = grid[i][j] * grid[i+1][j+1] * grid[i+2][j+2] * grid[i+3][j+4]; if(temp > res) res = temp; } if(i>3 && j<COLS-4){ temp = grid[i][j] * grid[i-1][j+1] * grid[i-2][j+2] * grid[i-3][j+3]; if(temp > res) res = temp; } } } return res; } unsigned long magic(FILE* input_file){ int grid[ROWS][COLS]; bool wasNumber = false; int input; int number = 0; int row_idx = 0; int col_idx = 0; while((input = getc(input_file)) != EOF){ if(isNumber(input)){ number *= 10; number += input - '0'; wasNumber = true; }else if(wasNumber){ grid[row_idx][col_idx] = number; number = 0; wasNumber = false; col_idx++; if(col_idx == COLS){ col_idx = 0; row_idx++; } } } return magic2(grid); } int main(){ unsigned long res = 0; char buffer[BUFFER_SZ]; printf("Insert the name of the input file: "); fgets(buffer, BUFFER_SZ, stdin); buffer[strlen(buffer)-1] = '\0'; FILE* input_file = fopen(buffer, "r"); if(input_file == NULL){ perror("fopen"); exit(EXIT_FAILURE); }else{ printf("File opened successfully.\n"); } res = magic(input_file); fclose(input_file); printf("If you can trust me, the number you are " "looking for is %lu\n", res); return 0; }
24.326316
79
0.465599
4964b54bcc941dd66b264ede259bbf384a01cb92
416
cpp
C++
functions/prime_between_two_nums.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
functions/prime_between_two_nums.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
functions/prime_between_two_nums.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool prime_between_two_nums(int num) { for (int i = 2; i < sqrt(num); i++) if (num % 2 == 0) { return false; } else { return true; } } int main() { int a, b; for (int i = a; i <= b; i++) { if (prime_between_two_nums(i)) cout << i << endl; } return 0; }
16
39
0.427885
496bf95d0aaecdc00598dc9fb87e2231003b1054
2,591
cpp
C++
ffl/source/utils/FFL_Clock.cpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
ffl/source/utils/FFL_Clock.cpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
ffl/source/utils/FFL_Clock.cpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
/* * This file is part of FFL project. * * The MIT License (MIT) * Copyright (C) 2017-2018 zhufeifei All rights reserved. * * FFL_Clock.cpp * Created by zhufeifei(34008081@qq.com) on 2018/04/29 * https://github.com/zhenfei2016/FFL-v2.git * * 时钟类,可以获取当前时间,改变时钟速度,修改时钟原点偏移 * y=ax +b */ #include <utils/FFL_Clock.hpp> namespace FFL { // // y=(a/KA_RATIO) x +b // 当前设置的a参数的放大倍数,实际的值= a/KA_RATIO // // static const int64_t KA_RATIO = 100; // // y=x*a /KA_RATIO // static int64_t getY(int64_t x, int64_t a) { return (int64_t)((double)(x * a) / KA_RATIO); } Clock::Clock():mListener(NULL){ reset(); } Clock::~Clock() { } void Clock::reset() { mB = 0; mA = KA_RATIO; } IClockListener* Clock::setListener(IClockListener* listener){ IClockListener* ret = mListener; mListener=listener; return ret; } // // 当前时间 // int64_t Clock::nowUs() { return nowUs(0); } // // 这个时钟的当前时间 systemUs:返回系统时钟的时间 // int64_t Clock::nowUs(int64_t* systemUs) { int64_t now = FFL_getNowUs(); if (systemUs) { *systemUs = now; } if (equalSystemClock()) { return now; } // // 转化到当前时钟的时间值 // y=ax +b // int64_t clockNow = getY(now, mA) + mB; FFL_LOG_INFO("Clock x:%" lld64 " y:%" lld64 "a=%" lld64 " b=%" lld64, now, clockNow, mA, mB); return clockNow; } // // 转换当前时钟的一个时间段转成系统时钟时间段 // 例如可以把当前时钟5分钟转成系统时钟8分钟 // int64_t Clock::clockToWorldTimeBucket(int64_t dy) { // // y=ax+b // 计算dx // return (int64_t)(double)(dy * 100) / mA; } int64_t Clock::SystemToClockRelativeUs(int64_t dx) { // // y=ax+b // 计算dy // return (int64_t)((double)(dx * mA) / 100); } int64_t Clock::worldToClockUs(int64_t x) { // // y=ax+b // 计算dy // return (int64_t)getY(x, mA) + mB; } // // 时钟速度,默认1.0时正常时钟值 // uint32_t Clock::speed() { return mA; } void Clock::setSpeed(uint32_t percent) { if (percent != mA) { int64_t x; int64_t y = nowUs(&x); // // 计算新的a,b参数 // b=y-ax // uint32_t oldA=mA; mA = percent; mB = y - (int64_t)((double)(mA* x) / KA_RATIO); if(mListener){ int32_t type=0; if(percent>oldA) type=1; else if(percent<oldA) type=-1; mListener->onSpeedChange(type, mA); } } } // // 偏移 // int64_t Clock::offset() { return mOffset; } void Clock::setOffset(int64_t offset) { mOffset = offset; } // // 是否系统时钟一致的 // bool Clock::equalSystemClock() { return mA == KA_RATIO; } }
17.868966
95
0.565033
496c85b7a32734eabd51d4fa2d7f9cce3a028f70
2,001
cpp
C++
nmainwindow.cpp
NeoProject/NeoPaintPrototype
ebfca88f7ddc2011daebf6d221c8e099f6e03645
[ "Info-ZIP" ]
null
null
null
nmainwindow.cpp
NeoProject/NeoPaintPrototype
ebfca88f7ddc2011daebf6d221c8e099f6e03645
[ "Info-ZIP" ]
null
null
null
nmainwindow.cpp
NeoProject/NeoPaintPrototype
ebfca88f7ddc2011daebf6d221c8e099f6e03645
[ "Info-ZIP" ]
null
null
null
#include "nmainwindow.h" #include "NGadget/nstatusbar.h" #include "NGadget/nmenubar.h" #include "NGadget/ntoolbar.h" #include <QLabel> #include <NCanvas/ncanvas.h> #include "NGadget/nabout.h" #include "NCanvas/ntabwidget.h" #include <QMenu> #include <QAction> #include "NGadget/ntablettest.h" #include "NDockWidget/ndockwidget.h" #include "NGadget/nabout.h" #include "NGadget/ntablettest.h" #include "NCanvas/ncanvasview.h" NMainWindow::NMainWindow(QWidget *parent) : QMainWindow(parent), neoStatusBar(new NStatusBar(this)), neoMenuBar(new NMenuBar(this)), neoToolBar(new NToolBar(this)), neoTabWidget(new NTabWidget(this)), neoPrototype(new NDockWidget(this)), neoAbout(new NAbout(tr("NeoPaintPrototype"))), neoTabletTest(new NTabletTest) { initWidget(); initConnection(); setDockNestingEnabled(true); neoPrototype->setAllowedAreas(Qt::LeftDockWidgetArea); neoPrototype->setMinimumWidth(300); // neoTabWidget->nCanvas->setMessage(neoStatusBar->nStatusMessage); } NMainWindow::~NMainWindow() { } void NMainWindow::initWidget() { setStatusBar(neoStatusBar); setMenuBar(neoMenuBar); addToolBar(neoToolBar); setCentralWidget(neoTabWidget); addDockWidget(Qt::LeftDockWidgetArea, neoPrototype); } void NMainWindow::initConnection() { connect(neoMenuBar->NFile.Close, &QAction::triggered, this, &NMainWindow::close); connect(neoMenuBar->NHelp.About, &QAction::triggered, neoAbout, &NAbout::show); connect(neoMenuBar->NHelp.TabletTest, &QAction::triggered, neoTabletTest, &NTabletTest::show); connect(neoMenuBar->NFile.New, &QAction::triggered, neoTabWidget, &NTabWidget::newCanvas); // connect(neoMenuBar, &NMenuBar::sendFileName, neoTabWidget->nView, &NCanvasView::openFile); // connect(neoMenuBar, &NMenuBar::sendSaveFileName, neoTabWidget->nView, &NCanvasView::saveFile); // connect(neoTabWidget->nCanvas, &NCanvas::tabletStatusChanged, neoStatusBar, &NStatusBar::changeStatus); }
31.761905
109
0.74013
4971d7fbcdd6db28eff49825d3b8a5b959f4e86a
3,757
cpp
C++
Project/Part Five: Data Cache/Code/CacheStats.cpp
HernandezDerekJ/Computer-Architecture-3339
03785b02169a76ca0b1b38205bd5e64adde2b727
[ "MIT" ]
null
null
null
Project/Part Five: Data Cache/Code/CacheStats.cpp
HernandezDerekJ/Computer-Architecture-3339
03785b02169a76ca0b1b38205bd5e64adde2b727
[ "MIT" ]
null
null
null
Project/Part Five: Data Cache/Code/CacheStats.cpp
HernandezDerekJ/Computer-Architecture-3339
03785b02169a76ca0b1b38205bd5e64adde2b727
[ "MIT" ]
null
null
null
/****************************** * CacheStats.cpp submitted by: Derek Hernandez (djh119) * CS 3339 - Spring 2019 * Project 4 Branch Predictor * Copyright 2019, all rights reserved * Updated by Lee B. Hinkle based on prior work by Martin Burtscher and Molly O'Neil ******************************/ #include <iostream> #include <cstdlib> #include <iomanip> #include "CacheStats.h" using namespace std; CacheStats::CacheStats() { cout << "Cache Config: "; if(!CACHE_EN) { cout << "cache disabled" << endl; } else { cout << (SETS * WAYS * BLOCKSIZE) << " B ("; cout << BLOCKSIZE << " bytes/block, " << SETS << " sets, " << WAYS << " ways)" << endl; cout << " Latencies: Lookup = " << LOOKUP_LATENCY << " cycles, "; cout << "Read = " << READ_LATENCY << " cycles, "; cout << "Write = " << WRITE_LATENCY << " cycles" << endl; } loads = 0; stores = 0; load_misses = 0; store_misses = 0; writebacks = 0; /* TODO: your code here */ tag = uint32_t(0); index = uint32_t(0); stallLatency = 0; for(int a = 0; a < SETS; a++){ w[a]=0; for(int b = 0; b < WAYS; b++){ tags[a][b] = uint32_t(0); modify[a][b] = 0; valid[a][b] = 0; } } } int CacheStats::access(uint32_t addr, ACCESS_TYPE type) { if(!CACHE_EN) { // cache is off return (type == LOAD) ? READ_LATENCY : WRITE_LATENCY; } /* TODO: your code here */ // Vars // Offset == log2 (32) // Set == 3 (2^3) index = (addr >> 5) & 0x7; //Data to store tag = addr >> 8; //Reset Stall stallLatency = 0; //Loads and Stores if (type == STORE) stores++; else if(type == LOAD) loads++; //HIT //tags match and its not empty(vaild) for(int a = 0; a < WAYS; a++){ if((tags[index][a] == tag) && (valid[index][a])){ stallLatency = LOOKUP_LATENCY; if(type == STORE) modify[index][a] = 1; return stallLatency; } } // Miss two types Clean, Dirty if(type == STORE) store_misses++; else if(type == LOAD) load_misses++; //Clean Modify == 0 Latency == 30 if(modify[index][w[index]] == 0){ stallLatency = stallLatency + READ_LATENCY; } //Dirty Modify == 1 Latency == 10+30 else if(modify[index][w[index]] == 1){ stallLatency = stallLatency + READ_LATENCY + WRITE_LATENCY; writebacks++; } //Install into cache tags[index][w[index]] = tag; valid[index][w[index]] = 1; //Determine Modify,based on type if(type == LOAD){ modify[index][w[index]] = 0; } else if(type == STORE){ modify[index][w[index]] = 1; } //Control w values, round robin 4 way, never go over 3 if (w[index] == 3){ w[index] = 0; } else{ w[index]++; } return stallLatency; } void CacheStats::printFinalStats() { /* TODO: your code here (don't forget to drain the cache of writebacks) */ // Write Back == Dirty/Modified (Whenever modify is true) for(int x = 0; x < SETS; x++){ for(int y = 0; y < WAYS; y++){ if(modify[x][y]) writebacks++; } } int accesses = loads + stores; int misses = load_misses + store_misses; cout << "Accesses: " << accesses << endl; cout << " Loads: " << loads << endl; cout << " Stores: " << stores << endl; cout << "Misses: " << misses << endl; cout << " Load misses: " << load_misses << endl; cout << " Store misses: " << store_misses << endl; cout << "Writebacks: " << writebacks << endl; cout << "Hit Ratio: " << fixed << setprecision(1) << 100.0 * (accesses - misses) / accesses; cout << "%" << endl; }
28.24812
94
0.526218
49724ecba26a56c2e2550a77eae9f9b0eabb32ef
2,919
cpp
C++
application/CMatrix.cpp
HO-COOH/Console
f6132e4135db0c5432a2943a8f5f367a6ce1167d
[ "MIT" ]
3
2020-06-05T05:18:32.000Z
2021-07-29T01:13:07.000Z
application/CMatrix.cpp
HO-COOH/Console
f6132e4135db0c5432a2943a8f5f367a6ce1167d
[ "MIT" ]
null
null
null
application/CMatrix.cpp
HO-COOH/Console
f6132e4135db0c5432a2943a8f5f367a6ce1167d
[ "MIT" ]
null
null
null
#include "Console.h" #include "ConsoleEngine.h" #include "TimedEvent.hpp" #include <iostream> #include <thread> #include <random> #include <vector> #include <array> #include <functional> static std::mt19937 rdEng{ std::random_device{}() }; char randomChar() { static std::uniform_int_distribution<int> rdNum{ '!', '}' }; return rdNum(rdEng); } int main(int argc, char** argv) { ConsoleEngine eng{ console }; eng.setAsciiMode(); const auto width = console.getWidth(); const auto height = console.getHeight(); std::uniform_int_distribution rdNumHeight{ 0, (int)height }; std::vector<short> head( width, 0); std::vector<short> tail( width, 0); std::vector<short> length(width, 0); std::vector<bool> hasContent(width); ScopedTimer t{ 60000 }; std::vector<short> emptyCol; emptyCol.reserve(width); while (true) { /*Get empty columns*/ for (auto col = 0; col < width; ++col) { if (!hasContent[col]) emptyCol.push_back(col); } /*select some empty columns*/ if (emptyCol.size() > width/2) { std::array<short, 10> toFill; std::uniform_int_distribution rd{ 0, static_cast<int>(emptyCol.size() - 1) }; std::generate(toFill.begin(), toFill.end(), [&rd, &emptyCol] {return emptyCol[rd(rdEng)]; }); for (auto& col : toFill) { eng.buffer(0, col).Char.AsciiChar = randomChar(); eng.buffer(0, col).Attributes = static_cast<WORD>(Color::WHITE) | FOREGROUND_INTENSITY; hasContent[col] = true; head[col] = 1; length[col] = rdNumHeight(rdEng); } } for (auto i = 0; i < width; ++i) { /*generate a random char at [head] position*/ if (hasContent[i]) { if (head[i] != 0) { eng.buffer(head[i], i).Char.AsciiChar = randomChar(); eng.buffer(head[i] - 1, i).Attributes = static_cast<WORD>(Color::GREEN) | FOREGROUND_INTENSITY; eng.buffer(head[i], i).Attributes = static_cast<WORD>(Color::WHITE) | FOREGROUND_INTENSITY; ++head[i]; if (head[i] >= height) head[i] = 0; } /*delete the char at [tail] position */ if ( head[i]==0||head[i]-tail[i] >= length[i]) { eng.buffer(tail[i], i).Char.AsciiChar = ' '; ++tail[i]; if (tail[i] >= height) { tail[i] = 0; hasContent[i] = false; } } } } eng.draw(); emptyCol.clear(); t.wait(); } }
31.053191
115
0.488866
49736fe0cc0e1cb621c5a52218f6fc60f8067e53
2,524
cc
C++
model/mosesdecoder/util/tempfile_test.cc
saeedesm/UNMT_AH
cc171bf66933b5c0ad8a0ab87e57f7364312a7df
[ "Apache-2.0" ]
3
2020-02-28T21:42:44.000Z
2021-03-12T13:56:16.000Z
tools/mosesdecoder-master/util/tempfile_test.cc
Pangeamt/nectm
6b84f048698f2530b9fdbb30695f2e2217c3fbfe
[ "Apache-2.0" ]
2
2020-11-06T14:40:10.000Z
2020-12-29T19:03:11.000Z
tools/mosesdecoder-master/util/tempfile_test.cc
Pangeamt/nectm
6b84f048698f2530b9fdbb30695f2e2217c3fbfe
[ "Apache-2.0" ]
2
2019-11-26T05:27:16.000Z
2019-12-17T01:53:43.000Z
#include "util/tempfile.hh" #include <fstream> #include <boost/filesystem.hpp> #define BOOST_TEST_MODULE TempFileTest #include <boost/test/unit_test.hpp> namespace util { namespace { BOOST_AUTO_TEST_CASE(temp_dir_has_path) { BOOST_CHECK(temp_dir().path().size() > 0); } BOOST_AUTO_TEST_CASE(temp_dir_creates_temp_directory) { const temp_dir t; BOOST_CHECK(boost::filesystem::exists(t.path())); BOOST_CHECK(boost::filesystem::is_directory(t.path())); } BOOST_AUTO_TEST_CASE(temp_dir_creates_unique_directory) { BOOST_CHECK(temp_dir().path() != temp_dir().path()); } BOOST_AUTO_TEST_CASE(temp_dir_cleans_up_directory) { std::string path; { const temp_dir t; path = t.path(); } BOOST_CHECK(!boost::filesystem::exists(path)); } BOOST_AUTO_TEST_CASE(temp_dir_cleanup_succeeds_if_directory_contains_file) { std::string path; { const temp_dir t; path = t.path(); boost::filesystem::create_directory(path + "/directory"); std::ofstream file((path + "/file").c_str()); file << "Text"; file.flush(); } BOOST_CHECK(!boost::filesystem::exists(path)); } BOOST_AUTO_TEST_CASE(temp_dir_cleanup_succeeds_if_directory_is_gone) { std::string path; { const temp_dir t; path = t.path(); boost::filesystem::remove_all(path); } BOOST_CHECK(!boost::filesystem::exists(path)); } BOOST_AUTO_TEST_CASE(temp_file_has_path) { BOOST_CHECK(temp_file().path().size() > 0); } BOOST_AUTO_TEST_CASE(temp_file_creates_temp_file) { const temp_file f; BOOST_CHECK(boost::filesystem::exists(f.path())); BOOST_CHECK(boost::filesystem::is_regular_file(f.path())); } BOOST_AUTO_TEST_CASE(temp_file_creates_unique_file) { BOOST_CHECK(temp_file().path() != temp_file().path()); } BOOST_AUTO_TEST_CASE(temp_file_creates_writable_file) { const std::string data = "Test-data-goes-here"; const temp_file f; std::ofstream outfile(f.path().c_str()); outfile << data; outfile.flush(); std::string read_data; std::ifstream infile(f.path().c_str()); infile >> read_data; BOOST_CHECK_EQUAL(data, read_data); } BOOST_AUTO_TEST_CASE(temp_file_cleans_up_file) { std::string path; { const temp_file f; path = f.path(); } BOOST_CHECK(!boost::filesystem::exists(path)); } BOOST_AUTO_TEST_CASE(temp_file_cleanup_succeeds_if_file_is_gone) { std::string path; { const temp_file t; path = t.path(); boost::filesystem::remove(path); } BOOST_CHECK(!boost::filesystem::exists(path)); } } // namespace anonymous } // namespace util
21.033333
74
0.717116
49772dc0de346e7b9097b33e8ee45bdb5f8a2971
2,636
cc
C++
src/iterator_async.cc
aspectron/zetta-lmdb
776efda991321734f0d3a030ebd3cb54f8eadcac
[ "MITNFA" ]
1
2019-11-30T00:02:49.000Z
2019-11-30T00:02:49.000Z
src/iterator_async.cc
aspectron/zetta-lmdb
776efda991321734f0d3a030ebd3cb54f8eadcac
[ "MITNFA" ]
null
null
null
src/iterator_async.cc
aspectron/zetta-lmdb
776efda991321734f0d3a030ebd3cb54f8eadcac
[ "MITNFA" ]
null
null
null
/* Copyright (c) 2013 Rod Vagg * MIT +no-false-attribs License <https://github.com/rvagg/lmdb/blob/master/LICENSE> */ #include <node.h> #include <node_buffer.h> #include "database.h" #include "nlmdb.h" #include "async.h" #include "iterator_async.h" namespace nlmdb { /** NEXT WORKER **/ NextWorker::NextWorker ( Iterator* iterator , NanCallback *callback , void (*localCallback)(Iterator*) ) : AsyncWorker(NULL, callback) , iterator(iterator) , localCallback(localCallback) {}; NextWorker::~NextWorker () {} void NextWorker::Execute () { //std::cerr << "NextWorker::Execute: " << iterator->id << std::endl; SetStatus(iterator->Next(&key, &value)); //std::cerr << "NextWorker::Execute done: " << iterator->id << std::endl; } void NextWorker::WorkComplete () { NanScope(); if (status.code == MDB_NOTFOUND || (status.code == 0 && status.error.length() == 0)) HandleOKCallback(); else HandleErrorCallback(); } void NextWorker::HandleOKCallback () { NanScope(); //std::cerr << "NextWorker::HandleOKCallback: " << iterator->id << std::endl; //std::cerr << "Read [" << std::string((char*)key.mv_data, key.mv_size) << "]=[" << std::string((char*)value.mv_data, value.mv_size) << "]\n"; if (status.code == MDB_NOTFOUND) { //std::cerr << "run callback, ended MDB_NOTFOUND\n"; localCallback(iterator); callback->Run(0, NULL); return; } v8::Local<v8::Value> returnKey; if (iterator->keyAsBuffer) { returnKey = NanNewBufferHandle((char*)key.mv_data, key.mv_size); } else { returnKey = v8::String::New((char*)key.mv_data, key.mv_size); } v8::Local<v8::Value> returnValue; if (iterator->valueAsBuffer) { returnValue = NanNewBufferHandle((char*)value.mv_data, value.mv_size); } else { returnValue = v8::String::New((char*)value.mv_data, value.mv_size); } // clean up & handle the next/end state see iterator.cc/checkEndCallback //std::cerr << "run callback, ended FOUND\n"; localCallback(iterator); v8::Local<v8::Value> argv[] = { v8::Local<v8::Value>::New(v8::Null()) , returnKey , returnValue }; callback->Run(3, argv); } /** END WORKER **/ EndWorker::EndWorker ( Iterator* iterator , NanCallback *callback ) : AsyncWorker(NULL, callback) , iterator(iterator) {executed=false;}; EndWorker::~EndWorker () {} void EndWorker::Execute () { executed = true; //std::cerr << "EndWorker::Execute...\n"; iterator->End(); } void EndWorker::HandleOKCallback () { //std::cerr << "EndWorker::HandleOKCallback: " << iterator->id << std::endl; iterator->Release(); callback->Run(0, NULL); } } // namespace nlmdb
24.635514
142
0.649469
49777283d6c10ab1c31f8cbaa2667c61dda384cf
3,352
hh
C++
geometry2.hh
lnw/nano-tori
5f43722085154c9315ada572108a360e6601dd1a
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
geometry2.hh
lnw/nano-tori
5f43722085154c9315ada572108a360e6601dd1a
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
geometry2.hh
lnw/nano-tori
5f43722085154c9315ada572108a360e6601dd1a
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
// Copyright (c) 2019, Lukas Wirz // All rights reserved. // This file is part of 'nano-tori' which is released under the BSD-2-clause license. // See file LICENSE in this project. #ifndef GEOMETRY2_HH #define GEOMETRY2_HH #include <cassert> #include <cmath> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> #include "auxiliary.hh" using namespace std; struct matrix2d; struct coord2d { double x[2]; coord2d(const double y[2]) { x[0] = y[0]; x[1] = y[1]; } explicit coord2d(const double x_=0, const double y=0) { x[0] = x_; x[1] = y; } coord2d operator/(const double s) const { return coord2d(*this) /= s; } coord2d operator*(const double s) const { return coord2d(*this) *= s; } coord2d operator+(const coord2d& y) const { return coord2d(*this) += y; } coord2d operator-(const coord2d& y) const { return coord2d(*this) -= y; } coord2d& operator+=(const coord2d& y){ x[0] += y[0]; x[1] += y[1]; return *this; } coord2d& operator-=(const coord2d& y){ x[0] -= y[0]; x[1] -= y[1]; return *this; } coord2d& operator*=(const double& y){ x[0] *= y; x[1] *= y; return *this; } coord2d& operator/=(const double& y){ x[0] /= y; x[1] /= y; return *this; } coord2d operator-() const {coord2d y(-x[0],-x[1]); return y;} coord2d operator*(const matrix2d& m) const; double& operator[](unsigned int i){ return x[i]; } double operator[](unsigned int i) const { return x[i]; } double norm() const {return sqrt(x[0]*x[0] + x[1]*x[1]);} friend ostream& operator<<(ostream& S, const coord2d &c2) { S << "{" << c2[0] << ", " << c2[1] << "}"; return S; } }; coord2d operator*(const double &d, const coord2d &c2d); struct structure2d { vector<coord2d> dat; vector<coord2d>::iterator begin(){return dat.begin();} vector<coord2d>::iterator end(){return dat.end();} structure2d operator*(const matrix2d& m) const; coord2d& operator[](unsigned int i){ return dat[i]; } coord2d operator[](unsigned int i) const { return dat[i]; } void push_back(const coord2d &c2d){dat.push_back(c2d);} size_t size() const {return dat.size();} bool contains(coord2d p) const; void crop(double x1, double y1, double x2, double y2); // assume that all points are consecutive, and both ends are connected // if the curve is self-intersecting, every intersection changes the sign, but the total sign is positive double area() const; friend ostream& operator<<(ostream& S, const structure2d &s2) { S << s2.dat; return S; } }; struct matrix2d { double values[4]; explicit matrix2d(const double w=0, const double x=0, const double y=0, const double z=0) { // (0,0), (0,1), (1,0), (1,1) values[0]=w; values[1]=x; values[2]=y; values[3]=z; } double& operator()(int i, int j) { return values[i*2+j]; } // i: row, j: column double operator()(int i, int j) const { return values[i*2+j]; } double& operator[](unsigned int i) { return values[i]; } double operator[](unsigned int i) const { return values[i]; } coord2d operator*(const coord2d& c2d) const; structure2d operator*(const structure2d& s2d) const; friend ostream& operator<<(ostream& S, const matrix2d &M) { S << "{"; for(int i=0;i<2;i++) S << vector<double>(&M.values[i*2],&M.values[(i+1)*2]) << (i+1<2?",":"}"); return S; } }; #endif
31.622642
123
0.636038
497938523755e3be70e0d1cc9bdad40f50ed3590
4,777
cpp
C++
playlistTable.cpp
allenyin/musicplayer2
429c5e86afc01df21161023d359826d65c9b35ec
[ "MIT" ]
1
2016-06-05T15:14:22.000Z
2016-06-05T15:14:22.000Z
playlistTable.cpp
allenyin/musicplayer2
429c5e86afc01df21161023d359826d65c9b35ec
[ "MIT" ]
null
null
null
playlistTable.cpp
allenyin/musicplayer2
429c5e86afc01df21161023d359826d65c9b35ec
[ "MIT" ]
1
2019-04-17T15:19:08.000Z
2019-04-17T15:19:08.000Z
#include "playlistTable.h" #include "playlistmodel.h" #include <stdio.h> #include <iostream> #include <QApplication> #include <QHeaderView> #include <QMimeData> #include <QDebug> class PlaylistModel; PlaylistTable::PlaylistTable(QWidget* parent) : QTableView(parent) { // edit only when F2 is pressed setEditTriggers(QAbstractItemView::EditKeyPressed); setAlternatingRowColors(true); // entire row is selected when any item is clicked setSelectionBehavior(QAbstractItemView::SelectRows); setSelectionMode(QAbstractItemView::ContiguousSelection); // enable drag and drop setDragEnabled(true); setAcceptDrops(true); setDropIndicatorShown(true); setDefaultDropAction(Qt::MoveAction); setDragDropOverwriteMode(false); setDragDropMode(QTableView::DragDrop); } PlaylistTable::~PlaylistTable() { } void PlaylistTable::mouseDoubleClickEvent(QMouseEvent* e) { QPoint clickPos = e->pos(); QModelIndex clickIdx = QTableView::indexAt(clickPos); #if DEBUG_PLAYLISTVIEW qDebug()<< "Double click at (" << clickPos.x() << ", " << clickPos.y(); qDebug()<< "ModelIndex: (" << clickIdx.row() << ", " << clickIdx.column(); #endif emit(QTableView::activated(clickIdx)); } void PlaylistTable::mouseReleaseEvent(QMouseEvent* e) { if (e->button() == Qt::LeftButton) { // Use base handler QTableView::mouseReleaseEvent(e); } else { QTableView::mouseReleaseEvent(e); } } #if DEBUG_PLAYLISTVIEW void PlaylistTable::contextMenuEvent(QContextMenuEvent* e) { QPoint clickPos = e->pos(); QModelIndex clickIdx = QTableView::indexAt(clickPos); qDebug() << "Right click at (" << clickPos.x() << ", " << clickPos.y() << ")"; qDebug() << "ModelIndex: (" << clickIdx.row() << ", " << clickIdx.column() << ")"; } #endif void PlaylistTable::keyPressEvent(QKeyEvent *event) { // selectionMode must be contiguous if (event->key() == Qt::Key_Delete) { if (selectionModel()->hasSelection()) { QModelIndexList selected = selectionModel()->selectedRows(); PlaylistModel *model = (PlaylistModel*)(QTableView::model()); model->removeMedia(selected.front().row(), selected.back().row()); } } else { QTableView::keyPressEvent(event); } } void PlaylistTable::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("myMediaItem")) { //qDebug() << "playlistTable::dragEnterEvent()"; #if DEBUG_PLAYLISTVIEW QPoint dragPos = event->pos(); QModelIndex dragIdx = QTableView::indexAt(dragPos); qDebug()<<"dragIdx is " << dragIdx; #endif event->accept(); } else { event->ignore(); } } void PlaylistTable::dragMoveEvent(QDragMoveEvent *event) { if (event->mimeData()->hasFormat("myMediaItem")) { //qDebug() << "playlistTable::dragMoveEvent(myMediaItem)"; event->setDropAction(Qt::MoveAction); event->accept(); } else { event->ignore(); } } void PlaylistTable::dropEvent(QDropEvent *event) { //qDebug()<<"PlaylistTable::dropEvent()"; if (event->mimeData()->hasFormat("myMediaItem")) { // this is when we re-arrange items in the playlist QByteArray itemData = event->mimeData()->data("myMediaItem"); QDataStream dataStream(&itemData, QIODevice::ReadOnly); QString header; dataStream >> header; qDebug() << "Header is: " << header; if (header == "playlistItem") { QPoint dropPos = event->pos(); int dropRow = QTableView::indexAt(dropPos).row(); QList<int> itemRowList; while (!dataStream.atEnd()) { int itemRow; dataStream >> itemRow; itemRowList << itemRow; } qSort(itemRowList); int offset = dropRow - itemRowList.back(); #if DEBUG_PLAYLISTVIEW qDebug()<<"dropRow is " << dropRow; #endif PlaylistModel *model = static_cast<PlaylistModel*>(QTableView::model()); model->swapSong(dropRow, itemRowList, offset); event->setDropAction(Qt::MoveAction); event->accept(); } if (header == "libraryItem") { QList<QHash<QString, QString> > itemList; QHash<QString, QString> hash; while (!dataStream.atEnd()) { dataStream >> hash; itemList << hash; } PlaylistModel *model = static_cast<PlaylistModel*>(QTableView::model()); model->addMediaList(itemList); event->setDropAction(Qt::CopyAction); event->accept(); } } else { event->ignore(); } }
30.621795
86
0.609378
497a1492afe717c7f57e2f374dd963873003af7b
28,261
cpp
C++
benchmark/message/message.cpp
smart-cloud/actor-zeta
9597d6c21843a5e24a7998d09ff041d2f948cc63
[ "BSD-3-Clause" ]
20
2016-01-07T07:37:52.000Z
2019-06-02T12:04:25.000Z
benchmark/message/message.cpp
smart-cloud/actor-zeta
9597d6c21843a5e24a7998d09ff041d2f948cc63
[ "BSD-3-Clause" ]
30
2017-03-10T14:47:46.000Z
2019-05-09T19:23:25.000Z
benchmark/message/message.cpp
jinncrafters/actor-zeta
9597d6c21843a5e24a7998d09ff041d2f948cc63
[ "BSD-3-Clause" ]
6
2017-03-10T14:06:01.000Z
2018-08-13T18:19:37.000Z
#include <benchmark/benchmark.h> #include <iostream> #include <map> #include <memory> #include <string> #include <vector> #include <actor-zeta/make_message.hpp> #include "fixtures.hpp" #include "register_benchmark.hpp" namespace benchmark_messages { static volatile int64_t message_sz = 0; using raw_t = actor_zeta::mailbox::message*; using smart_t = actor_zeta::mailbox::message_ptr; namespace by_name { BENCHMARK_TEMPLATE_DEFINE_F(fixture_t, RawPtrMessage_Name, raw_t) (benchmark::State& state) { while (state.KeepRunning()) { auto message = actor_zeta::make_message_ptr( actor_zeta::base::address_t::empty_address(), name_); auto tmp = sizeof(*message); delete message; if (static_cast<int64_t>(tmp) > static_cast<int64_t>(benchmark_messages::message_sz)) benchmark_messages::message_sz = static_cast<int64_t>(tmp); } } BENCHMARK_TEMPLATE_DEFINE_F(fixture_t, SmartPtrMessage_Name, smart_t) (benchmark::State& state) { while (state.KeepRunning()) { auto message = actor_zeta::make_message( actor_zeta::base::address_t::empty_address(), name_); auto tmp = sizeof(*message); if (static_cast<int64_t>(tmp) > static_cast<int64_t>(benchmark_messages::message_sz)) benchmark_messages::message_sz = static_cast<int64_t>(tmp); } } BENCHMARK_REGISTER_F(fixture_t, RawPtrMessage_Name)->DenseRange(0, 64, 8); BENCHMARK_REGISTER_F(fixture_t, SmartPtrMessage_Name)->DenseRange(0, 64, 8); } // namespace by_name namespace by_args { template<typename... Args> auto message_arg_tmpl(uint64_t name_, Args&&... args) -> void; namespace raw_ptr { template<typename... Args> auto message_arg_tmpl(uint64_t name_, Args&&... args) -> void { auto message = actor_zeta::make_message_ptr( actor_zeta::base::address_t::empty_address(), name_, std::forward<Args>(args)...); auto tmp = sizeof(*message); delete message; if (static_cast<int64_t>(tmp) > static_cast<int64_t>(benchmark_messages::message_sz)) benchmark_messages::message_sz = static_cast<int64_t>(tmp); } template<typename T, std::size_t... I> auto call_message_arg_tmpl(uint64_t name_, T& packed_tuple, actor_zeta::type_traits::index_sequence<I...>) -> void { message_arg_tmpl(name_, (std::get<I>(packed_tuple))...); } } // namespace raw_ptr namespace smart_ptr { template<typename... Args> auto message_arg_tmpl(uint64_t name_, Args&&... args) -> void { auto message = actor_zeta::make_message( actor_zeta::base::address_t::empty_address(), name_, std::forward<Args>(args)...); auto tmp = sizeof(*message); if (static_cast<int64_t>(tmp) > static_cast<int64_t>(benchmark_messages::message_sz)) benchmark_messages::message_sz = static_cast<int64_t>(tmp); } template<typename T, std::size_t... I> auto call_message_arg_tmpl(uint64_t name_, T& packed_tuple, actor_zeta::type_traits::index_sequence<I...>) -> void { message_arg_tmpl(name_, (std::get<I>(packed_tuple))...); } } // namespace smart_ptr #define REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture, bm_name, type) REGISTER_BENCHMARK_FOR_RAWPTR_ARGS(fixture, bm_name, raw_t, benchmark_messages::by_args::raw_ptr, type) #define REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture, bm_name, type) REGISTER_BENCHMARK_FOR_SMARTPTR_ARGS(fixture, bm_name, smart_t, benchmark_messages::by_args::smart_ptr, type) namespace trivial_args { REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long_double, long double);*/ REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long_double, long double);*/ } // namespace trivial_args namespace smart_pointer_args { //REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long_double, long double);*/ } // namespace smart_pointer_args namespace container_args { //REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long_double, long double);*/ } // namespace container_args namespace custom_args { //REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_custom_1, custom_1_t); //REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_custom_1, custom_1_t); } // namespace custom_args } // namespace by_args class memory_manager_t : public benchmark::MemoryManager { void Start() BENCHMARK_OVERRIDE {} void Stop(Result* result) BENCHMARK_OVERRIDE { result->max_bytes_used = message_sz; } }; } // namespace benchmark_messages // Run the benchmark int main(int argc, char** argv) { benchmark::Initialize(&argc, argv); if (benchmark::ReportUnrecognizedArguments(argc, argv)) return 1; std::unique_ptr<benchmark::MemoryManager> mm(new benchmark_messages::memory_manager_t()); benchmark::RegisterMemoryManager(mm.get()); benchmark::RunSpecifiedBenchmarks(); benchmark::Shutdown(); benchmark::RegisterMemoryManager(nullptr); return 0; }
81.20977
186
0.78695
497f10f04c580ca0ed1cf2ec41db964cbea1859c
5,472
cpp
C++
TAO/tao/Synch_Queued_Message.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/Synch_Queued_Message.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/Synch_Queued_Message.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// -*- C++ -*- // $Id: Synch_Queued_Message.cpp 93465 2011-03-02 16:16:33Z vzykov $ #include "tao/Synch_Queued_Message.h" #include "tao/debug.h" #include "tao/ORB_Core.h" #include "ace/Malloc_T.h" #include "ace/Message_Block.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_Synch_Queued_Message::TAO_Synch_Queued_Message ( const ACE_Message_Block *contents, TAO_ORB_Core *oc, ACE_Allocator *alloc, bool is_heap_allocated) : TAO_Queued_Message (oc, alloc, is_heap_allocated) , contents_ (const_cast<ACE_Message_Block*> (contents)) , current_block_ (contents_) , own_contents_ (is_heap_allocated) { } TAO_Synch_Queued_Message::~TAO_Synch_Queued_Message (void) { if (this->own_contents_ && this->contents_ != 0) { ACE_Message_Block::release (this->contents_); } } const ACE_Message_Block * TAO_Synch_Queued_Message::current_block (void) const { return this->current_block_; } size_t TAO_Synch_Queued_Message::message_length (void) const { if (this->current_block_ == 0) { return 0; } return this->current_block_->total_length (); } int TAO_Synch_Queued_Message::all_data_sent (void) const { return this->current_block_ == 0; } void TAO_Synch_Queued_Message::fill_iov (int iovcnt_max, int &iovcnt, iovec iov[]) const { ACE_ASSERT (iovcnt_max > iovcnt); for (const ACE_Message_Block *message_block = this->current_block_; message_block != 0 && iovcnt < iovcnt_max; message_block = message_block->cont ()) { size_t const message_block_length = message_block->length (); // Check if this block has any data to be sent. if (message_block_length > 0) { // Collect the data in the iovec. iov[iovcnt].iov_base = message_block->rd_ptr (); iov[iovcnt].iov_len = static_cast<u_long> (message_block_length); // Increment iovec counter. ++iovcnt; } } } void TAO_Synch_Queued_Message::bytes_transferred (size_t &byte_count) { this->state_changed_i (TAO_LF_Event::LFS_ACTIVE); while (this->current_block_ != 0 && byte_count > 0) { size_t const l = this->current_block_->length (); if (byte_count < l) { this->current_block_->rd_ptr (byte_count); byte_count = 0; return; } byte_count -= l; this->current_block_->rd_ptr (l); this->current_block_ = this->current_block_->cont (); while (this->current_block_ != 0 && this->current_block_->length () == 0) { this->current_block_ = this->current_block_->cont (); } } if (this->current_block_ == 0) this->state_changed (TAO_LF_Event::LFS_SUCCESS, this->orb_core_->leader_follower ()); } TAO_Queued_Message * TAO_Synch_Queued_Message::clone (ACE_Allocator *alloc) { TAO_Synch_Queued_Message *qm = 0; // Clone the message block. // NOTE: We wantedly do the cloning from <current_block_> instead of // starting from <contents_> since we dont want to clone blocks that // have already been sent on the wire. Waste of memory and // associated copying. ACE_Message_Block *mb = this->current_block_->clone (); if (alloc) { ACE_NEW_MALLOC_RETURN (qm, static_cast<TAO_Synch_Queued_Message *> ( alloc->malloc (sizeof (TAO_Synch_Queued_Message))), TAO_Synch_Queued_Message (mb, this->orb_core_, alloc, true), 0); } else { ACE_NEW_RETURN (qm, TAO_Synch_Queued_Message (mb, this->orb_core_, 0, true), 0); } return qm; } void TAO_Synch_Queued_Message::destroy (void) { if (this->own_contents_) { ACE_Message_Block::release (this->contents_); this->current_block_ = 0; this->contents_ = 0; } if (this->is_heap_created_) { // If we have an allocator release the memory to the allocator // pool. if (this->allocator_) { ACE_DES_FREE (this, this->allocator_->free, TAO_Synch_Queued_Message); } else // global release.. { delete this; } } } void TAO_Synch_Queued_Message::copy_if_necessary (const ACE_Message_Block* chain) { if (!this->own_contents_) { // Go through the message block chain looking for the message block // that matches our "current" message block. for (const ACE_Message_Block* mb = chain; mb != 0; mb = mb->cont ()) { if (mb == this->current_block_) { // Once we have found the message block, we need to // clone the current block so that if another thread comes // in and calls reset() on the output stream (via another // invocation on the transport), it doesn't cause the rest // of our message to be released. this->own_contents_ = true; this->contents_ = this->current_block_->clone (); this->current_block_ = this->contents_; break; } } } } TAO_END_VERSIONED_NAMESPACE_DECL
27.223881
82
0.591374
4982369fda4f70dff76a384072ccfc38881b1405
1,961
cpp
C++
libminifi/src/utils/file/PathUtils.cpp
achristianson/nifi-minifi-cpp-experimental
e41101f7f20d0fea287b3a97f2f611988bf1ea12
[ "Apache-2.0" ]
3
2018-01-11T19:48:07.000Z
2019-06-11T09:39:05.000Z
libminifi/src/utils/file/PathUtils.cpp
achristianson/nifi-minifi-cpp-experimental
e41101f7f20d0fea287b3a97f2f611988bf1ea12
[ "Apache-2.0" ]
null
null
null
libminifi/src/utils/file/PathUtils.cpp
achristianson/nifi-minifi-cpp-experimental
e41101f7f20d0fea287b3a97f2f611988bf1ea12
[ "Apache-2.0" ]
1
2019-02-25T19:47:06.000Z
2019-02-25T19:47:06.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 "utils/file/PathUtils.h" #include "utils/file/FileUtils.h" #include <iostream> namespace org { namespace apache { namespace nifi { namespace minifi { namespace utils { namespace file { bool PathUtils::getFileNameAndPath(const std::string &path, std::string &filePath, std::string &fileName) { const std::size_t found = path.find_last_of(FileUtils::get_separator()); /** * Don't make an assumption about about the path, return false for this case. * Could make the assumption that the path is just the file name but with the function named * getFileNameAndPath we expect both to be there ( a fully qualified path ). * */ if (found == std::string::npos || found == path.length() - 1) { return false; } if (found == 0) { filePath = ""; // don't assume that path is not empty filePath += FileUtils::get_separator(); fileName = path.substr(found + 1); return true; } filePath = path.substr(0, found); fileName = path.substr(found + 1); return true; } } /* namespace file */ } /* namespace utils */ } /* namespace minifi */ } /* namespace nifi */ } /* namespace apache */ } /* namespace org */
33.810345
107
0.704233
21a316b503d0458ef2a590ffd7f9f0cc7481d0d4
1,234
cpp
C++
Modeler/ScriptDoc.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
1
2022-02-14T15:46:44.000Z
2022-02-14T15:46:44.000Z
Modeler/ScriptDoc.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
null
null
null
Modeler/ScriptDoc.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
2
2022-01-10T22:17:06.000Z
2022-01-17T09:34:08.000Z
// ScriptDoc.cpp : implementation file // #include "stdafx.h" #ifdef _DEBUG #undef new #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CScriptDoc IMPLEMENT_DYNCREATE(CScriptDoc, CDocument) CScriptDoc::CScriptDoc() { } BOOL CScriptDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; return TRUE; } CScriptDoc::~CScriptDoc() { } BEGIN_MESSAGE_MAP(CScriptDoc, CDocument) //{{AFX_MSG_MAP(CScriptDoc) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CScriptDoc diagnostics #ifdef _DEBUG void CScriptDoc::AssertValid() const { CDocument::AssertValid(); } void CScriptDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CScriptDoc serialization void CScriptDoc::Serialize(CArchive& ar) { ((CEditView*)m_viewList.GetHead())->SerializeRaw(ar); } ///////////////////////////////////////////////////////////////////////////// // CScriptDoc commands
18.984615
77
0.551053
21a4e4a96b4ee13c38d7e855aff3f790b3cc2052
1,696
cpp
C++
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/storage-manager/src/SMLogging.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/storage-manager/src/SMLogging.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/storage-manager/src/SMLogging.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
2
2022-02-27T14:00:01.000Z
2022-03-31T06:24:22.000Z
/* Copyright (C) 2019 MariaDB Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdarg.h> #include <unistd.h> #include "SMLogging.h" using namespace std; namespace { storagemanager::SMLogging *smLog = NULL; boost::mutex m; }; namespace storagemanager { SMLogging::SMLogging() { //TODO: make this configurable setlogmask (LOG_UPTO (LOG_DEBUG)); openlog ("StorageManager", LOG_PID | LOG_NDELAY | LOG_PERROR | LOG_CONS, LOG_LOCAL1); } SMLogging::~SMLogging() { syslog(LOG_INFO, "CloseLog"); closelog(); } SMLogging * SMLogging::get() { if (smLog) return smLog; boost::mutex::scoped_lock s(m); if (smLog) return smLog; smLog = new SMLogging(); return smLog; } void SMLogging::log(int priority,const char *format, ...) { va_list args; va_start(args, format); #ifdef DEBUG va_list args2; va_copy(args2, args); vfprintf(stderr, format, args2); fprintf(stderr, "\n"); va_end(args2); #endif vsyslog(priority, format, args); va_end(args); } }
22.315789
89
0.68809
21a55d0c5e3ca82fd2e04d7ccd567e8d7846fe1a
4,204
cpp
C++
Source/Cache/FrameCache.cpp
Karshilov/Dorothy-SSR
cce19ed2218d76f941977370f6b3894e2f87236a
[ "MIT" ]
43
2020-01-29T02:22:41.000Z
2021-12-06T04:20:12.000Z
Source/Cache/FrameCache.cpp
Jilliana8397/Dorothy-SSR
5ad647909c5e20cb7ebde9a1a054cdb944969dcb
[ "MIT" ]
1
2020-03-19T16:23:12.000Z
2020-03-19T16:23:12.000Z
Source/Cache/FrameCache.cpp
Jilliana8397/Dorothy-SSR
5ad647909c5e20cb7ebde9a1a054cdb944969dcb
[ "MIT" ]
8
2020-03-08T13:46:08.000Z
2021-07-19T11:30:23.000Z
/* Copyright (c) 2021 Jin Li, http://www.luvfight.me Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Const/Header.h" #include "Cache/FrameCache.h" #include "Const/XmlTag.h" #include "Cache/TextureCache.h" #include "Cache/ClipCache.h" #include "Node/Sprite.h" NS_DOROTHY_BEGIN FrameActionDef* FrameCache::loadFrame(String frameStr) { if (Path::getExt(frameStr) == "frame"_slice) return load(frameStr); BLOCK_START { auto parts = frameStr.split("::"_slice); BREAK_IF(parts.size() != 2); FrameActionDef* def = FrameActionDef::create(); def->clipStr = parts.front(); Vec2 origin{}; if (SharedClipCache.isClip(parts.front())) { Texture2D* tex = nullptr; Rect rect; std::tie(tex, rect) = SharedClipCache.loadTexture(parts.front()); origin = rect.origin; } auto tokens = parts.back().split(","_slice); BREAK_IF(tokens.size() != 4); auto it = tokens.begin(); float width = Slice::stof(*it); float height = Slice::stof(*++it); int count = Slice::stoi(*++it); def->duration = Slice::stof(*++it); for (int i = 0; i < count; i++) { def->rects.push_back(New<Rect>(origin.x + i * width, origin.y, width, height)); } return def; } BLOCK_END Warn("invalid frame str not load: \"{}\".", frameStr); return nullptr; } bool FrameCache::isFrame(String frameStr) const { auto parts = frameStr.split("::"_slice); if (parts.size() == 1) return Path::getExt(parts.front()) == "frame"_slice; else if (parts.size() == 2) return parts.back().split(","_slice).size() == 4; else return false; } std::shared_ptr<XmlParser<FrameActionDef>> FrameCache::prepareParser(String filename) { return std::shared_ptr<XmlParser<FrameActionDef>>(new Parser(FrameActionDef::create(), Path::getPath(filename))); } void FrameCache::Parser::xmlSAX2Text(const char* s, size_t len) { } void FrameCache::Parser::xmlSAX2StartElement(const char* name, size_t len, const std::vector<AttrSlice>& attrs) { switch (Xml::Frame::Element(name[0])) { case Xml::Frame::Element::Dorothy: { for (int i = 0; attrs[i].first != nullptr;i++) { switch (Xml::Frame::Dorothy(attrs[i].first[0])) { case Xml::Frame::Dorothy::File: { Slice file(attrs[++i]); std::string localFile = Path::concat({_path, file}); _item->clipStr = SharedContent.exist(localFile) ? localFile : file.toString(); break; } case Xml::Frame::Dorothy::Duration: _item->duration = s_cast<float>(std::atof(attrs[++i].first)); break; } } break; } case Xml::Frame::Element::Clip: { for (int i = 0; attrs[i].first != nullptr; i++) { switch (Xml::Frame::Clip(attrs[i].first[0])) { case Xml::Frame::Clip::Rect: { Slice attr(attrs[++i]); auto tokens = attr.split(","); AssertUnless(tokens.size() == 4, "invalid clip rect str for: \"{}\"", attr); auto it = tokens.begin(); float x = Slice::stof(*it); float y = Slice::stof(*++it); float w = Slice::stof(*++it); float h = Slice::stof(*++it); _item->rects.push_back(New<Rect>(x, y, w, h)); break; } } } break; } } } void FrameCache::Parser::xmlSAX2EndElement(const char* name, size_t len) { } NS_DOROTHY_END
34.178862
463
0.672217
21a5dad926c4e000099bd64e80dadf40be432e3f
381
hpp
C++
src/delta.hpp
crockeo/hc
a5f9eaa1051e8825fa765d120d8ea76682909a5a
[ "MIT" ]
null
null
null
src/delta.hpp
crockeo/hc
a5f9eaa1051e8825fa765d120d8ea76682909a5a
[ "MIT" ]
null
null
null
src/delta.hpp
crockeo/hc
a5f9eaa1051e8825fa765d120d8ea76682909a5a
[ "MIT" ]
null
null
null
#ifndef _DELTA_HPP_ #define _DELTA_HPP_ ////////// // Code // // Getting the current system time in milliseconds. int getTimeMillis(); // A utility to do some delta timing stuff. class Delta { private: int last, curr; bool first; public: // Constructing a delta. Delta(); // Getting the time since the last time this was run. float since(); }; #endif
15.24
57
0.650919
21a5f501ef3650eec5efbe46f08a594997b372d5
652
cpp
C++
Codeforces/A_Games.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
Codeforces/A_Games.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
Codeforces/A_Games.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define endl "\n" #define pi acos(-1) #define faster_io ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); using namespace std; int main() { //freopen("/home/sohel/Documents/my_codes/out.txt", "wt", stdout); faster_io; int n, cnt_rep = 0, cnt = 0; cin >> n; int h[n], a[n]; for (int i = 0; i < n; i++) { cin >> h[i] >> a[i]; } for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (h[i] == a[j]) cnt++; if(a[i] == h[j]) cnt++; } } cout << cnt << endl; return 0; }
21.733333
77
0.435583
21a61f52b9ddbd1d42dcc22dee17ed910b20266f
6,950
hpp
C++
include/crocoddyl/multibody/frames.hpp
ggory15/crocoddyl
4708428676f596f93ffe2df739faeb5cc38d2326
[ "BSD-3-Clause" ]
null
null
null
include/crocoddyl/multibody/frames.hpp
ggory15/crocoddyl
4708428676f596f93ffe2df739faeb5cc38d2326
[ "BSD-3-Clause" ]
null
null
null
include/crocoddyl/multibody/frames.hpp
ggory15/crocoddyl
4708428676f596f93ffe2df739faeb5cc38d2326
[ "BSD-3-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (C) 2018-2020, LAAS-CNRS, University of Edinburgh // Copyright note valid unless otherwise stated in individual files. // All rights reserved. /////////////////////////////////////////////////////////////////////////////// #ifndef CROCODDYL_MULTIBODY_FRAMES_HPP_ #define CROCODDYL_MULTIBODY_FRAMES_HPP_ #include "crocoddyl/multibody/fwd.hpp" #include "crocoddyl/multibody/friction-cone.hpp" #include "crocoddyl/core/mathbase.hpp" #include <pinocchio/spatial/se3.hpp> #include <pinocchio/spatial/motion.hpp> #include <pinocchio/spatial/force.hpp> namespace crocoddyl { typedef std::size_t FrameIndex; template <typename _Scalar> struct FrameTranslationTpl { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef typename MathBaseTpl<Scalar>::Vector3s Vector3s; explicit FrameTranslationTpl() : frame(0), oxf(Vector3s::Zero()) {} FrameTranslationTpl(const FrameTranslationTpl<Scalar>& value) : frame(value.frame), oxf(value.oxf) {} FrameTranslationTpl(const FrameIndex& frame, const Vector3s& oxf) : frame(frame), oxf(oxf) {} friend std::ostream& operator<<(std::ostream& os, const FrameTranslationTpl<Scalar>& X) { os << " frame: " << X.frame << std::endl << "translation: " << std::endl << X.oxf.transpose() << std::endl; return os; } FrameIndex frame; Vector3s oxf; }; template <typename _Scalar> struct FrameRotationTpl { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef typename MathBaseTpl<Scalar>::Matrix3s Matrix3s; explicit FrameRotationTpl() : frame(0), oRf(Matrix3s::Identity()) {} FrameRotationTpl(const FrameRotationTpl<Scalar>& value) : frame(value.frame), oRf(value.oRf) {} FrameRotationTpl(const FrameIndex& frame, const Matrix3s& oRf) : frame(frame), oRf(oRf) {} friend std::ostream& operator<<(std::ostream& os, const FrameRotationTpl<Scalar>& X) { os << " frame: " << X.frame << std::endl << "rotation: " << std::endl << X.oRf << std::endl; return os; } FrameIndex frame; Matrix3s oRf; }; template <typename _Scalar> struct FramePlacementTpl { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef pinocchio::SE3Tpl<Scalar> SE3; explicit FramePlacementTpl() : frame(0), oMf(SE3::Identity()) {} FramePlacementTpl(const FramePlacementTpl<Scalar>& value) : frame(value.frame), oMf(value.oMf) {} FramePlacementTpl(const FrameIndex& frame, const SE3& oMf) : frame(frame), oMf(oMf) {} friend std::ostream& operator<<(std::ostream& os, const FramePlacementTpl<Scalar>& X) { os << " frame: " << X.frame << std::endl << "placement: " << std::endl << X.oMf << std::endl; return os; } FrameIndex frame; pinocchio::SE3Tpl<Scalar> oMf; }; template <typename _Scalar> struct FrameMotionTpl { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef pinocchio::MotionTpl<Scalar> Motion; explicit FrameMotionTpl() : frame(0), oMf(Motion::Zero()) {} FrameMotionTpl(const FrameMotionTpl<Scalar>& value) : frame(value.frame), oMf(value.oMf) {} FrameMotionTpl(const FrameIndex& frame, const Motion& oMf) : frame(frame), oMf(oMf) {} friend std::ostream& operator<<(std::ostream& os, const FrameMotionTpl<Scalar>& X) { os << " frame: " << X.frame << std::endl << "motion: " << std::endl << X.oMf << std::endl; return os; } FrameIndex frame; pinocchio::MotionTpl<Scalar> oMf; }; template <typename _Scalar> struct FrameForceTpl { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef pinocchio::ForceTpl<Scalar> Force; explicit FrameForceTpl() : frame(0), oFf(Force::Zero()) {} FrameForceTpl(const FrameForceTpl<Scalar>& value) : frame(value.frame), oFf(value.oFf) {} FrameForceTpl(const FrameIndex& frame, const Force& oFf) : frame(frame), oFf(oFf) {} friend std::ostream& operator<<(std::ostream& os, const FrameForceTpl<Scalar>& X) { os << "frame: " << X.frame << std::endl << "force: " << std::endl << X.oFf << std::endl; return os; } FrameIndex frame; pinocchio::ForceTpl<Scalar> oFf; }; template <typename _Scalar> struct FrameFrictionConeTpl { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef FrictionConeTpl<Scalar> FrictionCone; explicit FrameFrictionConeTpl() : frame(0), oRf(FrictionCone()) {} FrameFrictionConeTpl(const FrameFrictionConeTpl<Scalar>& value) : frame(value.frame), oRf(value.oRf) {} FrameFrictionConeTpl(const FrameIndex& frame, const FrictionCone& oRf) : frame(frame), oRf(oRf) {} friend std::ostream& operator<<(std::ostream& os, const FrameFrictionConeTpl& X) { os << "frame: " << X.frame << std::endl << " cone: " << std::endl << X.oRf << std::endl; return os; } FrameIndex frame; FrictionCone oRf; }; template <typename _Scalar> class FrameCoPSupportTpl { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef typename MathBaseTpl<Scalar>::Vector2s Vector2s; typedef typename MathBaseTpl<Scalar>::Vector3s Vector3s; typedef Eigen::Matrix<Scalar, 4, 6> Matrix46; public: explicit FrameCoPSupportTpl() : frame_(0), support_region_(Vector2s::Zero()) { update_A(); } FrameCoPSupportTpl(const FrameCoPSupportTpl<Scalar>& value) : frame_(value.get_frame()), support_region_(value.get_support_region()), A_(value.get_A()) {} FrameCoPSupportTpl(const FrameIndex& frame, const Vector2s& support_region) : frame_(frame), support_region_(support_region) { update_A(); } friend std::ostream& operator<<(std::ostream& os, const FrameCoPSupportTpl<Scalar>& X) { os << " frame: " << X.get_frame() << std::endl << "foot dimensions: " << std::endl << X.get_support_region() << std::endl; return os; } // Define the inequality matrix A to implement A * f >= 0. Compare eq.(18-19) in // https://hal.archives-ouvertes.fr/hal-02108449/document void update_A() { A_ << Scalar(0), Scalar(0), support_region_[0] / Scalar(2), Scalar(0), Scalar(-1), Scalar(0), Scalar(0), Scalar(0), support_region_[0] / Scalar(2), Scalar(0), Scalar(1), Scalar(0), Scalar(0), Scalar(0), support_region_[1] / Scalar(2), Scalar(1), Scalar(0), Scalar(0), Scalar(0), Scalar(0), support_region_[1] / Scalar(2), Scalar(-1), Scalar(0), Scalar(0); } void set_frame(FrameIndex frame) { frame_ = frame; } void set_support_region(const Vector2s& support_region) { support_region_ = support_region; update_A(); } const FrameIndex& get_frame() const { return frame_; } const Vector2s& get_support_region() const { return support_region_; } const Matrix46& get_A() const { return A_; } private: FrameIndex frame_; //!< contact frame ID Vector2s support_region_; //!< cop support region = (length, width) Matrix46 A_; //!< inequality matrix }; } // namespace crocoddyl #endif // CROCODDYL_MULTIBODY_FRAMES_HPP_
36.387435
119
0.684029
21a8243a1b25a7c9c5eb843cc756b8ef79e3e2ad
789
cpp
C++
src/cpp/common/acsNtripStream.cpp
RodrigoNaves/ginan-bitbucket-update-tests
4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c
[ "Apache-2.0" ]
73
2021-07-08T23:35:08.000Z
2022-03-31T15:17:58.000Z
src/cpp/common/acsNtripStream.cpp
RodrigoNaves/ginan-bitbucket-update-tests
4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c
[ "Apache-2.0" ]
5
2021-09-27T14:27:32.000Z
2022-03-21T23:50:02.000Z
src/cpp/common/acsNtripStream.cpp
RodrigoNaves/ginan-bitbucket-update-tests
4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c
[ "Apache-2.0" ]
39
2021-07-12T05:42:51.000Z
2022-03-31T15:15:34.000Z
#include "acsNtripStream.hpp" #include <boost/system/error_code.hpp> #include <list> void NtripStream::getData() { receivedDataBufferMtx.lock(); //if ( receivedDataBuffer.size() > 0 ) // BOOST_LOG_TRIVIAL(debug) << "NtripStream::getData(), receivedDataBuffer.size() = " << receivedDataBuffer.size() << std::endl; receivedData.insert(receivedData.end(), receivedDataBuffer.begin(), receivedDataBuffer.end()); receivedDataBuffer.clear(); receivedDataBufferMtx.unlock(); } void NtripStream::connected() { start_read_stream(); } bool NtripStream::dataChunkDownloaded(vector<char> dataChunk) { receivedDataBufferMtx.lock(); for ( int j = 0; j < chunked_message_length; j++ ) receivedDataBuffer.push_back(dataChunk[j]); receivedDataBufferMtx.unlock(); return false; }
24.65625
132
0.737643
21a952cc62ec9b8ea87fefe5b7244690c6ca0878
2,637
cpp
C++
tests/brica2/core/module.cpp
wbap/dcdfa
e8082b5239ebbfdb12645cb3cd225082cf36f249
[ "Apache-2.0" ]
1
2020-04-30T11:38:00.000Z
2020-04-30T11:38:00.000Z
tests/brica2/core/module.cpp
wbap/dcdfa
e8082b5239ebbfdb12645cb3cd225082cf36f249
[ "Apache-2.0" ]
null
null
null
tests/brica2/core/module.cpp
wbap/dcdfa
e8082b5239ebbfdb12645cb3cd225082cf36f249
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * * brica2/core/module.cpp * * Copyright (C) 2016 Kotone Itaya * * 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 "brica2/core/module.hpp" #include "gtest/gtest.h" namespace brica2 { namespace core { class MyComponent : public Component { public: Dictionary operator()(Dictionary& inputs) { return Dictionary(); } }; TEST(Module, Simple) { Module m0; MyComponent mc0; MyComponent mc1; Cargo c0; Cargo c1; Cargo c2; Cargo c3; c0 = 42; c1 = 43; mc0.make_in_port("in", c0); mc0.make_out_port("out", c1); c2 = mc0.get_in_port("in").get_buffer(); c3 = mc0.get_out_port("out").get_buffer(); ASSERT_EQ(c0.get<int>(), c2.get<int>()); ASSERT_EQ(c1.get<int>(), c3.get<int>()); m0.add_component("mc0", mc0); mc1 = m0.get_component<MyComponent>("mc0"); c2 = mc1.get_in_port("in").get_buffer(); c3 = mc1.get_out_port("out").get_buffer(); ASSERT_EQ(c0.get<int>(), c2.get<int>()); ASSERT_EQ(c1.get<int>(), c3.get<int>()); } TEST(Module, Submodule) { Module m0; Module m1; Module m2; MyComponent mc0; MyComponent mc1; Cargo c0; Cargo c1; Cargo c2; Cargo c3; c0 = 42; c1 = 43; mc0.make_in_port("in", c0); mc0.make_out_port("out", c1); c2 = mc0.get_in_port("in").get_buffer(); c3 = mc0.get_out_port("out").get_buffer(); ASSERT_EQ(c0.get<int>(), c2.get<int>()); ASSERT_EQ(c1.get<int>(), c3.get<int>()); m0.add_submodule("m1", m1); m1.add_component("mc0", mc0); m2 = m0.get_submodule("m1"); mc1 = m2.get_component<MyComponent>("mc0"); c2 = mc1.get_in_port("in").get_buffer(); c3 = mc1.get_out_port("out").get_buffer(); ASSERT_EQ(c0.get<int>(), c2.get<int>()); ASSERT_EQ(c1.get<int>(), c3.get<int>()); } } }
23.544643
79
0.629882
21a97cdb8a3aca9743c770e22e6a6be248f6da18
1,163
cpp
C++
bzoj/1064.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
bzoj/1064.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
bzoj/1064.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> using namespace std; inline int read(){ int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+ch-'0';ch=getchar();} return x*f; } const int inf = 1<<30; int n, m, cnt, maxn, minx, ans, tmp; struct edge{int to,nxt,val;}e[2000020]; int head[100020], vis[100020], mark[100020]; void ins(int x, int y, int v){ e[++cnt].nxt = head[x]; e[cnt].to = y; e[head[x]=cnt].val = v; } void ins(int x, int y){ ins(x, y, 1); ins(y, x, -1); } int gcd(int a, int b){return b?gcd(b, a%b):a;} void dfs(int x, int len){ if(vis[x]){ans = gcd(ans, abs(mark[x]-len)); return;} vis[x] = 1; mark[x] = len; maxn = max(maxn, len); minx = min(minx, len); for(int i = head[x]; i; i=e[i].nxt) dfs(e[i].to, len+e[i].val); } int main(){ n=read(); m=read(); for(int i = 1,x,y; i <= m; i++){ x=read();y=read(); ins(x, y); } for(int i = 1; i <= n; i++){ if(vis[i]) continue; minx = inf; maxn = -inf; dfs(i, 1); tmp += maxn-minx+1; } int ans2 = 3; if(!ans) ans = tmp; else while(ans2<=ans&&ans%ans2)ans2++; if(ans<3) puts("-1 -1"); else printf("%d %d\n", ans, ans2); }
24.744681
62
0.545142
21afeaaaffd32f0e17161a02333cff232f80cdef
790
hpp
C++
src/beast/include/beast/core/detail/clamp.hpp
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
5
2018-02-02T04:50:43.000Z
2020-10-14T08:15:01.000Z
src/beast/include/beast/core/detail/clamp.hpp
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
10
2019-01-07T05:33:34.000Z
2020-07-15T00:09:26.000Z
src/beast/include/beast/core/detail/clamp.hpp
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
4
2017-06-06T12:49:07.000Z
2021-07-01T07:44:49.000Z
// // Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BEAST_CORE_DETAIL_CLAMP_HPP #define BEAST_CORE_DETAIL_CLAMP_HPP #include <limits> #include <cstdlib> namespace beast { namespace detail { template<class UInt> static std::size_t clamp(UInt x) { if(x >= (std::numeric_limits<std::size_t>::max)()) return (std::numeric_limits<std::size_t>::max)(); return static_cast<std::size_t>(x); } template<class UInt> static std::size_t clamp(UInt x, std::size_t limit) { if(x >= limit) return limit; return static_cast<std::size_t>(x); } } // detail } // beast #endif
19.268293
79
0.696203
21b0580c4ba426b315ac89f33121ce92e45e01e7
1,098
cpp
C++
src/main.cpp
rathyon/xgp
8aba899746665d4d6afd51c9e83d5065e2f51abb
[ "MIT" ]
null
null
null
src/main.cpp
rathyon/xgp
8aba899746665d4d6afd51c9e83d5065e2f51abb
[ "MIT" ]
null
null
null
src/main.cpp
rathyon/xgp
8aba899746665d4d6afd51c9e83d5065e2f51abb
[ "MIT" ]
null
null
null
#include "XGPApp.h" using namespace xgp; XGPApp* app; void errorCallback(int error, const char* description) { app->errorCallback(error, description); } void reshapeCallback(GLFWwindow* window, int width, int height) { app->reshapeCallback(width, height); } void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { app->keyCallback(key, scancode, action, mods); } void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods) { app->mouseButtonCallback(button, action, mods); } void mousePosCallback(GLFWwindow* window, double xpos, double ypos) { app->mousePosCallback(xpos, ypos); } int main() { app = new XGPApp("XGP - eXperimental Graphics Program", 640, 480); app->init(); //Set callbacks glfwSetErrorCallback(errorCallback); glfwSetFramebufferSizeCallback(app->window(), reshapeCallback); glfwSetKeyCallback(app->window(), keyCallback); glfwSetMouseButtonCallback(app->window(), mouseButtonCallback); glfwSetCursorPosCallback(app->window(), mousePosCallback); app->loop(); app->cleanup(); delete app; exit(EXIT_SUCCESS); }
26.780488
83
0.752277
21b6c0fcfb8354aeeebc7f80a886fac90f1979fc
2,318
cpp
C++
odevice/app/src/main/jni/ParallelME/runtime/src/parallelme/Runtime.cpp
rcarvs/android-ocr
f8760afd378607ced0beca0b2c1beda14ea4ab49
[ "MIT" ]
5
2016-08-09T17:09:46.000Z
2020-12-12T21:17:33.000Z
src/parallelme/Runtime.cpp
ParallelME/runtime
80c3104c88e8efe9e4d746aa2976702c84f6302d
[ "Apache-2.0" ]
12
2016-04-07T19:42:02.000Z
2017-06-12T13:37:50.000Z
src/parallelme/Runtime.cpp
ParallelME/runtime
80c3104c88e8efe9e4d746aa2976702c84f6302d
[ "Apache-2.0" ]
2
2017-04-07T20:31:10.000Z
2021-04-19T23:24:38.000Z
/* _ __ ____ * _ __ ___ _____ ___ __ __ ___ __ / | / / __/ * | _ \/ _ | _ | / _ | / / / / / __/ / / | / / /__ * | __/ __ | ___|/ __ |/ /_/ /__/ __/ /__ / / v / /__ * |_| /_/ |_|_|\_\/_/ |_/____/___/___/____/ /_/ /_/____/ * */ #include <parallelme/Runtime.hpp> #include <parallelme/Task.hpp> #include "Worker.hpp" #include "dynloader/dynLoader.h" using namespace parallelme; Runtime::~Runtime() = default; void Runtime::loadDevices() { if(!dynLoadOpenCL()) throw RuntimeConstructionError("No OpenCL devices found."); int err; // Get the number of platforms. unsigned numPlatforms; err = clGetPlatformIDs(0, nullptr, &numPlatforms); if(err < 0) throw RuntimeConstructionError(std::to_string(err)); // Get the platforms. auto platforms = std::unique_ptr<cl_platform_id []>{new cl_platform_id[numPlatforms]}; err = clGetPlatformIDs(numPlatforms, platforms.get(), nullptr); if(err < 0) throw RuntimeConstructionError(std::to_string(err)); // Initialize the devices for each platform. for(unsigned i = 0; i < numPlatforms; ++i) { unsigned numDevices; err = clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_ALL, 0, nullptr, &numDevices); if(err < 0) throw RuntimeConstructionError(std::to_string(err)); std::unique_ptr<cl_device_id []> devices{new cl_device_id[numDevices]}; err = clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_ALL, numDevices, devices.get(), nullptr); if(err < 0) throw RuntimeConstructionError(std::to_string(err)); for(unsigned j = 0; j < numDevices; ++j) _devices.push_back(std::make_shared<Device>(devices[j])); } } void Runtime::startWorkers(JavaVM *jvm) { for(auto &device : _devices) _workers.push_back(std::make_shared<Worker>(device)); for(auto &worker : _workers) worker->run(_scheduler, jvm); } void Runtime::submitTask(std::unique_ptr<Task> task) { _scheduler->push(std::move(task)); for(auto &worker : _workers) worker->wakeUp(); } void Runtime::finish() { _scheduler->waitUntilIdle(); for(auto &worker : _workers) worker->finish(); }
30.5
79
0.597929
21b7b165f624e89398583caebcbdf007153ffcea
6,181
cpp
C++
qmk_firmware/quantum/serial_link/tests/transport_tests.cpp
igagis/best84kb
e4f58e0138b0835b39e636d69658183a8e74594e
[ "MIT" ]
2
2019-05-13T05:19:02.000Z
2021-11-29T09:07:43.000Z
qmk_firmware/quantum/serial_link/tests/transport_tests.cpp
igagis/best84kb
e4f58e0138b0835b39e636d69658183a8e74594e
[ "MIT" ]
null
null
null
qmk_firmware/quantum/serial_link/tests/transport_tests.cpp
igagis/best84kb
e4f58e0138b0835b39e636d69658183a8e74594e
[ "MIT" ]
1
2020-11-05T02:23:49.000Z
2020-11-05T02:23:49.000Z
/* The MIT License (MIT) Copyright (c) 2016 Fred Sundvik Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "gtest/gtest.h" #include "gmock/gmock.h" using testing::_; using testing::ElementsAreArray; using testing::Args; extern "C" { #include "serial_link/protocol/transport.h" } struct test_object1 { uint32_t test; }; struct test_object2 { uint32_t test1; uint32_t test2; }; MASTER_TO_ALL_SLAVES_OBJECT(master_to_slave, test_object1); MASTER_TO_SINGLE_SLAVE_OBJECT(master_to_single_slave, test_object1); SLAVE_TO_MASTER_OBJECT(slave_to_master, test_object1); static remote_object_t* test_remote_objects[] = { REMOTE_OBJECT(master_to_slave), REMOTE_OBJECT(master_to_single_slave), REMOTE_OBJECT(slave_to_master), }; class Transport : public testing::Test { public: Transport() { Instance = this; add_remote_objects(test_remote_objects, sizeof(test_remote_objects) / sizeof(remote_object_t*)); } ~Transport() { Instance = nullptr; reinitialize_serial_link_transport(); } MOCK_METHOD0(signal_data_written, void ()); MOCK_METHOD1(router_send_frame, void (uint8_t destination)); void router_send_frame(uint8_t destination, uint8_t* data, uint16_t size) { router_send_frame(destination); std::copy(data, data + size, std::back_inserter(sent_data)); } static Transport* Instance; std::vector<uint8_t> sent_data; }; Transport* Transport::Instance = nullptr; extern "C" { void signal_data_written(void) { Transport::Instance->signal_data_written(); } void router_send_frame(uint8_t destination, uint8_t* data, uint16_t size) { Transport::Instance->router_send_frame(destination, data, size); } } TEST_F(Transport, write_to_local_signals_an_event) { begin_write_master_to_slave(); EXPECT_CALL(*this, signal_data_written()); end_write_master_to_slave(); begin_write_slave_to_master(); EXPECT_CALL(*this, signal_data_written()); end_write_slave_to_master(); begin_write_master_to_single_slave(1); EXPECT_CALL(*this, signal_data_written()); end_write_master_to_single_slave(1); } TEST_F(Transport, writes_from_master_to_all_slaves) { update_transport(); test_object1* obj = begin_write_master_to_slave(); obj->test = 5; EXPECT_CALL(*this, signal_data_written()); end_write_master_to_slave(); EXPECT_CALL(*this, router_send_frame(0xFF)); update_transport(); transport_recv_frame(0, sent_data.data(), sent_data.size()); test_object1* obj2 = read_master_to_slave(); EXPECT_NE(obj2, nullptr); EXPECT_EQ(obj2->test, 5); } TEST_F(Transport, writes_from_slave_to_master) { update_transport(); test_object1* obj = begin_write_slave_to_master(); obj->test = 7; EXPECT_CALL(*this, signal_data_written()); end_write_slave_to_master(); EXPECT_CALL(*this, router_send_frame(0)); update_transport(); transport_recv_frame(3, sent_data.data(), sent_data.size()); test_object1* obj2 = read_slave_to_master(2); EXPECT_EQ(read_slave_to_master(0), nullptr); EXPECT_NE(obj2, nullptr); EXPECT_EQ(obj2->test, 7); } TEST_F(Transport, writes_from_master_to_single_slave) { update_transport(); test_object1* obj = begin_write_master_to_single_slave(3); obj->test = 7; EXPECT_CALL(*this, signal_data_written()); end_write_master_to_single_slave(3); EXPECT_CALL(*this, router_send_frame(4)); update_transport(); transport_recv_frame(0, sent_data.data(), sent_data.size()); test_object1* obj2 = read_master_to_single_slave(); EXPECT_NE(obj2, nullptr); EXPECT_EQ(obj2->test, 7); } TEST_F(Transport, ignores_object_with_invalid_id) { update_transport(); test_object1* obj = begin_write_master_to_single_slave(3); obj->test = 7; EXPECT_CALL(*this, signal_data_written()); end_write_master_to_single_slave(3); EXPECT_CALL(*this, router_send_frame(4)); update_transport(); sent_data[sent_data.size() - 1] = 44; transport_recv_frame(0, sent_data.data(), sent_data.size()); test_object1* obj2 = read_master_to_single_slave(); EXPECT_EQ(obj2, nullptr); } TEST_F(Transport, ignores_object_with_size_too_small) { update_transport(); test_object1* obj = begin_write_master_to_slave(); obj->test = 7; EXPECT_CALL(*this, signal_data_written()); end_write_master_to_slave(); EXPECT_CALL(*this, router_send_frame(_)); update_transport(); sent_data[sent_data.size() - 2] = 0; transport_recv_frame(0, sent_data.data(), sent_data.size() - 1); test_object1* obj2 = read_master_to_slave(); EXPECT_EQ(obj2, nullptr); } TEST_F(Transport, ignores_object_with_size_too_big) { update_transport(); test_object1* obj = begin_write_master_to_slave(); obj->test = 7; EXPECT_CALL(*this, signal_data_written()); end_write_master_to_slave(); EXPECT_CALL(*this, router_send_frame(_)); update_transport(); sent_data.resize(sent_data.size() + 22); sent_data[sent_data.size() - 1] = 0; transport_recv_frame(0, sent_data.data(), sent_data.size()); test_object1* obj2 = read_master_to_slave(); EXPECT_EQ(obj2, nullptr); }
32.703704
104
0.738554
21b88a1bc63738d366059fd2350f9b6bfde5e44c
579
cpp
C++
src/tlsh_c.cpp
HoundThe/tlsh
e84e854b56b6f0ecbbf2d122a2a128b1b60a2a67
[ "BSD-3-Clause" ]
null
null
null
src/tlsh_c.cpp
HoundThe/tlsh
e84e854b56b6f0ecbbf2d122a2a128b1b60a2a67
[ "BSD-3-Clause" ]
null
null
null
src/tlsh_c.cpp
HoundThe/tlsh
e84e854b56b6f0ecbbf2d122a2a128b1b60a2a67
[ "BSD-3-Clause" ]
null
null
null
#include "tlsh_c.h" #include "tlsh.h" TLSH *TLSH_new() { return reinterpret_cast<TLSH *>(new Tlsh); } void TLSH_update(TLSH *tlsh, const unsigned char *data, unsigned int len) { reinterpret_cast<Tlsh *>(tlsh)->update(data, len); } void TLSH_final(TLSH *tlsh, const unsigned char *data, unsigned int len, int fc_cons_option) { reinterpret_cast<Tlsh *>(tlsh)->final(data, len, fc_cons_option); } const char *TLSH_hash(TLSH *tlsh) { return reinterpret_cast<Tlsh *>(tlsh)->getHash(); void TLSH_free(TLSH * tlsh) { delete reinterpret_cast<TLSH *>(tlsh); } }
34.058824
75
0.697755
21c04010e161eed4e3d4bc7c6c16d1be21dec5af
2,977
hpp
C++
src/number_theory/modulo.hpp
RamchandraApte/OmniTemplate
f150f451871b0ab43ac39a798186278106da1527
[ "MIT" ]
14
2019-04-23T21:44:12.000Z
2022-03-04T22:48:59.000Z
src/number_theory/modulo.hpp
RamchandraApte/OmniTemplate
f150f451871b0ab43ac39a798186278106da1527
[ "MIT" ]
3
2019-04-25T10:45:32.000Z
2020-08-05T22:40:39.000Z
src/number_theory/modulo.hpp
RamchandraApte/OmniTemplate
f150f451871b0ab43ac39a798186278106da1527
[ "MIT" ]
1
2020-07-16T22:16:33.000Z
2020-07-16T22:16:33.000Z
#pragma once #include "core/all.hpp" namespace modulo_namespace { template <typename... Args> using invert_t = decltype(invert(std::declval<Args>()...)); /*! @brief Returns \f$a^b\f$ * @param a the base * @param b the exponent * * Time complexity: \f$O(\log_2 |b|)\f$ multiplications */ template <typename T> T power(T a, ll b) { if (b < 0) { if constexpr (experimental::is_detected_v<invert_t, multiplies<>, decltype(a)>) { a = invert(multiplies{}, a); b = -b; } else { assert(("b < 0 but unable to inverse a", false)); } } T ret = identity(multiplies<>{}, a); for (; b; b >>= 1, a *= a) { if (b & 1) { ret *= a; } } return ret; } /*! @brief Returns the remainder of a divided by b as a nonnegative integer in [0, b).*/ ll mod(ll a, const ll b) { a %= b; if (a < 0) { a += b; } return a; } /*! Set a to the remainder when divided by b. */ ll mod_eq(ll &a, const ll b) { return a = mod(a, b); } /*! no_mod tag class allows a modulo object to be quickly constructed from an integer in the range * [0, b) without performing a modulo operation.*/ struct no_mod {}; struct modulo { inline static ll modulus = 1e9 + 7; //!< Modulus used for operations like modular multiplication /*! Modular arithmetic class */ ll x; //!< The representative element, which is in [0, M) modulo() : x{0LL} {} template <typename T, typename = enable_if_t<is_integral<T>::value, void>> modulo(T x_) : x(mod(x_, modulo::modulus)) {} modulo(ll x_, no_mod) : x(x_) {} explicit operator auto() const { return x; } }; modulo operator"" _M(const unsigned long long x) { return modulo{x}; } modulo identity(plus<>, modulo) { return 0; } modulo identity(multiplies<>, modulo) { return 1; } modulo operator+(modulo const &a, modulo const &b) { ll const sum = a.x + b.x; return {sum >= modulo::modulus ? sum - modulo::modulus : sum, no_mod{}}; } modulo operator++(modulo &a) { return a += 1; } modulo operator-(modulo const &a) { return {modulo::modulus - a.x, no_mod{}}; } // To avoid ADL issues using ::operator-; bin(==, modulo); modulo operator*(modulo const &a, modulo const &b) { /*! Computes a times b modulo modulo::modulus using long double */ const ull quot = ld(a.x) * ld(b.x) / ld(modulo::modulus); // Computes the approximate remainder const ll rem = ull(a.x) * ull(b.x) - ull(modulo::modulus) * quot; if (rem < 0) { return {rem + modulo::modulus, no_mod{}}; } if (rem >= modulo::modulus) { return {rem - modulo::modulus, no_mod{}}; } return {rem, no_mod{}}; } modulo invert(multiplies<>, modulo const &b) { /*! Computes the modular inverse \f$b^{-1} \pmod{M}\f$ */ assert(b != 0); return power(b, modulo::modulus - 2); } using ::operator/; template <typename Stream> auto &operator<<(Stream &os, modulo const &m) { return os << m.x; } } // namespace modulo_namespace using namespace modulo_namespace; namespace std { template <> struct hash<modulo> { ll operator()(modulo const &x) const { return x.x; } }; } // namespace std
32.714286
98
0.642257
21cb346ca25d20a839156d4a39c533e1731addd1
737
cpp
C++
Questions Level-Wise/Hard/find-minimum-in-rotated-sorted-array-ii.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
2
2021-03-05T22:32:23.000Z
2021-03-05T22:32:29.000Z
Questions Level-Wise/Hard/find-minimum-in-rotated-sorted-array-ii.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
Questions Level-Wise/Hard/find-minimum-in-rotated-sorted-array-ii.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
class Solution { public: int binarysearch(vector<int> nums,int l,int h) { while(l<h) { int mid=(h-l)/2+l; if(nums[l]<nums[h]) return nums[l]; else if(l+1==h) return nums[h]; else if(nums[l]>=nums[mid]&&nums[mid]<=nums[h]) { int temp1=binarysearch(nums,l,mid); int temp2=binarysearch(nums,mid,h); if(temp1<temp2) return temp1; return temp2; } else l=mid; } return nums[0]; } int findMin(vector<int>& nums) { return binarysearch(nums,0,nums.size()-1); } };
24.566667
59
0.419267
21cca6a5317fcb2283a18c2ce3170313a1fa433f
757
cpp
C++
locs.cpp
yurivict/crate
cf25e21ad2b7bce320c5d04a6ad27c8e67d4e09f
[ "BSD-3-Clause" ]
14
2019-08-04T13:03:10.000Z
2021-03-14T13:19:55.000Z
locs.cpp
yurivict/crate
cf25e21ad2b7bce320c5d04a6ad27c8e67d4e09f
[ "BSD-3-Clause" ]
null
null
null
locs.cpp
yurivict/crate
cf25e21ad2b7bce320c5d04a6ad27c8e67d4e09f
[ "BSD-3-Clause" ]
2
2020-05-08T04:52:13.000Z
2021-03-14T13:20:38.000Z
// Copyright (C) 2019 by Yuri Victorovich. All rights reserved. #include "locs.h" #include "util.h" #include <string> namespace Locations { const char *jailDirectoryPath = "/var/run/crate"; const char *jailSubDirectoryIfaces = "/ifaces"; const char *cacheDirectoryPath = "/var/cache/crate"; const std::string ctxFwUsersFilePath = std::string(jailDirectoryPath) + "/ctx-firewall-users"; const std::string baseArchive = std::string(Locations::cacheDirectoryPath) + "/base.txz"; const std::string baseArchiveUrl = STRg("ftp://ftp1.freebsd.org/pub/FreeBSD/snapshots/" << Util::getSysctlString("hw.machine") << "/" << Util::getSysctlString("kern.osrelease") << "/base.txz"); }
37.85
128
0.652576
21d0edae97d5d9f1b8d6bc3ff5d01a05b2e4fd7a
1,797
cpp
C++
oneEngine/oneGame/source/engine/physics/collider/types/CBoxCollider.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
8
2017-12-08T02:59:31.000Z
2022-02-02T04:30:03.000Z
oneEngine/oneGame/source/engine/physics/collider/types/CBoxCollider.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
2
2021-04-16T03:44:42.000Z
2021-08-30T06:48:44.000Z
oneEngine/oneGame/source/engine/physics/collider/types/CBoxCollider.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
1
2021-04-16T02:09:54.000Z
2021-04-16T02:09:54.000Z
#include "engine/physics/motion/CRigidbody.h" #include "CBoxCollider.h" #include "physical/physics/shapes/physBoxShape.h" CBoxCollider::CBoxCollider ( Vector3d const& size ) { vExtents = size; vCenterOfMass = Vector3d( 0,0,0 ); //pCollisionShape = Physics::CreateBoxShape( vExtents * 0.5f ); pCollisionShape = new physBoxShape( vExtents * 0.5f ); } CBoxCollider::CBoxCollider ( BoundingBox const& bbox, Vector3d const& pos ) { vExtents = bbox.GetSize(); //vCenterOfMass = bbox.GetCenterPoint() - pos; vCenterOfMass = pos; //pCollisionShape = Physics::CreateBoxShape( vExtents * 0.5f ); //pCollisionShape = Physics::CreateBoxShape( vExtents * 0.5f, bbox.GetCenterPoint() ); pCollisionShape = new physBoxShape( vExtents * 0.5f, bbox.GetCenterPoint() ); } CBoxCollider::~CBoxCollider ( void ) { Physics::FreeShape( pCollisionShape ); } // Setters void CBoxCollider::SetSize ( Vector3d const& size ) { // Set the current extents of the collider vExtents = size; // Get the Havok object and set the size of it. ((physBoxShape*)pCollisionShape)->setHalfExtents( Vector3d( vExtents.x*0.5f, vExtents.y*0.5f, vExtents.z*0.5f ) ); // Change the rigid body's current shape to the new collider object if ( pRigidBody ) pRigidBody->SetShape( pCollisionShape ); } void CBoxCollider::Set ( BoundingBox const& bbox, Vector3d const& pos ) { vExtents = bbox.GetSize(); vCenterOfMass = bbox.GetCenterPoint() - pos; // Get the Havok object and set the size of it. ((physBoxShape*)pCollisionShape)->setHalfExtents( Vector3d( vExtents.x*0.5f, vExtents.y*0.5f, vExtents.z*0.5f ) ); // Change the rigid body's current shape to the new collider object if ( pRigidBody ) pRigidBody->SetShape( pCollisionShape ); } // Getters Vector3d CBoxCollider::GetSize ( void ) { return vExtents; }
30.457627
115
0.72788
21d3802f04245351d855c9ca5900a75a6cde87b5
2,522
cpp
C++
src/EZOI/1018/kaleidoscope.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
1
2021-08-13T14:27:39.000Z
2021-08-13T14:27:39.000Z
src/EZOI/1018/kaleidoscope.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
null
null
null
src/EZOI/1018/kaleidoscope.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
null
null
null
#include <algorithm> #include <cstdio> #include <iostream> typedef long long ll; int n, m; template <typename T> T read(); class Star { private: const static int MAX_N = 200050; public: struct Node { int v; int nxt; ll w; } node[MAX_N << 1]; int head[MAX_N]; int cnt; void create(int u, int v, ll w) { node[++cnt].v = v; node[cnt].nxt = head[u]; node[cnt].w = w; head[u] = cnt; } }; class MST { private: Star* star; const static int MAX_N = 200050; protected: ll dis[MAX_N]; bool vis[MAX_N]; int tot, crt = 1; public: MST(Star* star) { this->star = star; } ll prim() { std::fill(dis, dis + n + 10, 0x3f3f3f3f3f3f3f3f); for (int i = star->head[1]; i; i = star->node[i].nxt) { int v = star->node[i].v; dis[v] = std::min(dis[v], star->node[i].w); } ll ans = 0; while (++tot < n) { ll min = 0x3f3f3f3f3f3f3f3f; vis[crt] = true; for (int i = 1; i <= n; i++) { if (!vis[i] and min > dis[i]) { min = dis[i]; crt = i; } } ans += min; for (int i = star->head[crt]; i; i = star->node[i].nxt) { int v = star->node[i].v; ll w = star->node[i].w; if (dis[v] > w and !vis[v]) { dis[v] = w; } } } return ans; } }; signed main() { freopen("kaleidoscope.in", "r", stdin); freopen("kaleidoscope.out", "w", stdout); int t = read<int>(); while (t--) { n = read<int>(), m = read<int>(); Star* star = new Star(); for (int i = 1; i <= m; i++) { int x = read<int>(), y = read<int>(); ll z = read<ll>(); for (int i = 0; i < n; i++) { star->create((x + i) % n + 1, (y + i) % n + 1, z); star->create((y + i) % n + 1, (x + i) % n + 1, z); } } MST* mst = new MST(star); std::cout << mst->prim() << '\n'; } fclose(stdin); fclose(stdout); return 0; } template <typename T> T read() { T x = 0, 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; }
21.016667
69
0.406027