blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
listlengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a71ab47a58af26bb784e6e9259f2d1ddf57de3b6 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /content/browser/web_contents/web_contents_view_android.cc | 0222bc629b44766fe282fe8df395257522a925a6 | [
"BSD-3-Clause"
]
| permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 11,581 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/web_contents/web_contents_view_android.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/logging.h"
#include "content/browser/android/content_view_core_impl.h"
#include "content/browser/frame_host/interstitial_page_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_android.h"
#include "content/browser/renderer_host/render_view_host_factory.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/common/drop_data.h"
#include "ui/display/screen.h"
#include "ui/gfx/android/device_display_info.h"
#include "ui/gfx/android/java_bitmap.h"
#include "ui/gfx/image/image_skia.h"
using base::android::AttachCurrentThread;
using base::android::ConvertUTF16ToJavaString;
using base::android::JavaRef;
using base::android::ScopedJavaLocalRef;
namespace content {
// static
void WebContentsView::GetDefaultScreenInfo(ScreenInfo* results) {
const display::Display& display =
display::Screen::GetScreen()->GetPrimaryDisplay();
results->rect = display.bounds();
// TODO(husky): Remove any system controls from availableRect.
results->available_rect = display.work_area();
results->device_scale_factor = display.device_scale_factor();
results->orientation_angle = display.RotationAsDegree();
results->orientation_type =
RenderWidgetHostViewBase::GetOrientationTypeForMobile(display);
gfx::DeviceDisplayInfo info;
results->depth = display.color_depth();
results->depth_per_component = display.depth_per_component();
results->is_monochrome = display.is_monochrome();
}
WebContentsView* CreateWebContentsView(
WebContentsImpl* web_contents,
WebContentsViewDelegate* delegate,
RenderViewHostDelegateView** render_view_host_delegate_view) {
WebContentsViewAndroid* rv = new WebContentsViewAndroid(
web_contents, delegate);
*render_view_host_delegate_view = rv;
return rv;
}
WebContentsViewAndroid::WebContentsViewAndroid(
WebContentsImpl* web_contents,
WebContentsViewDelegate* delegate)
: web_contents_(web_contents),
content_view_core_(NULL),
delegate_(delegate) {
}
WebContentsViewAndroid::~WebContentsViewAndroid() {
}
void WebContentsViewAndroid::SetContentViewCore(
ContentViewCoreImpl* content_view_core) {
content_view_core_ = content_view_core;
RenderWidgetHostViewAndroid* rwhv = static_cast<RenderWidgetHostViewAndroid*>(
web_contents_->GetRenderWidgetHostView());
if (rwhv)
rwhv->SetContentViewCore(content_view_core_);
if (web_contents_->ShowingInterstitialPage()) {
rwhv = static_cast<RenderWidgetHostViewAndroid*>(
web_contents_->GetInterstitialPage()
->GetMainFrame()
->GetRenderViewHost()
->GetWidget()
->GetView());
if (rwhv)
rwhv->SetContentViewCore(content_view_core_);
}
}
gfx::NativeView WebContentsViewAndroid::GetNativeView() const {
return content_view_core_ ? content_view_core_->GetViewAndroid() : nullptr;
}
gfx::NativeView WebContentsViewAndroid::GetContentNativeView() const {
RenderWidgetHostView* rwhv = web_contents_->GetRenderWidgetHostView();
if (rwhv)
return rwhv->GetNativeView();
// TODO(sievers): This should return null.
return GetNativeView();
}
gfx::NativeWindow WebContentsViewAndroid::GetTopLevelNativeWindow() const {
return content_view_core_ ? content_view_core_->GetWindowAndroid() : nullptr;
}
void WebContentsViewAndroid::GetScreenInfo(ScreenInfo* result) const {
// ScreenInfo isn't tied to the widget on Android. Always return the default.
WebContentsView::GetDefaultScreenInfo(result);
}
void WebContentsViewAndroid::GetContainerBounds(gfx::Rect* out) const {
*out = content_view_core_ ? gfx::Rect(content_view_core_->GetViewSize())
: gfx::Rect();
}
void WebContentsViewAndroid::SetPageTitle(const base::string16& title) {
if (content_view_core_)
content_view_core_->SetTitle(title);
}
void WebContentsViewAndroid::SizeContents(const gfx::Size& size) {
// TODO(klobag): Do we need to do anything else?
RenderWidgetHostView* rwhv = web_contents_->GetRenderWidgetHostView();
if (rwhv)
rwhv->SetSize(size);
}
void WebContentsViewAndroid::Focus() {
if (web_contents_->ShowingInterstitialPage())
web_contents_->GetInterstitialPage()->Focus();
else
web_contents_->GetRenderWidgetHostView()->Focus();
}
void WebContentsViewAndroid::SetInitialFocus() {
if (web_contents_->FocusLocationBarByDefault())
web_contents_->SetFocusToLocationBar(false);
else
Focus();
}
void WebContentsViewAndroid::StoreFocus() {
NOTIMPLEMENTED();
}
void WebContentsViewAndroid::RestoreFocus() {
NOTIMPLEMENTED();
}
DropData* WebContentsViewAndroid::GetDropData() const {
NOTIMPLEMENTED();
return NULL;
}
gfx::Rect WebContentsViewAndroid::GetViewBounds() const {
if (content_view_core_)
return gfx::Rect(content_view_core_->GetViewSize());
return gfx::Rect();
}
void WebContentsViewAndroid::CreateView(
const gfx::Size& initial_size, gfx::NativeView context) {
}
RenderWidgetHostViewBase* WebContentsViewAndroid::CreateViewForWidget(
RenderWidgetHost* render_widget_host, bool is_guest_view_hack) {
if (render_widget_host->GetView()) {
// During testing, the view will already be set up in most cases to the
// test view, so we don't want to clobber it with a real one. To verify that
// this actually is happening (and somebody isn't accidentally creating the
// view twice), we check for the RVH Factory, which will be set when we're
// making special ones (which go along with the special views).
DCHECK(RenderViewHostFactory::has_factory());
return static_cast<RenderWidgetHostViewBase*>(
render_widget_host->GetView());
}
// Note that while this instructs the render widget host to reference
// |native_view_|, this has no effect without also instructing the
// native view (i.e. ContentView) how to obtain a reference to this widget in
// order to paint it. See ContentView::GetRenderWidgetHostViewAndroid for an
// example of how this is achieved for InterstitialPages.
RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(render_widget_host);
return new RenderWidgetHostViewAndroid(rwhi, content_view_core_);
}
RenderWidgetHostViewBase* WebContentsViewAndroid::CreateViewForPopupWidget(
RenderWidgetHost* render_widget_host) {
RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(render_widget_host);
return new RenderWidgetHostViewAndroid(rwhi, NULL);
}
void WebContentsViewAndroid::RenderViewCreated(RenderViewHost* host) {
}
void WebContentsViewAndroid::RenderViewSwappedIn(RenderViewHost* host) {
}
void WebContentsViewAndroid::SetOverscrollControllerEnabled(bool enabled) {
}
void WebContentsViewAndroid::ShowContextMenu(
RenderFrameHost* render_frame_host, const ContextMenuParams& params) {
if (delegate_)
delegate_->ShowContextMenu(render_frame_host, params);
}
void WebContentsViewAndroid::ShowPopupMenu(
RenderFrameHost* render_frame_host,
const gfx::Rect& bounds,
int item_height,
double item_font_size,
int selected_item,
const std::vector<MenuItem>& items,
bool right_aligned,
bool allow_multiple_selection) {
if (content_view_core_) {
content_view_core_->ShowSelectPopupMenu(
render_frame_host, bounds, items, selected_item,
allow_multiple_selection, right_aligned);
}
}
void WebContentsViewAndroid::HidePopupMenu() {
if (content_view_core_)
content_view_core_->HideSelectPopupMenu();
}
void WebContentsViewAndroid::StartDragging(
const DropData& drop_data,
blink::WebDragOperationsMask allowed_ops,
const gfx::ImageSkia& image,
const gfx::Vector2d& image_offset,
const DragEventSourceInfo& event_info) {
if (drop_data.text.is_null()) {
// Need to clear drag and drop state in blink.
OnDragEnded();
return;
}
gfx::NativeView native_view = GetNativeView();
if (!native_view) {
// Need to clear drag and drop state in blink.
OnDragEnded();
return;
}
const SkBitmap* bitmap = image.bitmap();
SkBitmap dummy_bitmap;
if (image.size().IsEmpty()) {
// An empty drag image is possible if the Javascript sets an empty drag
// image on purpose.
// Create a dummy 1x1 pixel image to avoid crashes when converting to java
// bitmap.
dummy_bitmap.allocN32Pixels(1, 1);
dummy_bitmap.eraseColor(0);
bitmap = &dummy_bitmap;
}
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jstring> jtext =
ConvertUTF16ToJavaString(env, drop_data.text.string());
if (!native_view->StartDragAndDrop(jtext, gfx::ConvertToJavaBitmap(bitmap))) {
// Need to clear drag and drop state in blink.
OnDragEnded();
return;
}
if (content_view_core_)
content_view_core_->HidePopupsAndPreserveSelection();
}
void WebContentsViewAndroid::UpdateDragCursor(blink::WebDragOperation op) {
// Intentional no-op because Android does not have cursor.
}
void WebContentsViewAndroid::OnDragEntered(
const std::vector<DropData::Metadata>& metadata,
const gfx::Point& location,
const gfx::Point& screen_location) {
blink::WebDragOperationsMask allowed_ops =
static_cast<blink::WebDragOperationsMask>(blink::WebDragOperationCopy |
blink::WebDragOperationMove);
web_contents_->GetRenderViewHost()->DragTargetDragEnterWithMetaData(
metadata, location, screen_location, allowed_ops, 0);
}
void WebContentsViewAndroid::OnDragUpdated(const gfx::Point& location,
const gfx::Point& screen_location) {
blink::WebDragOperationsMask allowed_ops =
static_cast<blink::WebDragOperationsMask>(blink::WebDragOperationCopy |
blink::WebDragOperationMove);
web_contents_->GetRenderViewHost()->DragTargetDragOver(
location, screen_location, allowed_ops, 0);
}
void WebContentsViewAndroid::OnDragExited() {
web_contents_->GetRenderViewHost()->DragTargetDragLeave();
}
void WebContentsViewAndroid::OnPerformDrop(DropData* drop_data,
const gfx::Point& location,
const gfx::Point& screen_location) {
web_contents_->GetRenderViewHost()->FilterDropData(drop_data);
web_contents_->GetRenderViewHost()->DragTargetDrop(*drop_data, location,
screen_location, 0);
}
void WebContentsViewAndroid::OnDragEnded() {
web_contents_->GetRenderViewHost()->DragSourceSystemDragEnded();
}
void WebContentsViewAndroid::GotFocus() {
// This is only used in the views FocusManager stuff but it bleeds through
// all subclasses. http://crbug.com/21875
}
// This is called when we the renderer asks us to take focus back (i.e., it has
// iterated past the last focusable element on the page).
void WebContentsViewAndroid::TakeFocus(bool reverse) {
if (web_contents_->GetDelegate() &&
web_contents_->GetDelegate()->TakeFocus(web_contents_, reverse))
return;
web_contents_->GetRenderWidgetHostView()->Focus();
}
} // namespace content
| [
"[email protected]"
]
| |
e56cbdbc2d025096dcbb941fb1c4d07b197525a3 | 3d92d4c1d204424a114a2db861add512e90a75df | /EventCLoop/Event.hpp | 97e897d31a30a8197532e6a007b335f6674c37be | []
| no_license | sea5727/hiredis-tutorial | 4aba10643d3befa10ee6a78df9f2b5970dbc8fea | 3f4b8b99183d2cbab036d0f7185b6a459326d621 | refs/heads/main | 2023-02-19T04:41:43.960592 | 2021-01-25T12:08:07 | 2021-01-25T12:08:07 | 331,785,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | hpp | #pragma once
#include <functional>
#include <sys/epoll.h>
namespace EventCLoop
{
class Event{
public:
int fd;
std::function<void(const struct epoll_event & ev)> pop;
Event()
: fd{-1}
, pop{nullptr} {}
bool
isCleared(){
if(fd == -1)
return true;
return false;
}
void
clear(){
fd = -1;
pop = nullptr;
}
};
} | [
"[email protected]"
]
| |
da6d28eecee10af714afc85796383fae67b5e7a3 | c82d4afeabb5247daf14045effea2dce06b82d54 | /C++/2_4_1/2_4_1/2_4_1.cpp | 9d6388c6df35759b02c46ca988122956dd6a2976 | []
| no_license | lubolib/University_Code | d9bcfefde5c7e5fd5bf50676a9f957f20e049fd3 | 092752985de849385be39a6740befbde2deab4aa | refs/heads/master | 2022-03-22T23:13:27.702527 | 2019-09-26T23:47:06 | 2019-09-26T23:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 857 | cpp | // 2_4_1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
int main()
{
const int i = 1024;
const int &r = i;
std::cout << r;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门提示:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
| [
"[email protected]"
]
| |
5582a2be46acab851aaf8a85b5a08bd1fab615a8 | 94e893fd29d0813bc74dd5afc05834681d46fe52 | /TCP聊天客户端/StdAfx.cpp | 41d0a92989fd68c4a2fc6baf235e1748f790f298 | []
| no_license | BangBangTangDe/TCPIP | 77805d1317652f8d4f16224552170f406edc440c | 897163330cbdc5b73fc4bc069d9826be2e7ebb7f | refs/heads/master | 2020-06-09T15:10:20.999408 | 2019-06-24T07:35:23 | 2019-06-24T07:35:23 | 193,456,876 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 204 | cpp | // stdafx.cpp : source file that includes just the standard includes
// CSocketcli.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"[[email protected]]"
]
| |
8daaa3a270f88dcf7f6c0dba8bc6cd0d9414f3da | ece90f5a6a123ab6c26ab8fa0fa7a81efbd651d6 | /moui/core/android/application_android.cc | e70303b2d81605daf4bc38ef32544c240e04eec9 | [
"Apache-2.0"
]
| permissive | hinike/moui | ab79e28818ec7f552eeea86e07786421a5d27fcd | 4d558df1cb16ab1cd4a5ee8282abe2a3930b2a1c | refs/heads/master | 2020-03-19T11:24:58.500463 | 2018-06-07T06:30:13 | 2018-06-07T06:30:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,545 | cc | // Copyright (c) 2014 Ollix. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ---
// Author: [email protected] (Olli Wang)
#include "moui/core/application.h"
#include "jni.h" // NOLINT
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include "aasset.h"
namespace {
JavaVM* java_vm = nullptr;
jobject main_activity = nullptr;
} // namespace
namespace moui {
void Application::InitJNI(JNIEnv* env, jobject activity,
jobject asset_manager) {
if (main_activity != nullptr) {
env->DeleteGlobalRef(main_activity);
}
main_activity = reinterpret_cast<jobject>(env->NewGlobalRef(activity));
env->GetJavaVM(&java_vm);
// Initializes the aasset library.
aasset_init(AAssetManager_fromJava(env, asset_manager));
}
JNIEnv* Application::GetJNIEnv() {
JNIEnv* env;
java_vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6);
return env;
}
jobject Application::GetMainActivity() {
return main_activity;
}
} // namespace moui
| [
"[email protected]"
]
| |
1d26914ad2fcf58fe66431ce6148a82b7b1c7b6e | bcd6309fd23189bd17522575f2ed4e1fb8dbc0e5 | /Win32/应用程序/PEinfo/PEViewer/PEViewer/PEImportClass.cpp | f163b3d9fa7521d52bd1b897add7ea41be1993cc | []
| no_license | qqzxingchen/CodeDB | f6ed63ee165fe9f67b8b98a77e1e949881456449 | 7bab59fa69a1c132d79e45d4950dc8b575769a5b | refs/heads/master | 2021-01-10T04:47:59.199551 | 2015-12-10T01:57:34 | 2015-12-10T01:57:34 | 47,730,470 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,373 | cpp | #include "PEImportClass.h"
#include "PEBaseClass.h"
#include "global.h"
PEImportClass::PEImportClass(PEBase * peBase)
{
this->peBase = peBase;
}
bool PEImportClass::writeToTempFile()
{
CreateDirectory( TEXT("temp"),NULL );
HANDLE peFile = CreateFile(peBase->getPEFilePath(),GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if ( peFile == INVALID_HANDLE_VALUE ){
int a = GetLastError();
wsprintf(ErrorString,TEXT("打开PE文件失败"));
return false;
}
HANDLE tempFile;
tempFile = CreateFile( this->GetTempFileName(),
GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL );
if ( tempFile == INVALID_HANDLE_VALUE ){
int a = GetLastError();
wsprintf(ErrorString,TEXT("创建缓存文件失败"));
return false;
}
writeStringToFile(tempFile,"var PEImportData = [");
writeDataToFile(peFile,tempFile);
writeStringToFile(tempFile,"];\n");
CloseHandle(tempFile);
CloseHandle(peFile);
return true;
}
void PEImportClass::writeDataToFile( HANDLE peFile, HANDLE hFile )
{
if(peBase->optionHeader->getDataDirectory(1).Size==0)
return ;
bool funcFirstSign;
bool totalFirstSign;
DWORD byteNum;
DWORD rva,foa;
char temp[1024];
char retu[1024];
IMAGE_IMPORT_DESCRIPTOR import;
IMAGE_THUNK_DATA thunk;
IMAGE_IMPORT_BY_NAME importByName;
DWORD importAddr=(DWORD)peBase->RvaToFoa((ULONGLONG)(peBase->optionHeader->getDataDirectory(1).VirtualAddress));
totalFirstSign = true;
for ( int i = 0 ; ; i ++ )
{
memset( &import,0,sizeof(IMAGE_IMPORT_DESCRIPTOR) );
SetFilePointer(peFile,importAddr+i*sizeof(IMAGE_IMPORT_DESCRIPTOR),NULL,FILE_BEGIN);
ReadFile(peFile,&import,sizeof(IMAGE_IMPORT_DESCRIPTOR),&byteNum,NULL);
if((int)import.Name==0)
break;
SetFilePointer(peFile,peBase->RvaToFoa((int)import.Name),NULL,FILE_BEGIN);
ReadFile(peFile,temp,256,&byteNum,NULL);
if ( !totalFirstSign )
writeSeparatorToFile(hFile);
else
totalFirstSign = false;
writeStringToFile(hFile,"{name:'");
writeStringToFile(hFile,temp);
writeStringToFile(hFile,"',value:[");
funcFirstSign = true;
rva = ( import.OriginalFirstThunk != 0 ) ? import.OriginalFirstThunk : import.FirstThunk;
foa = peBase->RvaToFoa(rva);
for( int j = 0 ; ; j ++ )
{
SetFilePointer(peFile,foa+j*sizeof(IMAGE_THUNK_DATA),NULL,FILE_BEGIN);
ReadFile(peFile,&thunk,sizeof(IMAGE_THUNK_DATA),&byteNum,NULL);
if(thunk.u1.AddressOfData==0)
break;
if ( !funcFirstSign )
writeSeparatorToFile(hFile);
else
funcFirstSign = false;
if(((DWORD)thunk.u1.AddressOfData & 0x80000000)!=0 )
{
st.setBaseStr( StringTemplate::importTemplate );
st.exchange( "hint",( wsprintfA(temp,"%u",thunk.u1.AddressOfData & 0xFFFF),temp ) );
st.exchange( "name","无函数名,按序号导出");
st.getString( retu );
writeStringToFile( hFile,retu );
}else{
SetFilePointer(peFile,peBase->RvaToFoa(thunk.u1.AddressOfData),NULL,FILE_BEGIN);
ReadFile(peFile,&importByName,sizeof(WORD),&byteNum,NULL);
st.setBaseStr( StringTemplate::importTemplate );
ReadFile(peFile,temp,256,&byteNum,NULL);
st.exchange( "name",temp );
st.exchange( "hint",( wsprintfA(temp,"%u",importByName.Hint),temp ) );
st.getString( retu );
writeStringToFile( hFile,retu );
}
}
writeStringToFile(hFile,"]}");
}
}
| [
"[email protected]"
]
| |
2d844fe0f213e4d32e0272ed97591570ee604647 | 1880ae99db197e976c87ba26eb23a20248e8ee51 | /iotvideo/include/tencentcloud/iotvideo/v20201215/model/DescribeDevicesResponse.h | 5afa05ee198781a30e57c6aa471ecfa8826c7226 | [
"Apache-2.0"
]
| permissive | caogenwang/tencentcloud-sdk-cpp | 84869793b5eb9811bb1eb46ed03d4dfa7ce6d94d | 6e18ee6622697a1c60a20a509415b0ddb8bdeb75 | refs/heads/master | 2023-08-23T12:37:30.305972 | 2021-11-08T01:18:30 | 2021-11-08T01:18:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,936 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_IOTVIDEO_V20201215_MODEL_DESCRIBEDEVICESRESPONSE_H_
#define TENCENTCLOUD_IOTVIDEO_V20201215_MODEL_DESCRIBEDEVICESRESPONSE_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/iotvideo/v20201215/model/DeviceInfo.h>
namespace TencentCloud
{
namespace Iotvideo
{
namespace V20201215
{
namespace Model
{
/**
* DescribeDevices返回参数结构体
*/
class DescribeDevicesResponse : public AbstractModel
{
public:
DescribeDevicesResponse();
~DescribeDevicesResponse() = default;
CoreInternalOutcome Deserialize(const std::string &payload);
std::string ToJsonString() const;
/**
* 获取设备总数
* @return TotalCount 设备总数
*/
uint64_t GetTotalCount() const;
/**
* 判断参数 TotalCount 是否已赋值
* @return TotalCount 是否已赋值
*/
bool TotalCountHasBeenSet() const;
/**
* 获取设备详细信息列表
* @return Devices 设备详细信息列表
*/
std::vector<DeviceInfo> GetDevices() const;
/**
* 判断参数 Devices 是否已赋值
* @return Devices 是否已赋值
*/
bool DevicesHasBeenSet() const;
private:
/**
* 设备总数
*/
uint64_t m_totalCount;
bool m_totalCountHasBeenSet;
/**
* 设备详细信息列表
*/
std::vector<DeviceInfo> m_devices;
bool m_devicesHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_IOTVIDEO_V20201215_MODEL_DESCRIBEDEVICESRESPONSE_H_
| [
"[email protected]"
]
| |
2a30ed2e59720b5b8d9861d3bf7e809b6b639163 | f40fc57b3aaa9c3a720cbae1ebc5360d64f87b2b | /C++/Assignment1/Program5/Program5/Distance.cpp | b77fae8641e00d1325f7e6e919d62f98728b3137 | []
| no_license | SuryaPavan1/ncrwork | 303a0f90b360dbfc616d8fda5b2b9f828b0be1e8 | 63bbfd5b7dd5976f6ed07a60d94a5c37cc68777a | refs/heads/master | 2020-04-21T02:21:42.754546 | 2019-04-01T15:49:40 | 2019-04-01T15:49:40 | 168,962,583 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,498 | cpp | #include<iostream>
using namespace std;
class Distance2;
class Distance1
{
int meters;
int centimeters;
public:
Distance1() {
meters = centimeters = 0;
}
Distance1(int a,int b) {
meters = a;
centimeters = b;
}
friend Distance1 Add_1(Distance1 d1, Distance2 d2);
friend Distance2 Add_2(Distance1 d1, Distance2 d2);
void display()
{
cout <<endl<<meters << "meters " << centimeters << "centimeters";
}
};
class Distance2
{
int feet;
int inches;
public:
Distance2() {
feet = inches = 0;
}
Distance2(int a, int b) {
feet = a;
inches = b;
}
void display()
{
cout << feet << " feet " << inches << " inches ";
}
friend Distance1 Add_1(Distance1 d1, Distance2 d2);
friend Distance2 Add_2(Distance1 d1, Distance2 d2);
};
Distance1 Add_1(Distance1 d1, Distance2 d2)
{
Distance1 d3;
int temp;
temp = d1.meters * 100 + d1.centimeters + (d2.feet * 12 + d2.inches)*2.54;
d3.meters = temp / 100;
d3.centimeters= temp % 100;
return d3;
}
Distance2 Add_2(Distance1 d1, Distance2 d2)
{
Distance2 d3;
int temp;
temp = (d1.meters * 100 + d1.centimeters + (d2.feet * 12 + d2.inches)*2.54)/2.54;
d3.feet = temp /12;
d3.inches = temp %12;
return d3;
}
int main()
{
int a, b,c,d;
cout<<"enter the distance in meters and cm :";
cin>> a>> b;
printf("enter the distance in feet and inches :");
cin>>c>>d;
Distance1 d1(a,b), d2;
Distance2 d3(c,d), d4;
d2 = Add_1(d1, d3);
d4 = Add_2(d1, d3);
d2.display();
d4.display();
getchar();
getchar();
return 0;
} | [
"[email protected]"
]
| |
172b6bea2a23a737eb1f8d901cd5a492900e7845 | 21931fd388f368b4f59ad2d240ebd1300390bdab | /coding/codechef/SIMPSTAT.cpp | f98e0a5e11a6b0275d2ecc04a435c679ff285cd2 | []
| no_license | vishalgupta84/Programmes | 8c72486777eecf47c41b30b8bd1df116f8fa7fae | ef065e478d89b7fb09f653b41feab3f356963bd5 | refs/heads/master | 2021-01-21T03:13:32.742459 | 2019-07-28T15:42:57 | 2019-07-28T15:42:57 | 65,014,225 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 525 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
int main(int argc, char const *argv[]){
int t,n,k;
double ans;
cin >> t;
std::vector<int> num;
while(t--){
cin >> n >> k;
num.resize(n);
for (int i = 0; i < n; ++i){
/* code */
cin >> num[i];
}
sort(num.begin(),num.end());
ans=0;
for (int i = k; i <= n-1-k; ++i){
/* code */
ans+=num[i];
}
ans=(double)(ans/(n-2*k));
cout << fixed;
cout << setprecision(6) << ans << endl;
}
return 0;
} | [
"[email protected]"
]
| |
f151ec8e10591296918016fadd1cee2c156f8d05 | 6eb5d2987337fd2f184f471ec19234c0707b877f | /ASSIGNMENT/ASSIGNMENT 3/Q5Charges.cpp | e3c8413785212919b32f7ff593942c72b613dc0e | []
| no_license | piyushkeshari23/OOPS | ccca9a3295861b592f690189943c4273ebaa47d3 | 0235f77c22d2ab69e63841e01b8a485500d716b9 | refs/heads/master | 2023-01-01T12:46:48.190487 | 2020-10-22T09:30:57 | 2020-10-22T09:30:57 | 282,585,979 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 969 | cpp | #include <iostream>
using namespace std;
float calculateCharges(float customer_time);
int main()
{
int number;
cout<<"enter the number of customers";
cin>>number;
float customer_fees[number];
float customer_times[number];
int i;
float a,b;
for(i = 0; i < number; i++)
{
cout << "Enter the time of parking of " << i+1 << " customer: ";
cin >> customer_times[i];
a= a + customer_times[i];
customer_fees[i] = calculateCharges(customer_times[i]);
}
for(i = 0; i < number; i++)
{
cout << "Customer's " << i+1 << " fee for " << customer_times[i] << " = " << customer_fees[i] << endl;
b= b + customer_fees[i];
}
cout<<"Total Hours: "<<a<<endl;
cout<<"Total charges: "<<b<<endl;
return 0;
}
float calculateCharges(float customer_time)
{
float amount = 2 + (0.5 * ((int)customer_time - 3));
if(amount > 10)
return 10;
else return amount;
}
| [
"[email protected]"
]
| |
a9bd36a63aa34ada2cb4aee359b7060a63e11478 | 5338cd4e316f9ba4b7993c3b4db1b514a4ac6d45 | /csa/palp.cpp | fb71b841afe7f6e82066c31da3a08b405ace0d9d | []
| no_license | exopeng/Competitive-Programming | 5371ed2ee7b585b36cf232b5557ed30c50ce67de | 5d28c21d3e5df5fe50a86ec6251dbc2b7018da61 | refs/heads/main | 2023-07-08T13:20:23.946747 | 2021-08-15T17:43:28 | 2021-08-15T17:43:28 | 396,431,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,732 | cpp | #include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
template <class T> using Tree = tree<T, null_type, less<T>,
rb_tree_tag, tree_order_statistics_node_update>;
#define mp make_pair
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define f first
#define s second
#define pii pair<int,int>
#define pdd pair<double,double>
#define is insert
const long long INF = 1e9;
const long long MOD = 1e9+7;
const int MAXN = 1e6+10;
//store test cases here
/*
*/
int t;
long long hsh[MAXN];
long long pw[MAXN]; // Stores the powers of P modulo M
const long long P = 9973; // Change M and P if you want to
const long long M = 1e9 + 9;
void calc_hashes(string s) {
hsh[0] = 1;
pw[0]=1;
for(int i=1;i<s.size();i++){
pw[i]=(pw[i-1]*P) % M;
}
for (int i = 0; i < s.size(); i++)
hsh[i + 1] = ((hsh[i] * P) % M + s[i]) % M;
}
long long get_hash(int a, int b) { // Endpoints of the substring
long long ab=(hsh[b + 1] - (hsh[a] * pw[b - a + 1]) % M + M) % M;
return ab;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin>>t;
for(int i=0;i<t;i++){
string s;
int ans=0;
cin>>s;
calc_hashes(s);
int start=0;
for(int j=0;j<s.size()/2;j++){
while(j<s.size()/2&&get_hash(start,j)!=get_hash(s.size()-1-j,s.size()-start-1)){
//cout<<s.substr(start,j-start+1)<<" "<<s.substr(s.size()-1-j,j-start+1)<<"\n";
j++;
}
if(j==s.size()/2){
ans++;
}else{
ans+=2;
}
start=j+1;
if(j==s.size()/2-1&&s.size()%2==1){
ans++;
}
}
cout<<max(1,ans)<<"\n";
}
return 0;
}
/* REMINDERS
* STORE INFO IN VECTORS, NOT STRINGS!!!!!!!!!
* CHECK ARRAY BOUNDS, HOW BIG ARRAY HAS TO BE
* PLANNING!!!!!!!! Concrete plan before code
* IF CAN'T FIGURE ANYTHING OUT, MAKE TEN TEST CASES TO EVALUATE ALL TYPES OF SCENARIOS, THEN CONSTRUCT SOLUTION TO FIT IT
* IF CAN'T FIGURE ANYTHING OUT, MAKE TEN TEST CASES TO EVALUATE ALL TYPES OF SCENARIOS, THEN CONSTRUCT SOLUTION TO FIT IT
* IF CAN'T FIGURE ANYTHING OUT, MAKE TEN TEST CASES TO EVALUATE ALL TYPES OF SCENARIOS, THEN CONSTRUCT SOLUTION TO FIT IT
* NAIVE SOL FIRST TO CHECK AGAINST OPTIMIZED SOL
* MOD OUT EVERY STEP
* DON'T MAKE ASSUMPTIONS
* DON'T OVERCOMPLICATE
* CHECK INT VS LONG, IF YOU NEED TO STORE LARGE NUMBERS
* CHECK CONSTRAINTS, C <= N <= F...
* CHECK SPECIAL CASES, N = 1...
* TO TEST TLE/MLE, PLUG IN MAX VALS ALLOWED AND SEE WHAT HAPPENS
* ALSO CALCULATE BIG-O, OVERALL TIME COMPLEXITY
* IF ALL ELSE FAILS, DO CASEWORK
* compile with "g++ -std=c++11 filename.cpp" if using auto keyword
*/
| [
"[email protected]"
]
| |
9fe2b2543dea1cc8fcfe09842c6e8fbf9010b823 | 3557c04368516127ea9807e59b94061bdb11e551 | /cppcomponents_rt/external/cds-1.4.0/cds/intrusive/split_list_base.h | f64f578a9063a8d7075af753ee6137586ea273b2 | [
"BSD-2-Clause",
"BSL-1.0"
]
| permissive | jbandela/cppcomponents_rt | 0d3c3360a94819a81f06ab21fbcfc027c3bcaa25 | eebbe27852f3882b61b47fbbdee1ef6836f4c905 | refs/heads/master | 2020-05-19T10:48:28.315193 | 2013-08-30T17:43:25 | 2013-08-30T17:43:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,684 | h | /*
This file is a part of libcds - Concurrent Data Structures library
See http://libcds.sourceforge.net/
(C) Copyright Maxim Khiszinsky (libcds.sf.com) 2006-2013
Distributed under the BSD license (see accompanying file license.txt)
Version 1.4.0
*/
#ifndef __CDS_INTRUSIVE_SPLIT_LIST_BASE_H
#define __CDS_INTRUSIVE_SPLIT_LIST_BASE_H
#include <cds/intrusive/base.h>
#include <cds/cxx11_atomic.h>
#include <cds/details/allocator.h>
#include <cds/int_algo.h>
#include <cds/bitop.h>
#include <cds/details/functor_wrapper.h>
namespace cds { namespace intrusive {
/// Split-ordered list related definitions
/** @ingroup cds_intrusive_helper
*/
namespace split_list {
/// Split-ordered list node
/**
Template parameter:
- OrderedListNode - node type for underlying ordered list
*/
template <typename OrderedListNode>
struct node: public OrderedListNode
{
//@cond
typedef OrderedListNode base_class ;
//@endcond
size_t m_nHash ; ///< Hash value for node
/// Default constructor
node()
: m_nHash(0)
{
assert( is_dummy() ) ;
}
/// Initializes dummy node with \p nHash value
node( size_t nHash )
: m_nHash( nHash )
{
assert( is_dummy() ) ;
}
/// Checks if the node is dummy node
bool is_dummy() const
{
return (m_nHash & 1) == 0 ;
}
};
/// Type traits for SplitListSet class
struct type_traits {
/// Hash function
/**
Hash function converts the key fields of struct \p T stored in the split list
into value of type \p size_t called hash value that is an index of hash table.
This is mandatory type and has no predefined one.
*/
typedef opt::none hash ;
/// Item counter
/**
The item counting is an important part of SplitListSet algorithm:
the <tt>empty()</tt> member function depends on correct item counting.
Therefore, atomicity::empty_item_counter is not allowed as a type of the option.
Default is atomicity::item_counter.
*/
typedef atomicity::item_counter item_counter;
/// Bucket table allocator
/**
Allocator for bucket table. Default is \ref CDS_DEFAULT_ALLOCATOR
*/
typedef CDS_DEFAULT_ALLOCATOR allocator ;
/// C++ memory model for atomic operations
/**
Can be opt::v::relaxed_ordering (relaxed memory model, the default) or opt::v::sequential_consistent (sequentially consisnent memory model).
*/
typedef opt::v::relaxed_ordering memory_model;
/// What type of bucket table is used
/**
\p true - use split_list::expandable_bucket_table that can be expanded
if the load factor of the set is exhausted
\p false - use split_list::static_bucket_table that cannot be expanded
Default is \p true.
*/
static const bool dynamic_bucket_table = true ;
/// back-off strategy used
/**
If the option is not specified, the cds::backoff::Default is used.
*/
typedef cds::backoff::Default back_off ;
};
/// [value-option] Split-list dynamic bucket table option
/**
The option is used to select bucket table implementation.
Possible values of \p Value are:
- \p true - select \ref expandable_bucket_table implementation
- \p false - select \ref static_bucket_table implementation
*/
template <bool Value>
struct dynamic_bucket_table
{
//@cond
template <typename Base> struct pack: public Base
{
enum { dynamic_bucket_table = Value } ;
};
//@endcond
};
/// Metafunction converting option list to traits struct
/**
This is a wrapper for <tt> cds::opt::make_options< type_traits, Options...> </tt>
Available \p Options:
- opt::hash - mandatory option, specifies hash functor.
- opt::item_counter - optional, specifies item counting policy. See type_traits::item_counter
for default type.
- opt::memory_model - C++ memory model for atomic operations.
Can be opt::v::relaxed_ordering (relaxed memory model, the default) or opt::v::sequential_consistent (sequentially consisnent memory model).
- opt::allocator - optional, bucket table allocator. Default is \ref CDS_DEFAULT_ALLOCATOR.
- split_list::dynamic_bucket_table - use dynamic or static bucket table implementation.
Dynamic bucket table expands its size up to maximum bucket count when necessary
- opt::back_off - back-off strategy used for spinning. If the option is not specified, the cds::backoff::Default is used.
See \ref MichaelHashSet, \ref type_traits.
*/
template <CDS_DECL_OPTIONS6>
struct make_traits {
typedef typename cds::opt::make_options< type_traits, CDS_OPTIONS6>::type type ; ///< Result of metafunction
};
/// Static bucket table
/**
Non-resizeable bucket table for SplitListSet class.
The capacity of table (max bucket count) is defined in the constructor call.
Template parameter:
- \p GC - garbage collector used
- \p Node - node type, must be a type based on\ref node template
- \p Options... - options
\p Options are:
- \p opt::allocator - allocator used to allocate bucket table. Default is \ref CDS_DEFAULT_ALLOCATOR
- \p opt::memory_model - memory model used. Possible types are opt::v::sequential_consistent, opt::v::relaxed_ordering
*/
template <typename GC, typename Node, CDS_DECL_OPTIONS2>
class static_bucket_table
{
//@cond
struct default_options
{
typedef CDS_DEFAULT_ALLOCATOR allocator ;
typedef opt::v::relaxed_ordering memory_model ;
};
typedef typename opt::make_options< default_options, CDS_OPTIONS2 >::type options ;
//@endcond
public:
typedef GC gc ; ///< Garbage collector
typedef Node node_type ; ///< Bucket node type
typedef CDS_ATOMIC::atomic<node_type *> table_entry ; ///< Table entry type
/// Bucket table allocator
typedef cds::details::Allocator< table_entry, typename options::allocator > bucket_table_allocator ;
/// Memory model for atomic operations
typedef typename options::memory_model memory_model ;
protected:
const size_t m_nLoadFactor ; ///< load factor (average count of items per bucket)
const size_t m_nCapacity ; ///< Bucket table capacity
table_entry * m_Table ; ///< Bucket table
protected:
//@cond
void allocate_table()
{
m_Table = bucket_table_allocator().NewArray( m_nCapacity, null_ptr<node_type *>() ) ;
}
void destroy_table()
{
bucket_table_allocator().Delete( m_Table, m_nCapacity ) ;
}
//@endcond
public:
/// Constructs bucket table for 512K buckets. Load factor is 1.
static_bucket_table()
: m_nLoadFactor(1)
, m_nCapacity( 512 * 1024 )
{
allocate_table() ;
}
/// Constructs
static_bucket_table(
size_t nItemCount, ///< Max expected item count in split-ordered list
size_t nLoadFactor ///< Load factor
)
: m_nLoadFactor( nLoadFactor > 0 ? nLoadFactor : (size_t) 1 ),
m_nCapacity( cds::beans::ceil2( nItemCount / m_nLoadFactor ) )
{
// m_nCapacity must be power of 2
assert( cds::beans::is_power2( m_nCapacity ) ) ;
allocate_table() ;
}
/// Destroy bucket table
~static_bucket_table()
{
destroy_table() ;
}
/// Returns head node of bucket \p nBucket
node_type * bucket( size_t nBucket ) const
{
assert( nBucket < capacity() ) ;
return m_Table[ nBucket ].load(memory_model::memory_order_acquire) ;
}
/// Set head node \p pNode of bucket \p nBucket
void bucket( size_t nBucket, node_type * pNode )
{
assert( nBucket < capacity() ) ;
assert( bucket(nBucket) == null_ptr<node_type *>() ) ;
m_Table[ nBucket ].store( pNode, memory_model::memory_order_release ) ;
}
/// Returns the capacity of the bucket table
size_t capacity() const
{
return m_nCapacity ;
}
/// Returns the load factor, i.e. average count of items per bucket
size_t load_factor() const
{
return m_nLoadFactor ;
}
};
/// Expandable bucket table
/**
This bucket table can dynamically grow its capacity when necessary
up to maximum bucket count.
Template parameter:
- \p GC - garbage collector used
- \p Node - node type, must be an instantiation of \ref node template
- \p Options... - options
\p Options are:
- \p opt::allocator - allocator used to allocate bucket table. Default is \ref CDS_DEFAULT_ALLOCATOR
- \p opt::memory_model - memory model used. Possible types are opt::v::sequential_consistent, opt::v::relaxed_ordering
*/
template <typename GC, typename Node, CDS_DECL_OPTIONS2>
class expandable_bucket_table
{
//@cond
struct default_options
{
typedef CDS_DEFAULT_ALLOCATOR allocator ;
typedef opt::v::relaxed_ordering memory_model;
};
typedef typename opt::make_options< default_options, CDS_OPTIONS2 >::type options ;
//@endcond
public:
typedef GC gc ; ///< Garbage collector
typedef Node node_type ; ///< Bucket node type
typedef CDS_ATOMIC::atomic<node_type *> table_entry ; ///< Table entry type
/// Memory model for atomic operations
typedef typename options::memory_model memory_model ;
protected:
typedef CDS_ATOMIC::atomic<table_entry *> segment_type ; ///< Bucket table segment type
public:
/// Bucket table allocator
typedef cds::details::Allocator< segment_type, typename options::allocator > bucket_table_allocator ;
/// Bucket table segment allocator
typedef cds::details::Allocator< table_entry, typename options::allocator > segment_allocator ;
protected:
/// Bucket table metrics
struct metrics {
size_t nSegmentCount ; ///< max count of segments in bucket table
size_t nSegmentSize ; ///< the segment's capacity. The capacity must be power of two.
size_t nSegmentSizeLog2 ; ///< log2( m_nSegmentSize )
size_t nLoadFactor ; ///< load factor
size_t nCapacity ; ///< max capacity of bucket table
metrics()
: nSegmentCount(1024)
, nSegmentSize(512)
, nSegmentSizeLog2( cds::beans::log2( nSegmentSize ) )
, nLoadFactor(1)
, nCapacity( nSegmentCount * nSegmentSize )
{}
};
const metrics m_metrics ; ///< Dynamic bucket table metrics
protected:
//const size_t m_nLoadFactor; ///< load factor (average count of items per bucket)
//const size_t m_nCapacity ; ///< Bucket table capacity
segment_type * m_Segments ; ///< bucket table - array of segments
protected:
//@cond
metrics calc_metrics( size_t nItemCount, size_t nLoadFactor )
{
metrics m ;
// Calculate m_nSegmentSize and m_nSegmentCount by nItemCount
m.nLoadFactor = nLoadFactor > 0 ? nLoadFactor : 1 ;
size_t nBucketCount = (size_t)( ((float) nItemCount) / m.nLoadFactor ) ;
if ( nBucketCount <= 2 ) {
m.nSegmentCount = 1 ;
m.nSegmentSize = 2 ;
}
else if ( nBucketCount <= 1024 ) {
m.nSegmentCount = 1 ;
m.nSegmentSize = ((size_t) 1) << beans::log2ceil( nBucketCount ) ;
}
else {
nBucketCount = beans::log2ceil( nBucketCount ) ;
m.nSegmentCount =
m.nSegmentSize = ((size_t) 1) << ( nBucketCount / 2 ) ;
if ( nBucketCount & 1 )
m.nSegmentSize *= 2 ;
if ( m.nSegmentCount * m.nSegmentSize * m.nLoadFactor < nItemCount )
m.nSegmentSize *= 2 ;
}
m.nCapacity = m.nSegmentCount * m.nSegmentSize ;
m.nSegmentSizeLog2 = cds::beans::log2( m.nSegmentSize ) ;
assert( m.nSegmentSizeLog2 != 0 ) ; //
return m ;
}
segment_type * allocate_table()
{
return bucket_table_allocator().NewArray( m_metrics.nSegmentCount, null_ptr<table_entry *>() ) ;
}
void destroy_table( segment_type * pTable )
{
bucket_table_allocator().Delete( pTable, m_metrics.nSegmentCount ) ;
}
table_entry * allocate_segment()
{
return segment_allocator().NewArray( m_metrics.nSegmentSize, null_ptr<node_type *>() ) ;
}
void destroy_segment( table_entry * pSegment )
{
segment_allocator().Delete( pSegment, m_metrics.nSegmentSize ) ;
}
void init_segments()
{
// m_nSegmentSize must be 2**N
assert( cds::beans::is_power2( m_metrics.nSegmentSize )) ;
assert( ( ((size_t) 1) << m_metrics.nSegmentSizeLog2) == m_metrics.nSegmentSize ) ;
// m_nSegmentCount must be 2**K
assert( cds::beans::is_power2( m_metrics.nSegmentCount )) ;
m_Segments = allocate_table() ;
}
//@endcond
public:
/// Constructs bucket table for 512K buckets. Load factor is 1.
expandable_bucket_table()
: m_metrics( calc_metrics( 512 * 1024, 1 ))
{
init_segments() ;
}
/// Constructs
expandable_bucket_table(
size_t nItemCount, ///< Max expected item count in split-ordered list
size_t nLoadFactor ///< Load factor
)
: m_metrics( calc_metrics( nItemCount, nLoadFactor ))
{
init_segments() ;
}
/// Destroy bucket table
~expandable_bucket_table()
{
segment_type * pSegments = m_Segments ;
for ( size_t i = 0; i < m_metrics.nSegmentCount; ++i ) {
table_entry * pEntry = pSegments[i].load(memory_model::memory_order_relaxed) ;
if ( pEntry != null_ptr<table_entry *>() )
destroy_segment( pEntry ) ;
}
destroy_table( pSegments ) ;
}
/// Returns head node of the bucket \p nBucket
node_type * bucket( size_t nBucket ) const
{
size_t nSegment = nBucket >> m_metrics.nSegmentSizeLog2 ;
assert( nSegment < m_metrics.nSegmentCount ) ;
table_entry * pSegment = m_Segments[ nSegment ].load(memory_model::memory_order_acquire) ;
if ( pSegment == null_ptr<table_entry *>() )
return null_ptr<node_type *>() ; // uninitialized bucket
return pSegment[ nBucket & (m_metrics.nSegmentSize - 1) ].load(memory_model::memory_order_acquire) ;
}
/// Set head node \p pNode of bucket \p nBucket
void bucket( size_t nBucket, node_type * pNode )
{
size_t nSegment = nBucket >> m_metrics.nSegmentSizeLog2 ;
assert( nSegment < m_metrics.nSegmentCount ) ;
segment_type& segment = m_Segments[nSegment] ;
if ( segment.load(memory_model::memory_order_relaxed) == null_ptr<table_entry *>() ) {
table_entry * pNewSegment = allocate_segment() ;
table_entry * pNull = null_ptr<table_entry *>() ;
if ( !segment.compare_exchange_strong( pNull, pNewSegment, memory_model::memory_order_release, CDS_ATOMIC::memory_order_relaxed )) {
destroy_segment( pNewSegment ) ;
}
}
segment.load(memory_model::memory_order_acquire)[ nBucket & (m_metrics.nSegmentSize - 1) ].store( pNode, memory_model::memory_order_release ) ;
}
/// Returns the capacity of the bucket table
size_t capacity() const
{
return m_metrics.nCapacity ;
}
/// Returns the load factor, i.e. average count of items per bucket
size_t load_factor() const
{
return m_metrics.nLoadFactor ;
}
};
/// Split-list node traits
/**
This traits is intended for converting between underlying ordered list node type
and split-list node type
Template parameter:
- \p BaseNodeTraits - node traits of base ordered list type
*/
template <class BaseNodeTraits>
struct node_traits: private BaseNodeTraits
{
typedef BaseNodeTraits base_class ; ///< Base ordered list type
typedef typename base_class::value_type value_type ; ///< Value type
typedef typename base_class::node_type base_node_type ; ///< Ordered list node type
typedef node<base_node_type> node_type ; ///< Spit-list node type
/// Convert value reference to node pointer
static node_type * to_node_ptr( value_type& v )
{
return static_cast<node_type *>( base_class::to_node_ptr( v ) ) ;
}
/// Convert value pointer to node pointer
static node_type * to_node_ptr( value_type * v )
{
return static_cast<node_type *>( base_class::to_node_ptr( v ) ) ;
}
/// Convert value reference to node pointer (const version)
static node_type const * to_node_ptr( value_type const& v )
{
return static_cast<node_type const*>( base_class::to_node_ptr( v ) ) ;
}
/// Convert value pointer to node pointer (const version)
static node_type const * to_node_ptr( value_type const * v )
{
return static_cast<node_type const *>( base_class::to_node_ptr( v ) ) ;
}
/// Convert node refernce to value pointer
static value_type * to_value_ptr( node_type& n )
{
return base_class::to_value_ptr( static_cast<base_node_type &>( n ) ) ;
}
/// Convert node pointer to value pointer
static value_type * to_value_ptr( node_type * n )
{
return base_class::to_value_ptr( static_cast<base_node_type *>( n ) ) ;
}
/// Convert node reference to value pointer (const version)
static const value_type * to_value_ptr( node_type const & n )
{
return base_class::to_value_ptr( static_cast<base_node_type const &>( n ) ) ;
}
/// Convert node pointer to value pointer (const version)
static const value_type * to_value_ptr( node_type const * n )
{
return base_class::to_value_ptr( static_cast<base_node_type const *>( n ) ) ;
}
};
//@cond
namespace details {
template <bool Value, typename GC, typename Node, CDS_DECL_OPTIONS2>
struct bucket_table_selector ;
template <typename GC, typename Node, CDS_SPEC_OPTIONS2>
struct bucket_table_selector< true, GC, Node, CDS_OPTIONS2>
{
typedef expandable_bucket_table<GC, Node, CDS_OPTIONS2> type ;
};
template <typename GC, typename Node, CDS_SPEC_OPTIONS2>
struct bucket_table_selector< false, GC, Node, CDS_OPTIONS2>
{
typedef static_bucket_table<GC, Node, CDS_OPTIONS2> type ;
};
template <typename GC, class Alloc >
struct dummy_node_disposer {
template <typename Node>
void operator()( Node * p )
{
typedef cds::details::Allocator< Node, Alloc > node_deallocator ;
node_deallocator().Delete( p ) ;
}
};
template <typename Q>
struct search_value_type
{
Q& val ;
size_t nHash ;
search_value_type( Q& v, size_t h )
: val( v )
, nHash( h )
{}
};
# ifndef CDS_CXX11_LAMBDA_SUPPORT
template <typename Func>
class find_functor_wrapper: protected cds::details::functor_wrapper<Func>
{
typedef cds::details::functor_wrapper<Func> base_class ;
public:
find_functor_wrapper( Func f )
: base_class( f )
{}
template <typename ValueType, typename Q>
void operator()( ValueType& item, split_list::details::search_value_type<Q>& val )
{
base_class::get()( item, val.val ) ;
}
};
# endif
template <class OrderedList, class Options>
class rebind_list_options
{
typedef OrderedList native_ordered_list ;
typedef Options options ;
typedef typename native_ordered_list::gc gc ;
typedef typename native_ordered_list::key_comparator native_key_comparator ;
typedef typename native_ordered_list::node_type node_type ;
typedef typename native_ordered_list::value_type value_type ;
typedef typename native_ordered_list::node_traits node_traits ;
typedef typename native_ordered_list::disposer native_disposer ;
typedef split_list::node<node_type> splitlist_node_type ;
struct key_compare {
int operator()( value_type const& v1, value_type const& v2 ) const
{
splitlist_node_type const * n1 = static_cast<splitlist_node_type const *>( node_traits::to_node_ptr( v1 )) ;
splitlist_node_type const * n2 = static_cast<splitlist_node_type const *>( node_traits::to_node_ptr( v2 )) ;
if ( n1->m_nHash != n2->m_nHash )
return n1->m_nHash < n2->m_nHash ? -1 : 1 ;
if ( n1->is_dummy() ) {
assert( n2->is_dummy() ) ;
return 0 ;
}
assert( !n1->is_dummy() && !n2->is_dummy() ) ;
return native_key_comparator()( v1, v2 ) ;
}
template <typename Q>
int operator()( value_type const& v, search_value_type<Q> const& q ) const
{
splitlist_node_type const * n = static_cast<splitlist_node_type const *>( node_traits::to_node_ptr( v )) ;
if ( n->m_nHash != q.nHash )
return n->m_nHash < q.nHash ? -1 : 1 ;
assert( !n->is_dummy() ) ;
return native_key_comparator()( v, q.val ) ;
}
template <typename Q>
int operator()( search_value_type<Q> const& q, value_type const& v ) const
{
return -operator()( v, q ) ;
}
};
struct wrapped_disposer
{
void operator()( value_type * v )
{
splitlist_node_type * p = static_cast<splitlist_node_type *>( node_traits::to_node_ptr( v )) ;
if ( p->is_dummy() )
dummy_node_disposer<gc, typename options::allocator>()( p ) ;
else
native_disposer()( v ) ;
}
};
public:
template <typename Less>
struct make_compare_from_less: public cds::opt::details::make_comparator_from_less<Less>
{
typedef cds::opt::details::make_comparator_from_less<Less> base_class ;
template <typename Q>
int operator()( value_type const& v, search_value_type<Q> const& q ) const
{
splitlist_node_type const * n = static_cast<splitlist_node_type const *>( node_traits::to_node_ptr( v )) ;
if ( n->m_nHash != q.nHash )
return n->m_nHash < q.nHash ? -1 : 1 ;
assert( !n->is_dummy() ) ;
return base_class()( v, q.val ) ;
}
template <typename Q>
int operator()( search_value_type<Q> const& q, value_type const& v ) const
{
splitlist_node_type const * n = static_cast<splitlist_node_type const *>( node_traits::to_node_ptr( v )) ;
if ( n->m_nHash != q.nHash )
return q.nHash < n->m_nHash ? -1 : 1 ;
assert( !n->is_dummy() ) ;
return base_class()( q.val, v ) ;
}
template <typename Q1, typename Q2>
int operator()( Q1 const& v1, Q2 const& v2 ) const
{
return base_class()( v1, v2 ) ;
}
};
typedef typename native_ordered_list::template rebind_options<
opt::compare< key_compare >
,opt::disposer< wrapped_disposer >
,opt::boundary_node_type< splitlist_node_type >
>::type result ;
};
template <typename OrderedList, bool IsConst>
struct select_list_iterator ;
template <typename OrderedList>
struct select_list_iterator<OrderedList, false>
{
typedef typename OrderedList::iterator type ;
};
template <typename OrderedList>
struct select_list_iterator<OrderedList, true>
{
typedef typename OrderedList::const_iterator type ;
};
template <typename NodeTraits, typename OrderedList, bool IsConst>
class iterator_type
{
typedef OrderedList ordered_list_type ;
protected:
typedef typename select_list_iterator<ordered_list_type, IsConst>::type list_iterator ;
typedef NodeTraits node_traits ;
private:
list_iterator m_itCur ;
list_iterator m_itEnd ;
public:
typedef typename list_iterator::value_ptr value_ptr ;
typedef typename list_iterator::value_ref value_ref ;
public:
iterator_type()
{}
iterator_type( iterator_type const& src )
: m_itCur( src.m_itCur )
, m_itEnd( src.m_itEnd )
{}
// This ctor should be protected...
iterator_type( list_iterator itCur, list_iterator itEnd )
: m_itCur( itCur )
, m_itEnd( itEnd )
{
// skip dummy nodes
while ( m_itCur != m_itEnd && node_traits::to_node_ptr( *m_itCur )->is_dummy() )
++m_itCur ;
}
value_ptr operator ->() const
{
return m_itCur.operator->() ;
}
value_ref operator *() const
{
return m_itCur.operator*() ;
}
/// Pre-increment
iterator_type& operator ++()
{
if ( m_itCur != m_itEnd ) {
do {
++m_itCur ;
} while ( m_itCur != m_itEnd && node_traits::to_node_ptr( *m_itCur )->is_dummy() ) ;
}
return *this ;
}
iterator_type& operator = (iterator_type const& src)
{
m_itCur = src.m_itCur ;
m_itEnd = src.m_itEnd ;
return *this ;
}
template <bool C>
bool operator ==(iterator_type<node_traits, ordered_list_type, C> const& i ) const
{
return m_itCur == i.m_itCur ;
}
template <bool C>
bool operator !=(iterator_type<node_traits, ordered_list_type, C> const& i ) const
{
return m_itCur != i.m_itCur ;
}
};
} // namespace details
//@endcond
//@cond
// Helper functions
/// Reverses bit order in \p nHash
static inline size_t reverse_bits( size_t nHash )
{
return bitop::RBO( nHash ) ;
}
static inline size_t regular_hash( size_t nHash )
{
return reverse_bits( nHash ) | size_t(1) ;
}
static inline size_t dummy_hash( size_t nHash )
{
return reverse_bits( nHash ) & ~size_t(1) ;
}
//@endcond
} // namespace split_list
//@cond
// Forward declaration
template <class GC, class OrderedList, class Traits = split_list::type_traits>
class SplitListSet ;
//@endcond
}} // namespace cds::intrusive
#endif // #ifndef __CDS_INTRUSIVE_SPLIT_LIST_BASE_H
| [
"[email protected]"
]
| |
be30b42d3cf73eef31b6f6b8405b8a2038e842b5 | 48a761c24be1181b7506f656ad4ac734944dc24e | /Appointment_System/src/controller/MainWindowUIController.cpp | 8f71aae5c21316bcf684d86c3f2cadf901b5ddd3 | []
| no_license | hchen106/Appointment_System | 9fb48f99da2c9eb5f55f7624b4f51d35ec17418d | 1b9984bce4896a1965256e1b4af465454e24f78b | refs/heads/master | 2023-02-09T23:21:53.556304 | 2021-01-05T04:32:25 | 2021-01-05T04:32:25 | 281,277,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,074 | cpp | #include "controller.h"
#include "src/model/tcpConnection.h"
#include <iostream>
using namespace boost::asio;
Controller::MainWindowUIController::MainWindowUIController(tcpConnection::pointer connection, std::string username)
: new_connection(connection), loginID(username){
}
std::string Controller::MainWindowUIController::read_message() {
boost::array<char, 512> buf;
//size_t len = new_connection->socket().read_some(boost::asio::buffer(buf));
size_t len = boost::asio::read(new_connection->socket(),boost::asio::buffer(buf));
std::string str = buf.data();
str = str.substr(0,len);
//boost::asio::write(new_connection->socket(), boost::asio::buffer("received"));
return str;
}
Controller::addClientController* Controller::MainWindowUIController::createAddClientController() {
Controller::addClientController *controller = new Controller::addClientController(new_connection, loginID);
return controller;
}
Controller::addAppointmentSettingController* Controller::MainWindowUIController::createAddAppointmentSetttingController() {
Controller::addAppointmentSettingController *controller = new Controller::addAppointmentSettingController(new_connection, loginID);
return controller;
}
Controller::TimeslotController* Controller::MainWindowUIController::createTimeslotController() {
Controller::TimeslotController *controller = new Controller::TimeslotController(new_connection,loginID);
return controller;
}
std::vector<Json::Value> Controller::MainWindowUIController::load() {
std::string command = loginID + " loadall";
std::cout << command << std::endl;
boost::system::error_code error;
boost::asio::write(new_connection->socket(), boost::asio::buffer(command),error);
bool end = false;
std::vector<std::string> vec;
std::vector<Json::Value> json_vec;
while(!end) {
if(!error) {
//std::cout << "Successfully sent command" << std::endl;
boost::array<char, 512> buf;
boost::asio::streambuf buffer;
//std::size_t len = boost::asio::read(new_connection->socket(),boost::asio::buffer(buf));
std::string str = read_message();
// size_t len = new_connection->socket().read_some(boost::asio::buffer(buf), error);
//std::cout.write(buf.data(), len) << std::endl<<std::endl;
//std::cout << len <<std::endl;
//std::string str = buf.data();
//str = str.substr(0,len);
std::cout << str << std::endl << std::endl;
//std::cout << len << std::endl;
std::string extendsion(512-3, ' ');
std::string ed = "End" + extendsion;
//std::cout << ed.size() << std::endl;
if(str == ed) {
end = true;
}else {
// boost::asio::write(new_connection->socket(), boost::asio::buffer("received"));
Json::Value jsonPacket;
std::stringstream(str) >> jsonPacket;
std::cout << jsonPacket << std::endl;
json_vec.push_back(jsonPacket);
//vec.push_back(str);
// Json::Value jsonPacket;
// std::stringstream(str) >> jsonPacket;
// std::cout << jsonPacket << std::endl;
}
}
}
/*
for(int i =0; i < vec.size(); i++) {
Json::Value jsonPacket;
std::stringstream(vec[i]) >> jsonPacket;
std::cout << jsonPacket << std::endl;
json_vec.push_back(jsonPacket);
//QString qs = QString::fromStdString(vec[i]);
//QStandardItem *item = new QStandardItem(qs);
//model.insertRow(0,item);
}
*/
return json_vec;
}
void Controller::MainWindowUIController::closeConnection() {
std::string command = "server logout";
std::cout << command << std::endl;
boost::system::error_code error;
boost::asio::write(new_connection->socket(), boost::asio::buffer(command),error);
}
| [
"[email protected]"
]
| |
c0c6249dd1aceacb736245e90196fe8ef2cc4edb | 23c6e6f35680bee885ee071ee123870c3dbc1e3d | /test/libcxx/containers/pop_back.pass.cpp | c4c70a1aa5fddf5645e3bdd85b0a43ed65e7689f | []
| no_license | paradise-fi/divine | 3a354c00f39ad5788e08eb0e33aff9d2f5919369 | d47985e0b5175a7b4ee506fb05198c4dd9eeb7ce | refs/heads/master | 2021-07-09T08:23:44.201902 | 2021-03-21T14:24:02 | 2021-03-21T14:24:02 | 95,647,518 | 15 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,158 | cpp | /* TAGS: c++ fin */
/* CC_OPTS: -std=c++2a */
/* VERIFY_OPTS: -o nofail:malloc */
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <list>
// void pop_back();
#include <list>
#include <cassert>
#include "test_macros.h"
#include "min_allocator.h"
int main(int, char**)
{
{
int a[] = {1, 2, 3};
std::list<int> c(a, a+3);
c.pop_back();
assert(c == std::list<int>(a, a+2));
c.pop_back();
assert(c == std::list<int>(a, a+1));
c.pop_back();
assert(c.empty());
}
#if TEST_STD_VER >= 11
{
int a[] = {1, 2, 3};
std::list<int, min_allocator<int>> c(a, a+3);
c.pop_back();
assert((c == std::list<int, min_allocator<int>>(a, a+2)));
c.pop_back();
assert((c == std::list<int, min_allocator<int>>(a, a+1)));
c.pop_back();
assert(c.empty());
}
#endif
return 0;
}
| [
"[email protected]"
]
| |
5ba5b40f6015512d971c77e4523199445bd9d299 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/xgboost/xgboost-gumtree/dmlc_xgboost_old_hunk_376.cpp | 1dc7ebc970e22dd26335e90d6216b781e1398fe1 | []
| no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 232 | cpp | fprintf(stderr, "start %s:%d\n", pname.c_str(), rabit::GetRank());
}
if (rabit::IsDistributed()) {
this->SetParam("data_split", "col");
}
if (rabit::GetRank() != 0) {
this->SetParam("silent", "2");
| [
"[email protected]"
]
| |
12e84494200b0b10a6f289228697a80ad1b8d074 | e27d27e615f576921592881a6d3c33755e339795 | /leetcode/Dynamic Programming/New 21 Game.cpp | f2ee3075bdcdbc093ee6fea541d3bed75a16f99a | []
| no_license | sangyx/algorithm | 3917f919dcbea001621d7d067dc57c56c16cac2d | aae0a8f474d4b1a2d21c0c211c638091893ce2a0 | refs/heads/master | 2021-07-10T06:01:13.819596 | 2020-07-31T08:05:26 | 2020-07-31T08:05:26 | 168,488,217 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 469 | cpp | class Solution {
public:
double new21Game(int N, int K, int W) {
if (K == 0 || N >= K + W) return 1.0;
vector<double> sum(K + W);
sum[0] = 1.0;
for (int i = 1; i < K + W; ++i) {
int t = min(i - 1, K - 1);
if (i <= W) sum[i] = sum[i - 1] + sum[t] / W;
else sum[i] = sum[i - 1] + (sum[t] - sum[i - W - 1]) / W;
}
return (sum[N] - sum[K - 1]) / (sum[K + W - 1] - sum[K - 1]);
}
}; | [
"[email protected]"
]
| |
e8720582c07931ef4ac65efd606f783a16c68482 | 234efff5291e2ab5e87ef71eb8ad80ec3b1854a2 | /TestingHexThrombus/processor12/0.001/s | 496125db98f140dcdaf88397ccc197c5a4f455dc | []
| no_license | tomwpeach/thrombus-code | 5c6f86f0436177d9bbacae70d43f645d70be1a97 | 8cd3182c333452543f3feaecde08282bebdc00ed | refs/heads/master | 2021-05-01T12:25:22.036621 | 2018-04-10T21:45:28 | 2018-04-10T21:45:28 | 121,060,409 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,614 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.1.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.001";
object s;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 0.75;
boundaryField
{
INLET
{
type fixedValue;
value nonuniform 0();
}
OUTLET
{
type zeroGradient;
}
WALL
{
type fixedValue;
value uniform 0.75;
}
PATCH
{
type fixedValue;
value nonuniform 0();
}
procBoundary12to8
{
type processor;
value uniform 0.75;
}
procBoundary12to13
{
type processor;
value uniform 0.75;
}
procBoundary12to14
{
type processor;
value uniform 0.75;
}
}
// ************************************************************************* //
| [
"tom@tom-VirtualBox.(none)"
]
| tom@tom-VirtualBox.(none) |
|
473367db9dc53f28947c96650f918de260bda950 | a06eb8c0df48113910d742e5f6f4a015e9673e77 | /src/HitagiFile.cc | 782abf8420494377350505e326b36c9ce156c945 | []
| no_license | EJDF/EJDF | 9b83336050d4989b72529ee153e21ea4e48fcdc8 | 86912a297d379ee7242b987944c8b65138a89b51 | refs/heads/master | 2021-07-07T07:33:08.904891 | 2018-11-18T04:35:22 | 2018-11-18T04:35:22 | 103,685,907 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 182 | cc | #include "HitagiFile.h"
#include "IOManager.h"
Engine::HitagiFile::HitagiFile(std::string filename){
Engine::IOManager::readFile(filename, this->file);
this->printFile();
}
| [
"[email protected]"
]
| |
f579dff079da04f96df628c2d7c3eaed122575c7 | cb38f5da8916a8c8192fd0d7729652f02417ede7 | /BeagleBone_Blue_catkin_ws/src/data/src/rc_calibrate_mag.cpp | 12f50a0a68e2698e23c289ab6d34cf3602a46eb7 | [
"MIT"
]
| permissive | raymondturrisi/MiniMAUV-software | fe42057687e4fc42436309bd7cc5f0d729f3d638 | 442c3238e3ca441a5fb9544da4163ef2afbaafda | refs/heads/main | 2023-04-23T22:19:44.685960 | 2021-05-12T14:42:14 | 2021-05-12T14:42:14 | 306,679,229 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,407 | cpp | /**
* @file rc_calibrate_mag.c
* @example rc_calibrate_mag
*
* @brief runs the MPU magnetometer calibration routine
*
* If the routine is successful, a new magnetometer calibration file
* will be saved which is loaded automatically the next time the MPU
* is used.
*
* @author James Strawson
* @date 1/29/2018
*/
#include <stdio.h>
extern "C" {
#include <rc/mpu.h>
#include <rc/time.h>
}
// bus for Robotics Cape and BeagleboneBlue is 2
// change this for your platform
#define I2C_BUS 2
int main()
{
printf("\n");
printf("This will sample the magnetometer for the next 15 seconds\n");
printf("Rotate the board around in the air through as many orientations\n");
printf("as possible to collect sufficient data for calibration\n");
printf("Press any key to continue\n");
getchar();
printf("spin spin spin!!!\n\n");
// wait for the user to actually start
rc_usleep(2000000);
rc_mpu_config_t config = rc_mpu_default_config();
config.i2c_bus = I2C_BUS;
if(rc_mpu_calibrate_mag_routine(config)<0){
printf("Failed to complete magnetometer calibration\n");
return -1;
}
printf("\nmagnetometer calibration file written\n");
printf("run rc_test_mpu to check performance\n");
return 0;
}
| [
"[email protected]"
]
| |
54d522f639499dd95e058af644a78a6976203e71 | 84916ee4107768fe18c24b561cfee07235ff388c | /code01/lc145PostOrderTrav.cpp | 67fa6629f83376d7fa176f0da96187c854e5fde0 | []
| no_license | azfa2019/lcCpp | 51bd3b83da6ddb95ce1dacdb8a61307abd98580d | 31d2041d599b4b81ab336ec28421dbe01de7b1ae | refs/heads/master | 2023-01-07T17:02:26.683087 | 2020-11-03T02:37:32 | 2020-11-03T02:37:32 | 288,076,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,695 | cpp | #include<iostream>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<algorithm>
#include <numeric>
using namespace std;
template<typename T>
void showVector(vector<T> g)
{
for (auto it = g.begin(); it != g.end(); ++it)
cout << *it<<" "; //'\t' ;
cout << '\n';
}
class TreeNode{
public:
int val;
TreeNode* lChild;
TreeNode* rChild;
};
class solution{
public:
void postOrderRecurHelper(TreeNode* root,vector<int>& ans){
if(root==nullptr) return;
postOrderRecurHelper(root->lChild,ans);
postOrderRecurHelper(root->rChild,ans);
ans.push_back(root->val);
}
vector<int> postOrderRecur(TreeNode* root){
vector<int> ans;
postOrderRecurHelper(root,ans);
return ans;
}
vector<int> postOrderNonRecur(TreeNode *root){
stack<TreeNode*> s;
deque<int> ans;
s.push(root);
while(s.size()>0){
TreeNode* n=s.top();s.pop();
ans.push_front(n->val);
if(n->lChild) s.push(n->lChild);
if(n->rChild) s.push(n->rChild);
}
return vector<int>(ans.begin(),ans.end());
}
};
int main(){
solution s0;
TreeNode t{4,nullptr,nullptr};
TreeNode n1{1,nullptr,nullptr};
TreeNode n3{3,nullptr,nullptr};
TreeNode n2{2,nullptr,nullptr};
t.lChild=&n1;
t.rChild=&n3;
n3.lChild=&n2;
auto ans=s0.postOrderRecur(&t);
showVector(ans);
cout<<"================================"<<endl;
ans=s0.postOrderNonRecur(&t);
showVector(ans);
cout<<"================================"<<endl;
cout<<"================================"<<endl;
cout<<"================================"<<endl;
return 0;
}
| [
"[email protected]"
]
| |
ef417c6be9fa86aead7983f20513b8394d603405 | 2b04a792ef138484c7bc48bc5a5b4fda140237ce | /Source/AudioSources/WavetableSound.h | 7c7648fe8c300f1528ec0afccc2610d46f4afe95 | []
| no_license | MeijisIrlnd/IPadTouchSynth | c1065729a9de563b5044b020755ab550e51b8270 | 8ea7449f4ef62397bf658b6a10e6ab57376bb165 | refs/heads/main | 2023-02-21T10:15:15.358663 | 2021-01-25T00:14:52 | 2021-01-25T00:14:52 | 332,586,315 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 485 | h | /*
==============================================================================
WavetableSound.h
Created: 24 Jan 2021 10:58:21pm
Author: Syl
==============================================================================
*/
#pragma once
#include <JuceHeader.h>
class WavetableSound : public juce::SynthesiserSound
{
bool appliesToNote(int n) override {
return true;
}
bool appliesToChannel(int n) override {
return true;
}
}; | [
"[email protected]"
]
| |
a81eb70e1656851bc30179796ad80c2aaa4f0c4f | 73709039ac2b42e410c4d1d7b862e4e352a74599 | /ipms_server_api/code_lib/include/epoll.h | 6a1f04619f03172a25275c4e52d6588d22ff6ed9 | []
| no_license | GarfieldLinux/IPMS | a0743629325032b3319d0bb713ed624d0f5c19b7 | 21fab7a2513c402c0c3b3314c974ad7ab0e21a9c | refs/heads/master | 2020-05-29T21:04:21.731270 | 2014-09-24T14:02:23 | 2014-09-24T14:02:23 | 19,529,124 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,735 | h | /************************************************************************************/
//模块名称:EPOLL 基类
//功能说明: 1)创建监听SOCKET
// 2)EPOLL管理
// 3)提供相关事件
// OnAccept()
// OnRecv()
//作者:徐永丰 [email protected]
//日期:2010-09-21
//Copyright (C), 2008-2010 Dnion Tech. Co., Ltd.
/************************************************************************************/
#ifndef __EPOLL_H
#define __EPOLL_H
#include <sys/epoll.h>
#include <pthread.h>
//目前默认处理2000个连接
#ifndef MAX_EPOLL_SIZE
#define MAX_EPOLL_SIZE 2000
#endif
class CEpollBase
{
//公有函数
public:
//构造函数
CEpollBase();
//析构函数
virtual~CEpollBase();
public:
//初始化
bool Init(const unsigned short nPort);
//释放
void UnInit();
//删除一个监听FD
bool DelFd(const int nFd);
//处理一次事件
void WaitOnce();
//用于继承
protected:
//接收连接事件
virtual bool OnAccept(const int nFd) = 0;
//接收消息事件
virtual void OnRecv(const int nFd) = 0;
private:
//开启处理线程
bool BeginDealThread();
//结束处理线程
void EndDealThread();
//开启服务端口
bool BeginServer(const unsigned short nPort);
//关闭服务端口
void EndServer();
//设为非阻塞
bool SetNonblocking(int nFd);
public:
//线程停止标识
bool m_bEndThread;
private:
//监听的SERVER端口
int m_nSockListen;
//当前FD数目
int m_nSizeCurFd;
//EPOLL句柄
int m_nSizeFd;
//EPOLL读写锁
pthread_mutex_t m_fdEpoll_mutex;
//EPOLL EVENT
struct epoll_event m_evEpoll;
//事件处理线程ID
pthread_t m_nThreadID;
};
#endif //__EPOLL_H
| [
"[email protected]"
]
| |
8fd46340790aaa8ee2910a6b0d628fd3b9d79778 | 85ec0860a0a9f5c0c0f0d81ce3cc0baf4b2a812e | /sngcpp20/symbols/Template.hpp | 0f06e5e927224c22a8661f5cc4da3fca009b41a8 | []
| no_license | slaakko/soulng | 3218185dc808fba63e2574b3a158fa1a9f0b2661 | a128a1190ccf71794f1bcbd420357f2c85fd75f1 | refs/heads/master | 2022-07-27T07:30:20.813581 | 2022-04-30T14:22:44 | 2022-04-30T14:22:44 | 197,632,580 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 926 | hpp | // =================================
// Copyright (c) 2022 Seppo Laakko
// Distributed under the MIT license
// =================================
#ifndef SNGCPP_SYMBOLS_TEMPLATE_INCLUDED
#define SNGCPP_SYMBOLS_TEMPLATE_INCLUDED
#include <sngcpp20/symbols/SymbolsApi.hpp>
#include <sngcpp20/ast/Node.hpp>
#include <sngcpp20/symbols/Context.hpp>
namespace sngcpp::symbols {
using namespace sngcpp::ast;
SYMBOLS_API void BeginTemplateDeclaration(Node* templateHeadNode, Context* context);
SYMBOLS_API void EndTemplateDeclaration(Context* context);
SYMBOLS_API void RemoveTemplateDeclaration(Context* context);
SYMBOLS_API void AddTemplateParameter(Node* templateParameterNode, int index, Context* context);
SYMBOLS_API void SetTemplateArgKinds(Node* templateIdNode, Context* context);
SYMBOLS_API bool TemplateArgCanBeTypeId(Node* templateIdNode, int index);
} // sngcpp::symbols
#endif // SNGCPP_SYMBOLS_TEMPLATE_INCLUDED
| [
"[email protected]"
]
| |
4fd96ce838bc7e6ef1217b60695fb472ed1b0457 | 749d78bfd5333ac80364d595bc64a0ee17257fdb | /src/utiltime.cpp | d57fd4ee0cdb1503d6a7f2186baef3044ceb64ab | [
"MIT"
]
| permissive | bitcoinhedge/bitcoinhedge | 22b70fa2c76f6ca54b0c3b6885ad4e852afa3e31 | d627c6fb5e174feb8ce378e29af11846edd2a000 | refs/heads/master | 2023-07-14T14:59:39.741065 | 2021-08-15T06:49:15 | 2021-08-15T06:49:15 | 396,245,260 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,526 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2016-2018 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoinhedge-config.h"
#endif
#include "tinyformat.h"
#include "utiltime.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>
using namespace std;
static int64_t nMockTime = 0; //! For unit testing
int64_t GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64_t nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
int64_t GetTimeMillis()
{
return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)))
.total_milliseconds();
}
int64_t GetTimeMicros()
{
return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)))
.total_microseconds();
}
void MilliSleep(int64_t n)
{
/**
* Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50
* until fixed in 1.52. Use the deprecated sleep method for the broken case.
* See: https://svn.boost.org/trac/boost/ticket/7238
*/
#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
#elif defined(HAVE_WORKING_BOOST_SLEEP)
boost::this_thread::sleep(boost::posix_time::milliseconds(n));
#else
//should never get here
#error missing boost sleep implementation
#endif
}
std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
{
// std::locale takes ownership of the pointer
std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
std::stringstream ss;
ss.imbue(loc);
ss << boost::posix_time::from_time_t(nTime);
return ss.str();
}
std::string DurationToDHMS(int64_t nDurationTime)
{
int seconds = nDurationTime % 60;
nDurationTime /= 60;
int minutes = nDurationTime % 60;
nDurationTime /= 60;
int hours = nDurationTime % 24;
int days = nDurationTime / 24;
if (days)
return strprintf("%dd %02dh:%02dm:%02ds", days, hours, minutes, seconds);
if (hours)
return strprintf("%02dh:%02dm:%02ds", hours, minutes, seconds);
return strprintf("%02dm:%02ds", minutes, seconds);
}
| [
"[email protected]"
]
| |
f88456870b5ee97eeeff94607abdfa0e4ce59ca4 | cbce9107a4a38f263242b5224251a1ced8d75fec | /bootstrap/Renderer2D.h | 08bdb0e4aa7023c3e07e2f3773d372f1b4b72ba6 | []
| no_license | jakrevai/Jak_Revai_Town_Simulation | 3268e38dfe670113528e22b3d74119309da9807f | aa15e39ef0b4b94a638816576c658ce5c34263a3 | refs/heads/master | 2020-04-05T02:44:49.996187 | 2018-11-07T04:18:32 | 2018-11-07T04:18:32 | 156,488,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,497 | h | #pragma once
namespace aie {
class Texture;
class Font;
// a class for rendering 2D sprites and font
class Renderer2D {
public:
Renderer2D();
virtual ~Renderer2D();
// all draw calls must occur between a begin / end pair
virtual void begin();
virtual void end();
// simple shape rendering
virtual void drawBox(float xPos, float yPos, float width, float height, float rotation = 0.0f);
virtual void drawCircle(float xPos, float yPos, float radius);
// if texture is nullptr then it renders a coloured sprite
// depth is in the range [0,100] with lower being closer to the viewer
virtual void drawSprite(Texture* texture, float xPos, float yPos, float width = 0.0f, float height = 0.0f, float rotation = 0.0f, float depth = 0.0f, float xOrigin = 0.5f, float yOrigin = 0.5f);
virtual void drawSpriteTransformed3x3(Texture* texture, float* transformMat3x3, float width = 0.0f, float height = 0.0f, float depth = 0.0f, float xOrigin = 0.5f, float yOrigin = 0.5f);
virtual void drawSpriteTransformed4x4(Texture* texture, float* transformMat4x4, float width = 0.0f, float height = 0.0f, float depth = 0.0f, float xOrigin = 0.5f, float yOrigin = 0.5f);
// draws a simple coloured line with a given thickness
// depth is in the range [0,100] with lower being closer to the viewer
virtual void drawLine(float x1, float y1, float x2, float y2, float thickness = 1.0f, float depth = 0.0f );
// draws simple text on the screen horizontally
// depth is in the range [0,100] with lower being closer to the viewer
virtual void drawText(Font* font, const char* text, float xPos, float yPos, float depth = 0.0f);
// sets the tint colour for all subsequent draw calls
void setRenderColour(float r, float g, float b, float a = 1.0f);
void setRenderColour(unsigned int colour);
// can be used to set the texture coordinates of sprites using textures
// for all subsequent drawSprite calls
void setUVRect(float uvX, float uvY, float uvW, float uvH);
// specify the camera position
void setCameraPos(float x, float y) { m_cameraX = x; m_cameraY = y; }
void getCameraPos(float& x, float& y) const { x = m_cameraX; y = m_cameraY; }
protected:
// helper methods used during drawing
bool shouldFlush(int additionalVertices = 0, int additionalIndices = 0);
void flushBatch();
unsigned int pushTexture(Texture* texture);
// indicates in the middle of a begin/end pair
bool m_renderBegun;
// the camera position
float m_cameraX, m_cameraY;
// texture handling
enum { TEXTURE_STACK_SIZE = 16 };
Texture* m_nullTexture;
Texture* m_textureStack[TEXTURE_STACK_SIZE];
int m_fontTexture[TEXTURE_STACK_SIZE];
unsigned int m_currentTexture;
// texture coordinate information
float m_uvX, m_uvY, m_uvW, m_uvH;
// represents colour in red, green, blue and alpha 0.0-1.0 range
float m_r, m_g, m_b, m_a;
// sprite handling
enum { MAX_SPRITES = 512 };
struct SBVertex {
float pos[4];
float color[4];
float texcoord[2];
};
// data used for opengl to draw the sprites (with padding)
SBVertex m_vertices[MAX_SPRITES * 4];
unsigned short m_indices[MAX_SPRITES * 6];
int m_currentVertex, m_currentIndex;
unsigned int m_vao, m_vbo, m_ibo;
// shader used to render sprites
unsigned int m_shader;
// helper method used to rotate sprites around a pivot
void rotateAround(float inX, float inY, float& outX, float& outY, float sin, float cos);
// data used for a virtual camera
float m_projectionMatrix[16];
};
} // namespace aie | [
"[email protected]"
]
| |
0594c9f8f8656ac30e96dc26d09235a46a485cdf | 527739ed800e3234136b3284838c81334b751b44 | /include/RED4ext/Types/generated/game/interactions/InteractionEvent.hpp | 23b9475eadb6e5d6c569d4594c05124b2a558af9 | [
"MIT"
]
| permissive | 0xSombra/RED4ext.SDK | 79ed912e5b628ef28efbf92d5bb257b195bfc821 | 218b411991ed0b7cb7acd5efdddd784f31c66f20 | refs/heads/master | 2023-07-02T11:03:45.732337 | 2021-04-15T16:38:19 | 2021-04-15T16:38:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,053 | hpp | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/Handle.hpp>
#include <RED4ext/Types/generated/game/interactions/EInteractionEventType.hpp>
#include <RED4ext/Types/generated/game/interactions/LayerData.hpp>
#include <RED4ext/Types/generated/red/Event.hpp>
namespace RED4ext
{
namespace game { struct Object; }
namespace game::interactions {
struct InteractionEvent : red::Event
{
static constexpr const char* NAME = "gameinteractionsInteractionEvent";
static constexpr const char* ALIAS = "InteractionEvent";
WeakHandle<game::Object> hotspot; // 40
WeakHandle<game::Object> activator; // 50
game::interactions::LayerData layerData; // 60
game::interactions::EInteractionEventType eventType; // 68
uint8_t unk6C[0x70 - 0x6C]; // 6C
};
RED4EXT_ASSERT_SIZE(InteractionEvent, 0x70);
} // namespace game::interactions
using InteractionEvent = game::interactions::InteractionEvent;
} // namespace RED4ext
| [
"[email protected]"
]
| |
7980af5e984a5903a2f4618059f27f6f0f3590f1 | d5fb726ae2eb18469da8f97ef89f0bb5038f8471 | /bakingdog/basic-algo-lecture-master/basic-algo-lecture-master/0x03/solutions/1919.cpp | ce8269325742c9bd6b4c5145cfe188f0af1560fa | []
| no_license | fpzk5656/studio-code | 3fe9b853ca0a79c53503d71647470a19d7c11cd1 | d095afda3aaad35d988f8f929e18ff062b4a7a4c | refs/heads/master | 2023-08-28T02:12:31.729007 | 2021-10-31T15:11:19 | 2021-10-31T15:11:19 | 349,780,230 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 444 | cpp | // Authored by : twinkite
// Co-authored by : BaaaaaaaaaaarkingDog
// http://boj.kr/ae5d8d2f69f04530b4df0c591e9b07d5
#include <bits/stdc++.h>
using namespace std;
int arr[2][26], res;
string s1, s2;
int main(void){
ios::sync_with_stdio(0);
cin.tie(0);
cin>>s1>>s2;
for(char c : s1)
arr[0][c-'a']++;
for(char c : s2)
arr[1][c-'a']++;
for(int i=0; i<26; i++)
res += abs(arr[0][i]-arr[1][i]);
cout << res;
}
| [
"[email protected]"
]
| |
a3d863709e3cd887744fdecd3913cd691a0bb47e | 146283549c402ae088d12a038b3714c08f08e744 | /Browse/Client/src/Singletons/FirebaseMailer.cpp | 355bb341e48409e2c35f84d1daf7a2f6b0d6c5f4 | [
"MIT",
"Apache-2.0"
]
| permissive | MAMEM/GazeTheWeb | 1ccc9473c7d8fd563ac5f0577e30e711aebd6285 | 54e1bf129c5ba64fd9518060d8538c46f0540ebb | refs/heads/master | 2021-12-28T08:15:32.143211 | 2021-08-29T21:16:25 | 2021-08-29T21:16:25 | 53,029,317 | 37 | 17 | null | 2018-11-13T11:07:17 | 2016-03-03T07:12:47 | C++ | UTF-8 | C++ | false | false | 26,061 | cpp | //============================================================================
// Distributed under the Apache License, Version 2.0.
// Author: Raphael Menges ([email protected])
//============================================================================
#include "FirebaseMailer.h"
#include "src/Utils/glmWrapper.h"
#include "src/Utils/Logger.h"
#include "src/Utils/Helper.h"
#include "externals/curl/include/curl/curl.h"
#include <sstream>
#include <chrono>
using json = nlohmann::json;
// ########################
// ### TEMPLATE HELPERS ###
// ########################
// Fallback for values when not found in database etc.
template<typename Type> Type fallback();
template<> int fallback<int>() { return 0; };
template<> std::string fallback<std::string>() { return ""; };
template<> json fallback<json>() { return json(); };
// ####################
// ### HTTP HELPERS ###
// ####################
// Write callback for CURL
size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
// Checks for something in the first line of HTTP header
bool HttpHeaderFirstLineContains(const std::string& rHeader, const std::string& rCompareTo)
{
std::string firstLine = rHeader.substr(0, rHeader.find("\n"));
return firstLine.find(rCompareTo) != std::string::npos;
}
// Checks header for ok
bool HttpHeaderOK(const std::string& rHeader)
{
return HttpHeaderFirstLineContains(rHeader, "200 OK")
|| HttpHeaderFirstLineContains(rHeader, "100 Continue"); // Google sometimes returns this and in the third line 200. For now, treating as synonyms
}
// Checks header for failed precondition
bool HttpHeaderPreconditionFailed(const std::string& rHeader)
{
return HttpHeaderFirstLineContains(rHeader, "412 Precondition Failed");
}
// Extract ETag from header, returns empty string if not found
std::string HttpHeaderExtractETag(const std::string& rHeader)
{
std::istringstream lineStream(rHeader);
std::string line;
std::getline(lineStream, line); // first line is not of interest
while(std::getline(lineStream, line)) // go over lines
{
std::istringstream tokenStream(line);
std::string token;
std::vector<std::string> tokens;
while (std::getline(tokenStream, token, ':')) // go over tokens
{
tokens.push_back(token); // collect tokens
}
// Should be two tokens, and first should be "ETag"
if (tokens.size() == 2 && tokens.at(0) == "ETag")
{
// Extract second token as ETag
return tokens.at(1).substr(1, tokens.at(1).length() - 1); // return without preceeding space
}
}
return ""; // return empty string in case of non exisiting ETag
}
// ##########################
// ### FIREBASE INTERFACE ###
// ##########################
bool FirebaseMailer::FirebaseInterface::Login(std::string email, std::string password, bool useDriftMap, std::promise<std::string>* pPromise)
{
// Store email and password
_email = email;
_password = password;
// Perform actual login
bool success = Login();
// If success, retrieve start index
if (success)
{
std::promise<int> promise; auto future = promise.get_future(); // future provides index
Transform(FirebaseIntegerKey::GENERAL_APPLICATION_START_COUNT, 1, &promise); // adds one to the count
int index = future.get() - 1;
nlohmann::json record = {
{ "date", GetDate() }, // add date
{ "timestamp", GetTimestamp() }, // add timestamp
{ "version", CLIENT_VERSION }, // add version
{ "useDriftMap", useDriftMap } // add information whether drift map is used
};
Put(FirebaseJSONKey::GENERAL_APPLICATION_START, record, std::to_string(index)); // send JSON to database
*_pStartIndex = index;
}
// Fullfill the promise
pPromise->set_value(_pIdToken->Get());
// Return the success
return success;
}
template<typename T>
void FirebaseMailer::FirebaseInterface::Put(T key, typename FirebaseValue<T>::type value, std::string subpath)
{
// Only continue if logged in
bool success = false;
if (_pIdToken->IsSet())
{
// Setup CURL
CURL *curl;
curl = curl_easy_init();
// Continue if CURL was initialized
if (curl)
{
// Local variables
std::string answerHeaderBuffer;
std::string answerBodyBuffer;
// Request URL
std::string requestURL =
_URL + "/"
+ BuildFirebaseKey(key, _uid) + "/" + subpath
+ ".json"
+ "?auth=" + _pIdToken->Get();
// Setup CURL
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // follow potential redirection
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); // tell about PUTting
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L); // CURL told me to use it
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, WriteCallback); // set callback for answer header
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); // set callback for answer body
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &answerHeaderBuffer); // set buffer for answer header
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &answerBodyBuffer); // set buffer for answer body
// Post field
const std::string postField = json(value).dump();
// Fill request
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postField.c_str()); // value to put
curl_easy_setopt(curl, CURLOPT_URL, requestURL.c_str()); // set address of request
// Perform the request
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) // everything ok with CURL
{
// Check header
if (HttpHeaderOK(answerHeaderBuffer))
{
success = true; // fine!
}
else // there is something else in header
{
// Try to relogin
if (Relogin()) // returns whether successful
{
// Setup CURL request (reuse stuff from first)
answerHeaderBuffer.clear();
answerBodyBuffer.clear();
requestURL =
_URL + "/"
+ BuildFirebaseKey(key, _uid) + "/" + subpath
+ ".json"
+ "?auth=" + _pIdToken->Get();
curl_easy_setopt(curl, CURLOPT_URL, requestURL.c_str()); // set address of new request
// Try again to PUT data
res = curl_easy_perform(curl);
if (res == CURLE_OK) // everything ok with CURL
{
if (HttpHeaderOK(answerHeaderBuffer))
{
success = true; // fine!
}
// else: ok, it failed.
}
}
}
}
// Cleanup
curl_easy_cleanup(curl); curl = nullptr;
}
}
// Tell user about no success
if (!success)
{
LogError("FirebaseInterface: ", "Data transfer to Firebase failed.");
}
}
template<typename T>
void FirebaseMailer::FirebaseInterface::Get(T key, std::promise<typename FirebaseValue<T>::type>* pPromise)
{
auto result = Get(BuildFirebaseKey(key, _uid));
if(!result.value.empty()) // result might be empty and json does not like to convert empty stuff
{
pPromise->set_value(result.value.get<typename FirebaseValue<T>::type>());
}
else
{
pPromise->set_value(fallback<typename FirebaseValue<T>::type>()); // for empty result, just use fallback
}
}
void FirebaseMailer::FirebaseInterface::Transform(FirebaseIntegerKey key, int delta, std::promise<int>* pPromise)
{
// Just add the delta to the existing value
auto result = Apply(key, [delta](int DBvalue) { return DBvalue + delta; });
if (pPromise != nullptr) { pPromise->set_value(result); }
}
void FirebaseMailer::FirebaseInterface::Maximum(FirebaseIntegerKey key, int value, std::promise<int>* pPromise)
{
// Use maximum of database value and this
auto result = Apply(key, [value](int DBvalue) { return glm::max(DBvalue, value); });
if (pPromise != nullptr) { pPromise->set_value(result); }
}
bool FirebaseMailer::FirebaseInterface::Login()
{
bool success = false;
// Invalidate tokens
_pIdToken->Reset();
_refreshToken = "";
// Setup CURL
CURL *curl;
curl = curl_easy_init();
// Continue if CURL was initialized
if (curl)
{
// Local variables
CURLcode res;
std::string postBuffer;
std::string answerHeaderBuffer;
std::string answerBodyBuffer;
struct curl_slist* headers = nullptr; // init to NULL is important
headers = curl_slist_append(headers, "Content-Type: application/json"); // type is JSON
// Set options
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); // apply header
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // follow potential redirection
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, WriteCallback); // set callback for answer header
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); // set callback for answer body
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &answerHeaderBuffer); // set buffer for answer header
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &answerBodyBuffer); // set buffer for answer body
// Post field
const json jsonPost =
{
{ "email", _email }, // email of user
{ "password", _password }, // password to access database
{ "returnSecureToken", true } // of course, thats what this is about
};
postBuffer = jsonPost.dump(); // store in a string, otherwise it breaks (CURL probably wants a reference)
// Fill request
curl_easy_setopt(curl, CURLOPT_URL, "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=" + _API_KEY); // URL to access
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postBuffer); // fill post body
// Execute request
res = curl_easy_perform(curl);
if (res != CURLE_OK) // something went wrong
{
LogError("FirebaseInterface: ", "User login to Firebase failed: ", curl_easy_strerror(res));
return false;
}
// Cleanup
curl_slist_free_all(headers); headers = nullptr;
curl_easy_cleanup(curl); curl = nullptr;
// Parse answer to JSON object and extract id token
const auto jsonAnswer = json::parse(answerBodyBuffer);
auto result = jsonAnswer.find("idToken");
if (result != jsonAnswer.end())
{
_pIdToken->Set(result.value().get<std::string>());
LogInfo("FirebaseInterface: ", "User successfully logged into Firebase.");
success = true;
}
else
{
LogError("FirebaseInterface: ", "User login to Firebase failed.");
}
// Search for refresh token (optional)
result = jsonAnswer.find("refreshToken");
if (result != jsonAnswer.end())
{
_refreshToken = result.value().get<std::string>();
}
// Search for uid
result = jsonAnswer.find("localId");
if (result != jsonAnswer.end())
{
_uid = result.value().get<std::string>(); // one could "break mailer" if not provided as nothing makes sense
}
}
return success;
}
bool FirebaseMailer::FirebaseInterface::Relogin()
{
bool success = false;
// Store refresh token locally
std::string refreshToken = _refreshToken;
// Invalidate tokens
_pIdToken->Reset();
_refreshToken = "";
// Check for empty refresh token
if (refreshToken.empty())
{
// No relogin through refresh token possible, try complete relogin
success = Login();
}
else // relogin possilbe
{
// Setup CURL
CURL *curl;
curl = curl_easy_init();
// Continue if CURL was initialized
if (curl)
{
// Local variables
CURLcode res;
std::string answerBodyBuffer;
struct curl_slist* headers = nullptr; // init to NULL is important
headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded"); // type is simple form encoding
// Set options
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); // apply header
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // follow potential redirection
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); // set callback for answer body
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &answerBodyBuffer); // set buffer for answer body
// Post field
const std::string postBuffer = "grant_type=refresh_token&refresh_token=" + refreshToken;
// Fill request
curl_easy_setopt(curl, CURLOPT_URL, "https://securetoken.googleapis.com/v1/token?key=" + _API_KEY); // URL to access
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postBuffer); // fill post body
// Execute request
res = curl_easy_perform(curl);
if (res != CURLE_OK) // something went wrong
{
LogError("FirebaseInterface: ", "User reauthentifiation to Firebase failed: ", curl_easy_strerror(res));
return false;
}
// Cleanup
curl_slist_free_all(headers); headers = nullptr;
curl_easy_cleanup(curl); curl = nullptr;
// Parse answer to JSON object and extract id token
const auto jsonAnswer = json::parse(answerBodyBuffer);
auto result = jsonAnswer.find("id_token"); // different from email and password login
if (result != jsonAnswer.end())
{
_pIdToken->Set(result.value().get<std::string>());
LogInfo("FirebaseInterface: ", "User reauthentifiation to Firebase successful.");
success = true;
}
else
{
LogError("FirebaseInterface: ", "User reauthentifiation to Firebase failed.");
}
// Search for refresh token (optional)
result = jsonAnswer.find("refresh_token");
if (result != jsonAnswer.end())
{
_refreshToken = result.value().get<std::string>();
}
}
}
return success;
}
template<typename T>
bool FirebaseMailer::FirebaseInterface::Put(T key, std::string ETag, typename FirebaseValue<T>::type value, std::string& rNewETag, typename FirebaseValue<T>::type& rNewValue, std::string subpath)
{
bool success = false;
rNewETag = "";
rNewValue = fallback<typename FirebaseValue<T>::type>();
// Only continue if logged in
if (_pIdToken->IsSet())
{
// Setup CURL
CURL *curl;
curl = curl_easy_init();
// Continue if CURL was initialized
if (curl)
{
// Local variables
std::string answerHeaderBuffer;
std::string answerBodyBuffer;
struct curl_slist* headers = nullptr; // init to NULL is important
const std::string putHeaderBuffer = "if-match:" + ETag;
headers = curl_slist_append(headers, putHeaderBuffer.c_str()); // 'if-match' criteria to use the ETag
// Request URL
std::string requestURL =
_URL + "/"
+ BuildFirebaseKey(key, _uid) + "/" + subpath
+ ".json"
+ "?auth=" + _pIdToken->Get();
// Setup CURL
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); // apply header
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // follow potential redirection
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); // tell about PUTting
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L); // CURL told me to use it
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, WriteCallback); // set callback for answer header
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); // set callback for answer body
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &answerHeaderBuffer); // set buffer for answer header
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &answerBodyBuffer); // set buffer for answer body
// Post field
const std::string postField = json(value).dump();
// Fill request
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postField.c_str()); // value to put
curl_easy_setopt(curl, CURLOPT_URL, requestURL.c_str()); // set address of request
// Perform the request
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) // everything ok with CURL
{
// Check header
if (HttpHeaderOK(answerHeaderBuffer))
{
success = true; // fine!
}
else if (HttpHeaderPreconditionFailed(answerHeaderBuffer))
{
// Fill newETag and newValue
rNewETag = HttpHeaderExtractETag(answerHeaderBuffer);
rNewValue = json::parse(answerBodyBuffer).get<typename FirebaseValue<T>::type>();
}
else // there is something else in header
{
// Try to relogin
if (Relogin()) // returns whether successful
{
// Setup CURL request (reuse stuff from first)
answerHeaderBuffer.clear();
answerBodyBuffer.clear();
requestURL =
_URL + "/"
+ BuildFirebaseKey(key, _uid) + "/" + subpath
+ ".json"
+ "?auth=" + _pIdToken->Get();
curl_easy_setopt(curl, CURLOPT_URL, requestURL.c_str()); // set address of new request
// Try again to PUT data
res = curl_easy_perform(curl);
if (res == CURLE_OK) // everything ok with CURL
{
if (HttpHeaderOK(answerHeaderBuffer))
{
success = true; // fine!
}
else if (HttpHeaderPreconditionFailed(answerHeaderBuffer))
{
// Fill newETag and newValue
rNewETag = HttpHeaderExtractETag(answerHeaderBuffer);
rNewValue = json::parse(answerBodyBuffer).get<typename FirebaseValue<T>::type>();
}
// else: ok, it failed.
}
}
}
}
// Cleanup
curl_slist_free_all(headers); headers = nullptr;
curl_easy_cleanup(curl); curl = nullptr;
}
}
return success;
}
FirebaseMailer::FirebaseInterface::DBEntry FirebaseMailer::FirebaseInterface::Get(std::string key)
{
// Return value
DBEntry result;
// Only continue if logged in
if (_pIdToken->IsSet())
{
// Setup CURL
CURL *curl;
curl = curl_easy_init();
// Continue if CURL was initialized
if (curl)
{
// Local variables
std::string answerHeaderBuffer;
std::string answerBodyBuffer;
struct curl_slist* headers = nullptr; // init to NULL is important
headers = curl_slist_append(headers, "X-Firebase-ETag: true"); // tell it to deliver ETag to identify the state
// Request URL
std::string requestURL =
_URL + "/"
+ key
+ ".json"
+ "?auth=" + _pIdToken->Get();
// Setup CURL
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); // apply header
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // follow potential redirection
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, WriteCallback); // set callback for answer header
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); // set callback for answer body
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &answerHeaderBuffer); // set buffer for answer header
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &answerBodyBuffer); // set buffer for answer body
curl_easy_setopt(curl, CURLOPT_URL, requestURL.c_str()); // set address of request
// Perform the request
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) // everything ok with CURL
{
// Check header for OK
if (HttpHeaderOK(answerHeaderBuffer))
{
// Parse
result = DBEntry(HttpHeaderExtractETag(answerHeaderBuffer), json::parse(answerBodyBuffer));
}
else // not ok, guess timeout of id token?
{
// Try to relogin
if (Relogin()) // returns whether successful
{
// Setup CURL request (reuse stuff from first)
answerHeaderBuffer.clear();
answerBodyBuffer.clear();
requestURL =
_URL + "/"
+ key
+ ".json"
+ "?auth=" + _pIdToken->Get(); // update request URL as id token should be new
curl_easy_setopt(curl, CURLOPT_URL, requestURL.c_str()); // set address of new request
// Try again to GET data
res = curl_easy_perform(curl);
if (res == CURLE_OK && HttpHeaderOK(answerHeaderBuffer)) // everything ok with CURL and header
{
// Parse
result = DBEntry(HttpHeaderExtractETag(answerHeaderBuffer), json::parse(answerBodyBuffer));
}
}
}
}
// Cleanup of CURL
curl_easy_cleanup(curl); curl = nullptr;
}
}
// Return result
return result;
}
int FirebaseMailer::FirebaseInterface::Apply(FirebaseIntegerKey key, std::function<int(int)> function)
{
bool success = false;
// Call own get method
const auto entry = this->Get(BuildFirebaseKey(key, _uid));
// Check whether data was found, create new with fallback value, if necessary
int value = (!entry.value.empty() && entry.value.is_number_integer()) ? entry.value.get<int>() : fallback<int>();
// Apply function on the value
value = function(value);
// Put value in database
std::string ETag = entry.ETag;
std::string newETag = "";
int newValue = 0;
const int maxTrialCount = 10;
int trialCount = 0;
// Try as long as no success but still new ETags
do
{
// Try to put on database
newETag = "";
newValue = 0;
success = Put(key, ETag, value, newETag, newValue);
// If no new ETag provided, just quit this (either success or database just does not like us)
if (newETag.empty()) { break; }
// Store new values
ETag = newETag;
value = newValue;
// Transform retrieved value
value = function(value);
// Increase trial count
++trialCount;
} while (!success && trialCount <= maxTrialCount);
// Tell user about no success
if (!success)
{
LogError("FirebaseInterface: ", "Data transfer to Firebase failed.");
}
return value;
}
// #######################
// ### FIREBASE MAILER ###
// #######################
FirebaseMailer::FirebaseMailer()
{
// Create thread where FirebaseInterface lives in
auto* pMutex = &_commandMutex;
auto* pConditionVariable = &_conditionVariable;
auto* pCommandQueue = &_commandQueue;
auto* pIdToken = &_idToken;
auto* pStartIndex = &_startIndex;
auto const * pShouldStop = &_shouldStop; // read-only
_upThread = std::unique_ptr<std::thread>(new std::thread([pMutex, pConditionVariable, pCommandQueue, pIdToken, pStartIndex, pShouldStop]() // pass copies of pointers to members
{
// Create interface to firebase
FirebaseInterface interface(pIdToken, pStartIndex); // object of inner class
// Local command queue where command are moved from mailer thread to this thread
std::deque<std::shared_ptr<Command> > localCommandQueue;
// While loop to work on commands
while (!*pShouldStop) // exits when should stop, so thread can be joined
{
// Wait for data
{
std::unique_lock<std::mutex> lock(*pMutex); // acquire lock
pConditionVariable->wait(
lock, // lock that is handled by condition variable
[pCommandQueue, pShouldStop]
{
return !pCommandQueue->empty() || *pShouldStop; // condition is either there are some commands or it is called to stop and becomes joinable
}); // hand over locking to the conidition variable which waits for notification by main thread
localCommandQueue = std::move(*pCommandQueue); // move content of command queue to local one
pCommandQueue->clear(); // clear original queue
lock.unlock(); // do not trust the scope stuff. But should be not necessary
}
// Work on commands
for (const auto& rCommand : localCommandQueue)
{
(*rCommand.get())(interface);
}
}
// Collect last commands before shutdown
std::unique_lock<std::mutex> lock(*pMutex);
localCommandQueue = std::move(*pCommandQueue); // move content of command queue to local one
pCommandQueue->clear(); // clear original queue
// Work on these last commands
for (const auto& rCommand : localCommandQueue)
{
(*rCommand.get())(interface);
}
}));
}
bool FirebaseMailer::PushBack_Login(std::string email, std::string password, bool useDriftMap, std::promise<std::string>* pPromise)
{
// Add command to queue, take parameters as copy
return PushBackCommand(std::shared_ptr<Command>(new Command([=](FirebaseInterface& rInterface)
{
return rInterface.Login(email, password, useDriftMap, pPromise);
})));
}
bool FirebaseMailer::PushBack_Transform(FirebaseIntegerKey key, int delta, std::promise<int>* pPromise)
{
// Add command to queue, take parameters as copy
return PushBackCommand(std::shared_ptr<Command>(new Command([=](FirebaseInterface& rInterface)
{
rInterface.Transform(key, delta, pPromise);
})));
}
bool FirebaseMailer::PushBack_Maximum(FirebaseIntegerKey key, int value, std::promise<int>* pPromise)
{
// Add command to queue, take parameters as copy
return PushBackCommand(std::shared_ptr<Command>(new Command([=](FirebaseInterface& rInterface)
{
rInterface.Maximum(key, value, pPromise);
})));
}
bool FirebaseMailer::PushBack_Put(FirebaseIntegerKey key, int value, std::string subpath)
{
// Add command to queue, take parameters as copy
return PushBackCommand(std::shared_ptr<Command>(new Command([=](FirebaseInterface& rInterface)
{
rInterface.Put(key, value, subpath);
})));
}
bool FirebaseMailer::PushBack_Put(FirebaseStringKey key, std::string value, std::string subpath)
{
// Add command to queue, take parameters as copy
return PushBackCommand(std::shared_ptr<Command>(new Command([=](FirebaseInterface& rInterface)
{
rInterface.Put(key, value, subpath);
})));
}
bool FirebaseMailer::PushBack_Put(FirebaseJSONKey key, json value, std::string subpath)
{
// Add command to queue, take parameters as copy
return PushBackCommand(std::shared_ptr<Command>(new Command([=](FirebaseInterface& rInterface)
{
rInterface.Put(key, value, subpath);
})));
}
bool FirebaseMailer::PushBack_Get(FirebaseIntegerKey key, std::promise<int>* pPromise)
{
// Add command to queue, take parameters as copy
return PushBackCommand(std::shared_ptr<Command>(new Command([=](FirebaseInterface& rInterface)
{
rInterface.Get(key, pPromise);
})));
}
bool FirebaseMailer::PushBack_Get(FirebaseStringKey key, std::promise<std::string>* pPromise)
{
// Add command to queue, take parameters as copy
return PushBackCommand(std::shared_ptr<Command>(new Command([=](FirebaseInterface& rInterface)
{
rInterface.Get(key, pPromise);
})));
}
bool FirebaseMailer::PushBack_Get(FirebaseJSONKey key, std::promise<json>* pPromise)
{
// Add command to queue, take parameters as copy
return PushBackCommand(std::shared_ptr<Command>(new Command([=](FirebaseInterface& rInterface)
{
rInterface.Get(key, pPromise);
})));
}
bool FirebaseMailer::PushBackCommand(std::shared_ptr<Command> spCommand)
{
if (setup::FIREBASE_MAILING && !_paused) // only push back the command if logging activated and not paused
{
std::lock_guard<std::mutex> lock(_commandMutex);
_commandQueue.push_back(spCommand); // push back command to queue
_conditionVariable.notify_all(); // notify thread about new data
return true;
}
else
{
return false; // command was not added to the queue
}
}
std::string FirebaseMailer::GetIdToken() const
{
// Only read in FirebaseMailer, do not set!
return _idToken.Get();
}
int FirebaseMailer::GetStartIndex() const
{
return _startIndex;
} | [
"[email protected]"
]
| |
55f19bbf83f576db2d906b689dddb88db62aa8b4 | 34b722f3d89a1428975316a248cb2d58658ae2f2 | /util.h | c9f37d8e127cac633018a5269d7045ae5fa5de48 | []
| no_license | gaoyiyeah/autoencoder | 4bf896491d669be1f020bd521cad36fbd4acaf58 | 2dd3331f1668bdc8584a5642ee9b122c3782afe0 | refs/heads/master | 2020-04-25T21:13:13.800814 | 2015-04-22T02:57:00 | 2015-04-22T02:57:00 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,014 | h | #include <iostream>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <bitset>
#include <io.h>
#include "global.h"
class Util {
private:
static std::vector<std::string> allFiles;
static std::vector<std::vector<ItemType>> finger_database;
static int _LoadFingerFromOneFile(std::string filepath_prefix, unsigned int fileNum);
static int _OutputFingerToOneFile(std::string filepath_prefix, unsigned int fileNum);
public:
static int LoadOneFile(std::string filepath, std::vector<KeyType>& audio_fingers);
static std::vector<std::string> LoadDir(std::string dirpath, std::string type);
static void LoadDirSpecific(std::vector<std::vector<std::string>>& allQueryFiles, std::string dirpath, std::string type);
static int LoadIndex(std::string index_filepath, IndexType& index);
static int OutputIndex(std::string index_filepath, IndexType& index);
static int LoadFingerDatabase(std::string filepath_prefix);
static int OutputFingerToFile(std::string filepath_prefix);
static int DeleteSomeIndex(std::string index_filepath, std::set<int> remove_list);
static int DeleteSomeIndex(std::string index_filepath, std::string filepath);
static int DeleteFingerDatabase(std::string database_filepath, std::set<int> remove_list);
static int DeleteFingerDatabase(std::string database_filepath, std::string filepath);
static int IncrementalBuildIndex(std::string index_filepath, std::string dir_path);
static int IncrementalBuildFingerDatabase(std::string database_filepath, std::string dir_path);
static std::vector<ItemType> VectorKeyToVectorBitset(std::vector<KeyType> v);
static std::vector<KeyType> VectorBitsetToVectorKey(std::vector<ItemType> v);
//以上函数均测试通过
static int t_DeleteFingerDatabase(std::vector<std::vector<ItemType>>& finger_database, std::set<int> remove_list);
static int t_DeleteSomeIndex(IndexType& index, std::set<int> remove_list);
static int t_OutputFingerToFile(std::string filepath_prefix, std::vector<std::vector<ItemType>>& database);
}; | [
"[email protected]"
]
| |
4319d8baefdfd06e879e74e6626ec861653bba14 | f297dc35be06acc9ded03b6fa97ae8c58dcadf55 | /EditorPage.xaml.h | 0e70cf2238544d5a32621c85ad274f3339957999 | [
"MIT"
]
| permissive | yakcyll/ygc-dev | b8bee57c9a4422d137f619128d1e961e80bb0ebe | 36ce4702975c85c9e2c11f627140b3cdcf20f0f3 | refs/heads/master | 2021-01-19T15:04:06.061060 | 2014-11-24T21:28:45 | 2014-11-24T21:28:45 | 25,370,663 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,538 | h | //
// EditorPage.xaml.h
// Declaration of the EditorPage class
//
#pragma once
#include "BoardPage.h"
#include "EditorPage.g.h"
namespace ygc
{
public ref class EditorPage sealed
{
internal:
StackPanel ^ CounterPanel, ^ ToolPanel, ^ FilePanel, ^ BottomStack, ^ CPCount, ^CPInd, ^ TPMode, ^ TPHistory;
Grid ^ CPIndCont, ^ TPModeCont, ^ TPHistoryCont;
Border ^ CPCountBorder, ^CPIndBorder, ^ TPModeBorder, ^TPHistoryBorder;
Canvas ^ LayoutRoot;
ScrollViewer ^ BottomPanel;
Image ^ turnIndicator, ^ stoneBrush, ^ checkPoint, ^ clearBoard, ^ hRewind, ^ hPrev, ^ hNext, ^loadFile;
Array<TextBlock^>^ scoreTBs;
Array<uint16_t>^ playerScores;
uint16_t moveId, checkPointId, noPlayers;
ygcStoneColor ^ turn, ^ historyTurn;
bool historyModeEnabled;
bool mixedStonesEnabled;
BoardPage ^ bp;
void InitBoard();
void InitPanels();
void InitInputHandler();
void UpdateIcons();
void ClearBoard();
bool LoadBoard(Platform::String^);
void UpdateBoard(ygcMove ^, bool);
void RewindHistory(bool = false);
void FilePickerContinuationActivated(Windows::ApplicationModel::Core::CoreApplicationView ^s, Windows::ApplicationModel::Activation::IActivatedEventArgs ^e);
Windows::Foundation::EventRegistrationToken fpcert;
Windows::ApplicationModel::Activation::FileActivatedEventArgs^ fileEventArgs;
public:
EditorPage();
protected:
virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
void OrientHandler(Object ^ s, SizeChangedEventArgs ^ sce);
};
}
| [
"[email protected]"
]
| |
ee944f545e1909278bdffb776ad30d7314076d05 | 337f830cdc233ad239a5cc2f52c6562fbb671ea8 | /case5cells/6.1/polyMesh/cellZones | f1026a5764f38d94ff75fac8a4753121c2f07dea | []
| no_license | j-avdeev/laplacianFoamF | dba31d0941c061b2435532cdfbd5a5b337e6ffe9 | 6e1504dc84780dc86076145c18862f1882078da5 | refs/heads/master | 2021-06-25T23:52:36.435909 | 2017-02-05T17:28:45 | 2017-02-05T17:28:45 | 26,997,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 872 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class regIOobject;
location "6.1/polyMesh";
object cellZones;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
0
()
// ************************************************************************* //
| [
"[email protected]"
]
| ||
a826d7881e287a229bac52a8e9fe6e34987629ca | 00652caf4c8f04baa124d2f7afa8e941e1bdb58e | /paramics_traci-0.8-release/src/TraCIAPI/Subscriptions.h | c1b678718a89bf54c11cd3fa84d02c945141f5ba | [
"BSD-3-Clause"
]
| permissive | Rukua95/Paramics-Omnet | 17ea5ef10bbcf3eedd176e25da8169556771ee66 | 8da0192f0a0aa63c580eb83101f93a4cce082a0a | refs/heads/master | 2023-01-16T03:59:39.028847 | 2020-11-28T17:51:57 | 2020-11-28T17:51:57 | 259,680,174 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,343 | h | #pragma once
#include <vector>
#include "storage.h"
#include "Constants.h"
#include "VehicleManager.h"
#include "Exceptions.h"
#include "Simulation.h"
namespace traci_api
{
class VariableSubscription
{
public:
static const uint8_t RES_SUB_INDVAR = 0xe0;
static const uint8_t RES_SUB_MULTVAR = 0xe1;
static const uint8_t RES_SUB_TLIGHTVAR = 0xe2;
static const uint8_t RES_SUB_LANEVAR = 0xe3;
static const uint8_t RES_SUB_VHCVAR = 0xe4;
static const uint8_t RES_SUB_VHCTYPEVAR = 0xe5;
static const uint8_t RES_SUB_RTEVAR = 0xe6;
static const uint8_t RES_SUB_POIVAR = 0xe7;
static const uint8_t RES_SUB_POLVAR = 0xe8;
static const uint8_t RES_SUB_JUNCTVAR = 0xe9;
static const uint8_t RES_SUB_EDGEVAR = 0xea;
static const uint8_t RES_SUB_SIMVAR = 0xeb;
static const uint8_t STATUS_OK = 0x00;
static const uint8_t STATUS_TIMESTEPNOTREACHED = 0x01;
static const uint8_t STATUS_EXPIRED = 0x02;
static const uint8_t STATUS_ERROR = 0xff;
static const uint8_t STATUS_OBJNOTFOUND = 0xee;
//update statuses
static const uint8_t STATUS_NOUPD = 0xa0;
static const uint8_t STATUS_UNSUB = 0xa1;
VariableSubscription(std::string obj_id, int begin_time, int end_time, std::vector<uint8_t> vars) :
objID(obj_id),
beginTime(begin_time),
endTime(end_time),
vars(vars),
sub_type(-1)
{
}
int checkTime() const;
virtual ~VariableSubscription()
{
};
uint8_t handleSubscription(tcpip::Storage& output, bool validate, std::string& errors);
virtual void getObjectVariable(uint8_t var_id, tcpip::Storage& result) = 0;
uint8_t getSubType() const { return sub_type; }
virtual uint8_t getResponseCode() const = 0;
uint8_t updateSubscription(uint8_t sub_type, std::string obj_id, int begin_time, int end_time, std::vector<uint8_t> vars, tcpip::Storage& result, std::string& errors);
protected:
std::string objID;
int beginTime;
int endTime;
std::vector<uint8_t> vars;
int sub_type;
};
class VehicleVariableSubscription : public VariableSubscription
{
public:
VehicleVariableSubscription(std::string vhc_id, int begin_time, int end_time, std::vector<uint8_t> vars)
: VariableSubscription(vhc_id, begin_time, end_time, vars)
{
sub_type = CMD_SUB_VHCVAR;
}
~VehicleVariableSubscription() override
{
}
void getObjectVariable(uint8_t var_id, tcpip::Storage& result) override;
uint8_t getResponseCode() const override;
};
class SimulationVariableSubscription : public VariableSubscription
{
public:
SimulationVariableSubscription(std::string object_id, int begin_time, int end_time, const std::vector<uint8_t>& vars)
: VariableSubscription(object_id, begin_time, end_time, vars)
{
sub_type = CMD_SUB_SIMVAR;
}
~SimulationVariableSubscription() override
{
}
void getObjectVariable(uint8_t var_id, tcpip::Storage& result) override;
uint8_t getResponseCode() const override;
};
}
| [
"[email protected]"
]
| |
90dcdcc98d5cf9b2cf54db84221eb2e43be69725 | b466fa3833c7ef39ac6d169d9df75f39e4a3b258 | /src/p528/FindKForYpiAt99Percent.cpp | 0f514997a2ee546b98c715fc3753fc4de4022211 | [
"LicenseRef-scancode-warranty-disclaimer"
]
| no_license | NTIA/p528 | 8a1ad3aba6150fcf391134cb7c6742daef2e5619 | 93853a8a3e3923556971dfb872c8222d5a52b45a | refs/heads/master | 2023-05-23T05:16:47.486813 | 2022-01-27T15:34:09 | 2022-01-27T15:34:09 | 174,558,606 | 15 | 11 | NOASSERTION | 2022-06-02T19:15:01 | 2019-03-08T15:10:32 | C++ | UTF-8 | C++ | false | false | 1,254 | cpp | #include "../../include/p528.h"
/*=============================================================================
|
| Description: This function returns the K-value of the Nakagami-Rice
| distribution for the given value of Y_pi(99)
|
| Input: Y_pi_99__db - Y_pi(99), in dB
|
| Returns: K - K-value
|
*===========================================================================*/
double FindKForYpiAt99Percent(double Y_pi_99__db)
{
// is Y_pi_99__db smaller than the smallest value in the distribution data
if (Y_pi_99__db < data::NakagamiRiceCurves.front()[Y_pi_99_INDEX])
return data::K.front();
// search the distribution data and interpolate to find K (dependent variable)
for (int i = 0; i < data::K.size(); i++)
if (Y_pi_99__db - data::NakagamiRiceCurves[i][Y_pi_99_INDEX] < 0)
return (data::K[i] * (Y_pi_99__db - data::NakagamiRiceCurves[i - 1][Y_pi_99_INDEX]) - data::K[i - 1] * (Y_pi_99__db - data::NakagamiRiceCurves[i][Y_pi_99_INDEX])) / (data::NakagamiRiceCurves[i][Y_pi_99_INDEX] - data::NakagamiRiceCurves[i - 1][Y_pi_99_INDEX]);
// no match. Y_pi_99__db is greater than the data contains. Return largest K
return data::K.back();
} | [
"[email protected]"
]
| |
79b3536f5401464d9d012979b19dfdcf8a8fea73 | 19407b960c6fe8fdc8fa59a0133fed9a73f5a66e | /src/vm/jvm_defines.h | fb5400649d44d16e07771b59cbeef135beaf9b7d | []
| no_license | slavam2605/BadVM | 0b5344c66773aa45de44c2a3c7ce00f9e491dced | 9260d0df86326fa86cef702b5177423926e5b0e4 | refs/heads/master | 2023-04-08T15:58:38.428112 | 2021-04-21T07:41:57 | 2021-04-21T07:41:57 | 351,406,223 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 350 | h | #ifndef BADJVM_JVM_DEFINES_H
#define BADJVM_JVM_DEFINES_H
#include <cstdint>
using jvm_reference = uint8_t*;
using jvm_boolean = bool;
using jvm_byte = int8_t;
using jvm_short = int16_t;
using jvm_char = uint16_t;
using jvm_int = int32_t;
using jvm_long = int64_t;
using jvm_float = float;
using jvm_double = double;
#endif //BADJVM_JVM_DEFINES_H
| [
"[email protected]"
]
| |
1963ee736e46305ec3051ceafcc689151f90c4bf | 566314a9814d13826bfb21de1ef174ee7351d06d | /OOP3/OOP3/Polygon.h | d53d15f13162880b361502a0b19ffc013fcbd819 | [
"MIT"
]
| permissive | Tomer20/Homework | a7bddbe6a213befc79c562b7db6fd6eb4e6c957e | 169e7b1bfc9240b2ec52a075af9a42151ae2c24e | refs/heads/master | 2022-11-07T21:47:30.771014 | 2018-02-05T11:51:45 | 2018-02-05T11:51:45 | 116,182,321 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 747 | h | //
// Assigned by:
//
// File Name: Polygon.h
// Files in project: TEST.cpp, Circle.cpp, Circle.h, Point.cpp,
// Point.h, Polygon.cpp, Polygon.h, Rectangle.cpp,
// Rectangle.h, Shape.h, Triangle.cpp, Triangle.h
//
#ifndef Polygon_h
#define Polygon_h
#include "Shape.h"
#include "Point.h"
// Abstract class that inherits from "Shape" class.
class Polygon : public Shape {
public:
~Polygon(); // Destructor for the "Point *point_array"
int getNumOfPoints() const;
double getPerim() const;
protected:
int num_of_points; // This variable is defined according to shape's size
Point *point_array; // Array to store all shape's points
};
#endif /* Polygon_h */
| [
"[email protected]"
]
| |
3bf1bad2a0faf2ff59be78d13cadc7b69d672d00 | 89df1ea7703a7d64ed2549027353b9f98b800e88 | /minecraft/minecraft/src/engine/data/time_data.h | 5cfe51e1eec8bfb82bbd03af3a06ed3cc7ab4cc4 | [
"MIT"
]
| permissive | llGuy/gamedev | 31a3e23f921fbe38af48177710eb7bae661f4cfd | 16aa203934fd767926c58558e021630288556399 | refs/heads/master | 2021-05-04T15:09:33.217825 | 2019-01-17T23:15:36 | 2019-01-17T23:15:36 | 120,221,445 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 410 | h | #ifndef TIME_DATA_HEADER
#define TIME_DATA_HEADER
#include <chrono>
namespace minecraft
{
namespace data
{
struct Time
{
std::chrono::time_point<std::chrono::high_resolution_clock> beginning;
std::chrono::time_point<std::chrono::high_resolution_clock> currentTime;
std::chrono::time_point<std::chrono::high_resolution_clock> previousTime;
double deltaT;
};
}
}
#endif | [
"[email protected]"
]
| |
842783a9782cfa5d4f10a9b8c9d8c08e8866c826 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/windows/advcore/gdiplus/test/functest/creadwrite.h | e1cccadd5aa985ac89b5a90e1f5f40d99f6361b2 | []
| no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 690 | h | /******************************Module*Header*******************************\
* Module Name: CReadWrite.h
*
* This file contains the code to support the functionality test harness
* for GDI+. This includes menu options and calling the appropriate
* functions for execution.
*
* Created: 05-May-2000 - Jeff Vezina [t-jfvez]
*
* Copyright (c) 2000 Microsoft Corporation
*
\**************************************************************************/
#ifndef __CREADWRITE_H
#define __CREADWRITE_H
#include "CPrimitive.h"
class CReadWrite : public CPrimitive
{
public:
CReadWrite(BOOL bRegression);
virtual ~CReadWrite();
void Draw(Graphics *g);
};
#endif
| [
"[email protected]"
]
| |
41bbc3f7b64edcee4b8a633ddbe1069f370239b7 | 6e4fd6be0921adfa1ec08d2e92acec312d42b793 | /src/h/register.h | 337c881ee1445609d8b17dab2f59594ebf9db4ac | []
| no_license | DraganVeljovic/GAssembler | a6e440c13f2bc3b4f125f6a15ef63e2017331d27 | a17b021f4f869b7a652bec98f0a4046c6f2a7248 | refs/heads/master | 2020-08-05T16:52:55.572797 | 2016-09-07T23:16:28 | 2016-09-07T23:16:28 | 67,649,807 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281 | h | #ifndef REGISTER_H
#define REGISTER_H
class Register {
private:
char* name;
char* nameUC;
int index;
public:
Register();
Register(char* name, char* nameUC);
~Register();
char* getName();
char* getNameUC();
void setName(char*);
void setNameUC(char*);
};
#endif
| [
"[email protected]"
]
| |
3e03352b6693360a76457b1b56cbc1322a513777 | fa73ad7a78238f8050d20f196805f729d0333919 | /src/Parser/Nodes/JoinNodes/RightJoinNode.h | a10b2bb4e0bdc31f14fd45bc57d0195c73bca7ca | []
| no_license | quiksilver4210/SelSQL | 3c9494fe331579d74dec07b7d1bf04595af12bb7 | f4593ee2ccea54b7ba0221ee74b8ad9af38b29ed | refs/heads/master | 2021-10-27T01:28:19.477068 | 2021-10-15T11:59:01 | 2021-10-15T11:59:01 | 210,825,355 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 285 | h | //
// Created by sapiest on 07.11.2019.
//
#ifndef SELSQL_RIGHTJOINNODE_H
#define SELSQL_RIGHTJOINNODE_H
#include "BaseJoinNode.h"
class RightJoinNode : public BaseJoinNode {
public:
void accept(TreeVisitor* v) override { v->visit(this); }
};
#endif // SELSQL_RIGHTJOINNODE_H
| [
"[email protected]"
]
| |
6b1fc8d9e9e18b952e0c566aa531328f2c7f445e | 7f81952c20254ef5b4463615afdc53fbaf4e2885 | /main.h | b58573dd4b7285ef6e254e27b6391f486e07651d | [
"MIT"
]
| permissive | pratinav/2048 | 40b6d06d98bf8562d8abdb0aa1804d04380af119 | dd279eb344267ff77db63b8ac8e886d8a8ff893b | refs/heads/master | 2021-01-02T08:37:50.537510 | 2017-09-10T11:30:10 | 2017-09-10T11:30:10 | 99,034,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 572 | h | /**
* Final Project
* author: Pratinav Bagla
*
* main.h
*
* main.h and main.cpp build an interface and other features such as
* a scoring system and a menu around the main board class
*/
#pragma once
#include <iostream>
#include <fstream>
#include <vector>
#include "board.h"
using namespace std;
void displayMenu();
void displayScores();
void play();
void play(board *b);
void loadScores();
bool saveGame(board *b);
void loadGame();
void bubbleSort(vector<int> &v);
int getIndex(string s, const string ARR[], const int ARR_LEN);
void pushNewScore(int newScore); | [
"[email protected]"
]
| |
17c5ede9f5eaf64104edd421cb38ee0f81ee0108 | 561392a4f8a3ea16602368c7a8a13f6d26520a43 | /src/HihoCoderProblem/MergeKSortedLists.cpp | 604d87c2f8629faab25b4e128b8e0646c23645ca | []
| no_license | suntaopku/DataStruct | d576df8c775b7934dbd6e9c99a553d832ead2910 | 66486c0880cf65ff5f4d84ffcb4543346de6df5b | refs/heads/master | 2021-01-18T14:44:02.909348 | 2016-01-20T13:02:03 | 2016-01-20T13:02:03 | 50,030,100 | 0 | 0 | null | 2016-01-20T12:56:48 | 2016-01-20T12:56:47 | null | UTF-8 | C++ | false | false | 2,124 | cpp | #include "MergeKSortedLists.h"
MergeKSortedLists::MergeKSortedLists(void)
{
}
MergeKSortedLists::~MergeKSortedLists(void)
{
}
ListNode* MergeKSortedLists::mergeKLists(vector<ListNode*>& lists)
{
ListNode **p,*head,*s;
int Len=lists.size();
if (Len==0){
return NULL;
}
int i,j;//flag is the status of all zeros
p=new ListNode *[Len];
for (i=0;i<Len;i++)
{
p[i]=lists[i];
}
head=NULL;s=NULL;
while(1)
{
int minv=10000000,pos=-1;
for (i=0;i<Len;i++)
{
if (p[i]==NULL)
{
continue;
}
else if (pos==-1)
{
minv=p[i]->val;
pos=i;
}
else if (p[i]->val<minv)
{
minv=p[i]->val;
pos=i;
}
}
if (pos==-1)
{
if (s!=NULL)
{
s->next=NULL;
}
break;
}
if (s==NULL)
{
s=p[pos];
head=s;
}
else
{
s->next=p[pos];
s=s->next;
}
p[pos]=p[pos]->next;
}
/*while(1)
{
int minv=10000000,pos=-1;
for (i=0;i<Len;i++)
{
if (lists[i]==NULL)
{
continue;
}
else if (pos==-1)
{
minv=lists[i]->val;
pos=i;
}
else if (lists[i]->val<minv)
{
minv=lists[i]->val;
pos=i;
}
}
if (pos==-1)
{
if (s!=NULL)
{
s->next=NULL;
}
break;
}
if (s==NULL)
{
s=lists[pos];
head=s;
}
else
{
s->next=lists[pos];
s=s->next;
}
lists[pos]=lists[pos]->next;
}*/
return head;
}
void MergeKSortedLists::TestClass()
{
ListNode *l1=NULL;
ListNode *l2=NULL;
l1=(ListNode*)malloc(sizeof(ListNode));
l2=(ListNode*)malloc(sizeof(ListNode));
int A1[3]={2,4,9};
int A2[3]={5,6,4};
l1->val=A1[0];
l2->val=A2[0];
l1->next=NULL;
l2->next=NULL;
ListNode *p,*q;
p=l1;q=l2;
for (int i=1;i<3;i++)
{
ListNode *res;
res=(ListNode*)malloc(sizeof(ListNode));
res->val=A1[i];
res->next=NULL;
p->next=res;
p=p->next;
}
for(int i=1;i<2;i++)
{
ListNode *res2;
res2=(ListNode*)malloc(sizeof(ListNode));
res2->val=A2[i];
res2->next=NULL;
q->next=res2;
q=q->next;
}
vector<ListNode*> lists(2);
lists[0]=l1;
lists[1]=l2;
ListNode *res=mergeKLists(lists);
p=res;
while(p!=NULL)
{
cout<<p->val<<endl;
p=p->next;
}
} | [
"[email protected]"
]
| |
eaeb8507e6cf346acb5e49ec0ed94a6290cb3495 | b3239097cad0e28dfce355fa1e6f5a6fd12c10f4 | /773D.cpp | 60c89adebf18bd4b4bdee63556665a84e58792f9 | []
| no_license | trinhtanphat/Codeforces | da52d4efae03fa8f20564a3062cf7fde8ff3224d | c52cd4749f1c1dd38a0f0140250e6d8e96181037 | refs/heads/master | 2023-04-12T11:34:04.121808 | 2018-11-10T19:36:01 | 2018-11-10T19:36:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,035 | cpp | #include <bits/stdc++.h>
using namespace std;
#define openfile {freopen("input.txt","r",stdin);}
#define debug 01
#define mp make_pair
const int MAX_N = 1e5;
int n, cnt, a[MAX_N][3];
map<pair<int,int>,int> mmap;
int mmax[2][3*MAX_N], mpos[2][3*MAX_N];
void exec(int idx, int x, int y, int z) {
pair<int, int> p = mp(a[idx][x],a[idx][y]);
if (mmap.find(p) == mmap.end()) {
mmap[p] = cnt;
mmax[0][cnt] = mmax[1][cnt] = -1;
mpos[0][cnt] = mpos[1][cnt] = -1;
cnt++;
}
int e = mmap[p];
if (mmax[0][e] < a[idx][z]) {
mmax[1][e] = mmax[0][e];
mpos[1][e] = mpos[0][e];
mmax[0][e] = a[idx][z];
mpos[0][e] = idx;
}
else if (mmax[1][e] < a[idx][z] && mpos[0][e] != idx) {
mmax[1][e] = a[idx][z];
mpos[1][e] = idx;
}
}
void findMax() {
int num = 0;
int res = 0;
int pos[2] = {-1, -1};
for (map<pair<int,int>,int>::iterator it=mmap.begin(); it!=mmap.end(); it++) {
int p = it->second;
// cout<<p<<endl;
int x = mpos[0][p], y = mpos[1][p];
if (y==-1) {
int u = min(a[x][0], min(a[x][1], a[x][2]));
if (u > res) {
res = u;
pos[0] = x;
num = 1;
}
}
else {
pair<int, int> val = it->first;
int u = min(val.first, min(val.second, mmax[0][p]+mmax[1][p]));
if (u > res) {
res = u;
pos[0] = x, pos[1] = y;
num = 2;
}
}
}
cout<<num<<endl;
for (int i=0; i<num; i++) {
cout<<pos[i]+1<<' ';
}
}
void solve() {
cnt=0;
for (int i=0; i<n; i++) {
sort(a[i],a[i]+3);
exec(i, 0, 1, 2);
exec(i, 0, 2, 1);
exec(i, 1, 2, 0);
}
findMax();
}
int main() {
if (debug) openfile;
cin>>n;
for (int i=0; i<n; i++) {
for (int j=0; j<3; j++) {
cin>>a[i][j];
}
}
solve();
return 0;
}
| [
"[email protected]"
]
| |
30615964214530630c80e7248c1511c15fa319f4 | 43d6d73e5b57e9bdab7cb0762f8ea76af30bfed2 | /code/engine/xrGame/base_client_classes_wrappers.h | 13704a5e3e079b4a08ff28c5024f015e9acabbab | [
"Apache-2.0"
]
| permissive | xIRaYIx-zz/xray-162 | eff2186b811e710214fbc79c4e075d59e8356171 | fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e | refs/heads/master | 2022-04-08T10:30:15.774896 | 2018-02-26T05:53:57 | 2018-02-26T05:53:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,937 | h | ////////////////////////////////////////////////////////////////////////////
// Module : base_client_classes_wrappers.h
// Created : 20.12.2004
// Modified : 20.12.2004
// Author : Dmitriy Iassenev
// Description : XRay base client classes wrappers
////////////////////////////////////////////////////////////////////////////
#pragma once
#include "script_export_space.h"
#include "base_client_classes.h"
#include "../xrEngine/engineapi.h"
#include "../xrcdb/ispatial.h"
#include "../xrEngine/isheduled.h"
#include "../xrEngine/irenderable.h"
#include "../xrEngine/icollidable.h"
#include "../xrEngine/xr_object.h"
#include "entity.h"
#include "ai_space.h"
#include "script_engine.h"
#include "xrServer_Object_Base.h"
template <typename Base, typename... Ts>
class DLL_PureWrapper : public Base, public Ts... {
public:
DLL_PureWrapper() = default;
virtual ~DLL_PureWrapper() = default;
DLL_Pure* _construct() override { return (call_member<DLL_Pure*>(this, "_construct")); }
static DLL_Pure* _construct_static(Base* self) { return (self->Base::_construct()); }
};
using CDLL_PureWrapper = DLL_PureWrapper<DLL_Pure, luabind::wrap_base>;
/*
template <typename base, typename... Ts>
class ISpatialWrapper : public base, public luabind_base {
public:
IC ISpatialWrapper () {};
virtual ~ISpatialWrapper () {};
virtual void spatial_register ()
{
call_member<void>(this,"spatial_register");
}
static void spatial_register_static (base *self)
{
self->base::spatial_register();
}
virtual void spatial_unregister ()
{
call_member<void>(this,"spatial_unregister");
}
static void spatial_unregister_static (base *self)
{
self->base::spatial_unregister();
}
virtual void spatial_move ()
{
call_member<void>(this,"spatial_move");
}
static void spatial_move_static (base *self)
{
self->base::spatial_move();
}
virtual Fvector spatial_sector_point ()
{
return (call_member<Fvector>(this,"spatial_sector_point"));
}
static Fvector spatial_sector_point_static (base *self)
{
return (self->base::spatial_sector_point());
}
virtual CObject* dcast_CObject ()
{
return (call_member<CObject*>(this,"dcast_CObject"));
}
static CObject* dcast_CObject_static (base *self)
{
return (self->base::dcast_CObject());
}
virtual Feel::Sound* dcast_FeelSound ()
{
return (call_member<Feel::Sound*>(this,"dcast_FeelSound"));
}
static Feel::Sound* dcast_FeelSound_static (base *self)
{
return (self->base::dcast_FeelSound());
}
virtual IRenderable* dcast_Renderable ()
{
return (call_member<IRenderable*>(this,"dcast_Renderable"));
}
static IRenderable* dcast_Renderable_static (base *self)
{
return (self->base::dcast_Renderable());
}
};
typedef ISpatialWrapper<ISpatial,luabind::wrap_base> CISpatialWrapper;
*/
template <typename Base, typename... Ts>
class ISheduledWrapper : public Base, public Ts... {
public:
ISheduledWrapper() = default;
virtual ~ISheduledWrapper() = default;
float shedule_Scale() override {
return 1;
// return (call_member<float>(this,"shedule_Scale"));
}
/* static float shedule_Scale_static (base *self)
{
ai().script_engine().script_log(eLuaMessageTypeError,"You are trying to call a
pure virtual function ISheduled::shedule_Scale!\nReturning default value 1000.0"); return
(1000.f);
}
*/
void shedule_Update(u32 dt) override {
Base::shedule_Update(dt);
// call_member<void>(this,"shedule_Update");
}
/* static void shedule_Update_static (base *self, u32 dt)
{
self->base::shedule_Update(dt);
}
*/
};
using CISheduledWrapper = ISheduledWrapper<ISheduled, luabind::wrap_base>;
template <typename Base, typename... Ts>
class IRenderableWrapper : public Base, public Ts... {
public:
IRenderableWrapper() = default;
virtual ~IRenderableWrapper() = default;
/*
virtual void renderable_Render ()
{
call_member<void>(this,"renderable_Render");
}
static void renderable_Render_static (IRenderable *self)
{
ai().script_engine().script_log(eLuaMessageTypeError,"You are trying to call a
pure virtual function IRenderable::renderable_Render!");
}
virtual BOOL renderable_ShadowGenerate ()
{
return ((BOOL)call_member<bool>(this,"renderable_ShadowGenerate"));
}
static bool renderable_ShadowGenerate_static(IRenderable *self)
{
return (!! self->IRenderable::renderable_ShadowGenerate());
}
virtual BOOL renderable_ShadowReceive ()
{
return ((BOOL)call_member<bool>(this,"renderable_ShadowReceive"));
}
static bool renderable_ShadowReceive_static (IRenderable *self)
{
return (!! self->IRenderable::renderable_ShadowReceive());
}
*/
};
using CIRenderableWrapper = IRenderableWrapper<IRenderable, luabind::wrap_base>;
// typedef DLL_PureWrapper<CObject,luabind::wrap_base> CObjectDLL_Pure;
// typedef ISpatialWrapper<CObjectDLL_Pure> CObjectISpatial;
// typedef ISheduledWrapper<CObjectDLL_Pure> CObjectISheduled;
// typedef IRenderableWrapper<CObjectISheduled> CObjectIRenderable;
// class CObjectWrapper : public CObjectIRenderable {
// public:
// IC CObjectWrapper () {};
// virtual ~CObjectWrapper () {};
///**
// virtual BOOL Ready ();
// virtual CObject* H_SetParent (CObject* O);
// virtual void Center (Fvector& C) const;
// virtual float Radius () const;
// virtual const Fbox& BoundingBox () const;
// virtual void Load (LPCSTR section);
// virtual void UpdateCL ();
// virtual BOOL net_Spawn (CSE_Abstract* data);
// virtual void net_Destroy ();
// virtual void net_Export (NET_Packet& P);
// virtual void net_Import (NET_Packet& P);
// virtual void net_ImportInput (NET_Packet& P);
// virtual BOOL net_Relevant ();
// virtual void net_MigrateInactive (NET_Packet& P);
// virtual void net_MigrateActive (NET_Packet& P);
// virtual void net_Relcase (CObject* O);
// virtual SavedPosition ps_Element (u32 ID) const;
// virtual void ForceTransform (const Fmatrix& m);
// virtual void OnHUDDraw (CCustomHUD* hud);
// virtual void OnH_B_Chield ();
// virtual void OnH_B_Independent (bool just_before_destroy);
// virtual void OnH_A_Chield ();
// virtual void OnH_A_Independent ();
///**/
//};
using CGameObjectDLL_Pure = DLL_PureWrapper<CGameObject, luabind::wrap_base>;
// typedef ISpatialWrapper<CGameObjectDLL_Pure> CGameObjectISpatial;
using CGameObjectISheduled = ISheduledWrapper<CGameObjectDLL_Pure>;
using CGameObjectIRenderable = IRenderableWrapper<CGameObjectISheduled>;
class CGameObjectWrapper : public CGameObjectIRenderable {
public:
CGameObjectWrapper() = default;
virtual ~CGameObjectWrapper() = default;
virtual bool use(CGameObject* who_use) { return call<bool>("use", who_use); }
static bool use_static(CGameObject* self, CGameObject* who_use) {
return self->CGameObject::use(who_use);
}
virtual void net_Import(NET_Packet& packet) { call<void>("net_Import", &packet); }
static void net_Import_static(CGameObject* self, NET_Packet* packet) {
self->CGameObject::net_Import(*packet);
}
virtual void net_Export(NET_Packet& packet) { call<void>("net_Export", &packet); }
static void net_Export_static(CGameObject* self, NET_Packet* packet) {
self->CGameObject::net_Export(*packet);
}
virtual BOOL net_Spawn(CSE_Abstract* data) {
return (luabind::call_member<bool>(this, "net_Spawn", data));
}
static bool net_Spawn_static(CGameObject* self, CSE_Abstract* abstract) {
return (!!self->CGameObject::net_Spawn(abstract));
}
};
class CEntityWrapper : public CEntity, public luabind::wrap_base {
public:
CEntityWrapper() = default;
virtual ~CEntityWrapper() = default;
virtual void HitSignal(float P, Fvector& local_dir, CObject* who, s16 element) {
luabind::call_member<void>(this, "HitSignal", P, local_dir, who, element);
}
static void HitSignal_static(CEntity* self, float P, Fvector& local_dir, CObject* who,
s16 element) {
ai().script_engine().script_log(
eLuaMessageTypeError,
"You are trying to call a pure virtual function CEntity::HitSignal!");
}
virtual void HitImpulse(float P, Fvector& vWorldDir, Fvector& vLocalDir) {
luabind::call_member<void>(this, "HitImpulse", P, vWorldDir, vLocalDir);
}
static void HitImpulse_static(float P, Fvector& vWorldDir, Fvector& vLocalDir) {
ai().script_engine().script_log(
eLuaMessageTypeError,
"You are trying to call a pure virtual function CEntity::HitImpulse!");
}
};
| [
"[email protected]"
]
| |
a49bb6fa4fc27f8a3f3554ca67cdc2912fa42880 | f679bf935a00fad933fb6237ed486456b907d480 | /fat32-x86/dir32.cc | cdb99320c81bb405db34ee02e7075b2b7868ac0f | []
| no_license | LimeProgramming/rpi | da3b278578eae27c97bc70929be697fe2694fd9d | 9bed84eeb518a0348ddefe1acaa403ccc490212e | refs/heads/master | 2023-09-05T16:52:48.764546 | 2021-11-10T16:04:32 | 2021-11-10T16:04:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 132 | cc | /* dump the partition table
*/
#include "fat32.h"
int main()
{
fat32_init();
fat32_list_root();
fat32_deinit();
return 0;
}
| [
"[email protected]"
]
| |
903781cb84e395a63271e6196969c36fe3fcafb2 | 46fe0f55257e00fe75c3a1ebfc72c011735ca8f0 | /src/Util/ObjectsConnector.cpp | 9faeb1f1f9a53ee3e749bed676aa6b4e63c2a16c | []
| no_license | Stepdan/ImageKit | 45b26c85145b2d8ffc06b398ce04245b8a4152f2 | 44ffe1f93d0493432b1e5e2d17f3ca7c08850a63 | refs/heads/master | 2020-06-07T14:12:04.566877 | 2019-06-25T10:40:17 | 2019-06-25T10:40:17 | 193,039,325 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,489 | cpp | #include "ObjectsConnector.h"
#include <cassert>
namespace ImageKit::Util {
static const std::string TYPE_SIGNAL = "TYPE_SIGNAL";
static const std::string TYPE_SLOT = "TYPE_SLOT";
ObjectsConnector::MetaObjectsMap ObjectsConnector::m_metaCollector = ObjectsConnector::MetaObjectsMap();
//.............................................................................
ObjectsConnector::ObjectsConnector(QObject *parent/* = 0*/) :
QObject(parent)
{
}
//.............................................................................
void ObjectsConnector::registerEmitter(const QString &ID, QObject *sender, const QString &signal, bool queued/* = false*/)
{
const std::string signal_str = signal.startsWith('2') ? signal.toStdString() : QString("2"+signal).toStdString();
for (const auto & record : m_metaCollector[ID][TYPE_SLOT])
{
if (sender != record.first)
{
const auto result = connect(sender, signal_str.c_str(), record.first, record.second.c_str(), queued ? static_cast<Qt::ConnectionType>(Qt::QueuedConnection | Qt::UniqueConnection) : Qt::UniqueConnection);
assert(result && "bad emitter");
}
}
registerMetaType(ID, TYPE_SIGNAL, std::make_pair(sender, signal_str));
}
//.............................................................................
void ObjectsConnector::registerReceiver(const QString &ID, QObject *receiver, const QString &slot, bool queued/* = false*/)
{
const std::string slot_str = slot.startsWith('1') ? slot.toStdString() : QString("1"+slot).toStdString();
for (const auto & record : m_metaCollector[ID][TYPE_SIGNAL])
{
if (receiver != record.first)
{
const auto result = connect(record.first, record.second.c_str(), receiver, slot_str.c_str(), queued ? static_cast<Qt::ConnectionType>(Qt::QueuedConnection | Qt::UniqueConnection) : Qt::UniqueConnection);
assert(result && "bad receiver");
}
}
registerMetaType(ID, TYPE_SLOT, std::make_pair(receiver, slot_str));
}
//.............................................................................
void ObjectsConnector::unregisterReceiver(const QString &ID, QObject *receiver, const QString &slot)
{
const std::string slot_str = slot.startsWith('1') ? slot.toStdString() : QString("1"+slot).toStdString();
for (const auto & record : m_metaCollector[ID][TYPE_SIGNAL])
{
if (receiver != record.first)
disconnect(record.first, record.second.c_str(), receiver, slot_str.c_str());
}
m_metaCollector[ID][TYPE_SLOT].remove(std::make_pair(receiver, slot_str));
}
//.............................................................................
void ObjectsConnector::unregisterEmitter(const QString &ID, QObject *sender, const QString &signal)
{
const std::string signal_str = signal.startsWith('2') ? signal.toStdString() : QString("2"+signal).toStdString();
for (const auto & record : m_metaCollector[ID][TYPE_SLOT])
{
if (sender != record.first)
disconnect(sender, signal_str.c_str(), record.first, record.second.c_str());
}
m_metaCollector[ID][TYPE_SIGNAL].remove(std::make_pair(sender, signal_str));
}
//.............................................................................
void ObjectsConnector::registerMetaType(const QString &ID, const std::string &metaType, const std::pair<const QObject*, const std::string> &metaPair)
{
m_metaCollector[ID][metaType].insert(m_metaCollector[ID][metaType].end(), metaPair );
connect(metaPair.first, &QObject::destroyed, [=]()
{
m_metaCollector[ID][metaType].remove(metaPair);
});
}
}
| [
"[email protected]"
]
| |
e520d546d4b2d2fb2c814413d9b5efd5e4541276 | 82c147779dfb0ddd4e539159c902d25487f8790f | /ABC/ABC071-080/ABC075/D/D.cpp | 4965d1d0551a33b0317d3c87ba3496b6f3a25870 | []
| no_license | nayuta1019/AtCoder | 4350e17ef21baf6015cbcf5a6d6ece8c5bbe767b | a1d8d85885e75dc103f185adfabd5354d0a69a6c | refs/heads/master | 2023-03-09T02:15:42.219174 | 2021-02-16T07:18:57 | 2021-02-16T07:18:57 | 339,315,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,050 | cpp | /**
ABC075
2019/01/25/ 未完成
**/
#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i = (a); i < (b); ++i)
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(),(x).end()
inline int toInt(string s) {int v; istringstream sin(s);sin>>v; return v;}
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector< vector<int> > Mat;
typedef tuple<int, int, int, int> T;
const int MOD = (int)1e9+7;
const int INF = (int)1e9;
const int dx[] = {0, 1, 0, -1};
const int dy[] = {1, 0, -1, 0};
const int ddx[] = {0, 1, 1, 1, 0, -1, -1, -1};
const int ddy[] = {1, 1, 0, -1, -1, -1, 0, 1};
struct point{
long long int x;
long long int y;
};
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int N, K;
cin >> N >> K;
vector<point> v(N);
rep(i, N) cin >> v[i].x >> v[i].y;
ll ans = 9e18;
for(int i = 0; i < N; i++){
for(int j = i+1; j < N; j++){
point p1, p2;
p1.x = v[i].x; p1.y = v[i].y;
p2.x = v[j].x; p2.y = v[j].y;
int cnt = 0;
for(int k = 0; k < N; k++){
if( min(p1.x, p2.x) <= v[k].x && v[k].x <= max(p1.x, p2.x) ){
cnt++;
}
if(K <= cnt){
if( min(p1.y, p2.y) <= v[k].y && v[k].y <= max(p1.y, p2.y) ){
ll area = abs(p1.x - p2.x) * abs(p1.y - p2.y);
ans = min(ans, area);
}else{
int y1, y2;
y1 = max({p1.y, p2.y, v[k].y});
y2 = min({p1.y, p2.y, v[k].y});
ll area = abs(p1.x - p2.x) * abs(y1 - y2);
ans = min(ans, area);
cnt--;
}
}
}
}
}
cout << ans << endl;
return 0;
} | [
"[email protected]"
]
| |
f9b7048e676543c10e3d9a7961da5ee6782a625d | 45aa6c77337e06f8ca8cd570a90d4542b3d63521 | /ThirdParty/cpgf/test/metagen/include/chainedobjectaccess.h | 9663ac5450bd2e29560d957ac7b0e95dd317d632 | [
"Apache-2.0"
]
| permissive | iteratif/uifaces | b6fcf4a023f41ee92c6cba0f06090cd967742031 | 2db85273282a52af09ced7f8ca50baff600dc31c | refs/heads/master | 2021-07-01T05:15:11.858215 | 2017-09-13T23:32:17 | 2017-09-13T23:32:17 | 103,461,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,384 | h | /*
cpgf Library
Copyright (C) 2011 - 2013 Wang Qi http://www.cpgf.org/
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __CHAINEDOBJECTACCESS_H
#define __CHAINEDOBJECTACCESS_H
class ChainedObjectA
{
public:
ChainedObjectA() : a(1) {}
virtual ~ChainedObjectA() {}
int getA() const { return this->doGetA(); }
protected:
virtual int doGetA() const { return this->a; }
private:
int a;
};
class ChainedObjectB
{
public:
ChainedObjectB() {}
virtual ~ChainedObjectB() {}
ChainedObjectA & getA() { return this->a; }
const ChainedObjectA & getConstA() const { return this->a; }
private:
ChainedObjectA a;
};
class ChainedObjectC
{
public:
ChainedObjectC() {}
virtual ~ChainedObjectC() {}
ChainedObjectB & getB() { return this->b; }
const ChainedObjectB & getConstB() const { return this->b; }
private:
ChainedObjectB b;
};
#endif
| [
"[email protected]"
]
| |
8a4cb40c6f8d79b53a0ea383a2a6724fac084c30 | a54d505c359afac37084c1bde71521fe0ca86f1b | /src/pointPlayer.h | 23c7743b668eb14870a225421f4b16d708d6ad5b | []
| no_license | kritzikratzi/soundythingie | e4af2cae455d745fd0a6c83309cdd22f094489ae | a630e03c941f8f94aec86997d50807016565b044 | refs/heads/master | 2021-01-19T20:12:59.757958 | 2020-10-02T14:50:49 | 2020-10-02T14:50:49 | 433,833 | 5 | 3 | null | 2020-10-02T14:50:50 | 2009-12-13T17:52:14 | C++ | UTF-8 | C++ | false | false | 1,365 | h | #ifndef __PEEPEE
#define __PEEPEE
#include "pointRecorder.h"
#include "Tones.h"
#include "Helpers.h"
// shape functions
float shapeFlat( float t );
float shapeSinus( float t );
float shapeSawtooth( float t );
float shapeRectangle( float t );
class pointRecorder;
class pointPlayer{
public:
pointPlayer();
void setup( pointRecorder * pr );
void draw();
void update();
void audioRequested(float * output, int bufferSize, int nChannels, bool useEnvelope);
void doCrazyMath( bool apply );
int triggerRate;
pointRecorder * pr;
//------------------- for the simple sine wave synthesis
float targetFrequency;
float phase;
float phaseAdder;
float phaseAdderTarget;
float timeCounter;
float timeOfLastFrame;
float amplitude;
float amplitudeTarget;
float pan;
float panTarget;
float sampleRate;
float diffTime;
float envelopeScale;
bool suicide;
bool dead;
static int idCount;
int id;
ofPoint currentPoint;
ofPoint currentVelocity;
// we use an "attack-hold-release" envelope.
// for t=0...attackTime: attack
// t=attackTime...releaseTime: hold
// t=releaseTime...duration: release
float attackTime;
float releaseTime;
int samplesSinceUpdate;
// how long should we wait before starting?
float startDelay;
float startTime;
};
#endif | [
"[email protected]"
]
| |
9cee39d79416b9e917c0ac72bb22f365c3ead342 | e4d3d56265ed372e08976670143ee88e54b84b2e | /includes/mfbt/tests/TestTypedEnum.cpp | 08566f2d3ccb6008f7076866bd131f220ac90b4b | [
"MIT"
]
| permissive | tigerwood/spec-cpp | e681d2a9de1e8469054ecf9a4b1aa109909a5774 | 1d7e33e93b9dfcecf8c79a94ee572965f6360247 | refs/heads/master | 2020-04-29T02:13:38.606000 | 2018-08-14T16:15:43 | 2018-08-14T16:15:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,255 | cpp | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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 "./Assertions.h"
#include "./Attributes.h"
#include "./TypedEnumBits.h"
#include <stdint.h>
// A rough feature check for is_literal_type. Not very carefully checked.
// Feel free to amend as needed.
// We leave ANDROID out because it's using stlport which doesn't have std::is_literal_type.
#if __cplusplus >= 201103L && !defined(ANDROID)
# if defined(__clang__)
/*
* Per Clang documentation, "Note that marketing version numbers should not
* be used to check for language features, as different vendors use different
* numbering schemes. Instead, use the feature checking macros."
*/
# ifndef __has_extension
# define __has_extension __has_feature /* compatibility, for older versions of clang */
# endif
# if __has_extension(is_literal) && __has_include(<type_traits>)
# define MOZ_HAVE_IS_LITERAL
# endif
# elif defined(__GNUC__) || defined(_MSC_VER)
# define MOZ_HAVE_IS_LITERAL
# endif
#endif
#if defined(MOZ_HAVE_IS_LITERAL) && defined(MOZ_HAVE_CXX11_CONSTEXPR)
#include <type_traits>
template<typename T>
void
RequireLiteralType()
{
static_assert(std::is_literal_type<T>::value, "Expected a literal type");
}
#else // not MOZ_HAVE_IS_LITERAL
template<typename T>
void
RequireLiteralType()
{
}
#endif
template<typename T>
void
RequireLiteralType(const T&)
{
RequireLiteralType<T>();
}
enum class AutoEnum {
A,
B = -3,
C
};
enum class CharEnum : char {
A,
B = 3,
C
};
enum class AutoEnumBitField {
A = 0x10,
B = 0x20,
C
};
enum class CharEnumBitField : char {
A = 0x10,
B,
C = 0x40
};
struct Nested
{
enum class AutoEnum {
A,
B,
C = -1
};
enum class CharEnum : char {
A = 4,
B,
C = 1
};
enum class AutoEnumBitField {
A,
B = 0x20,
C
};
enum class CharEnumBitField : char {
A = 1,
B = 1,
C = 1
};
};
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(AutoEnumBitField)
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(CharEnumBitField)
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(Nested::AutoEnumBitField)
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(Nested::CharEnumBitField)
#define MAKE_STANDARD_BITFIELD_FOR_TYPE(IntType) \
enum class BitFieldFor_##IntType : IntType { \
A = 1, \
B = 2, \
C = 4, \
}; \
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(BitFieldFor_##IntType)
MAKE_STANDARD_BITFIELD_FOR_TYPE(int8_t)
MAKE_STANDARD_BITFIELD_FOR_TYPE(uint8_t)
MAKE_STANDARD_BITFIELD_FOR_TYPE(int16_t)
MAKE_STANDARD_BITFIELD_FOR_TYPE(uint16_t)
MAKE_STANDARD_BITFIELD_FOR_TYPE(int32_t)
MAKE_STANDARD_BITFIELD_FOR_TYPE(uint32_t)
MAKE_STANDARD_BITFIELD_FOR_TYPE(int64_t)
MAKE_STANDARD_BITFIELD_FOR_TYPE(uint64_t)
MAKE_STANDARD_BITFIELD_FOR_TYPE(char)
typedef signed char signed_char;
MAKE_STANDARD_BITFIELD_FOR_TYPE(signed_char)
typedef unsigned char unsigned_char;
MAKE_STANDARD_BITFIELD_FOR_TYPE(unsigned_char)
MAKE_STANDARD_BITFIELD_FOR_TYPE(short)
typedef unsigned short unsigned_short;
MAKE_STANDARD_BITFIELD_FOR_TYPE(unsigned_short)
MAKE_STANDARD_BITFIELD_FOR_TYPE(int)
typedef unsigned int unsigned_int;
MAKE_STANDARD_BITFIELD_FOR_TYPE(unsigned_int)
MAKE_STANDARD_BITFIELD_FOR_TYPE(long)
typedef unsigned long unsigned_long;
MAKE_STANDARD_BITFIELD_FOR_TYPE(unsigned_long)
typedef long long long_long;
MAKE_STANDARD_BITFIELD_FOR_TYPE(long_long)
typedef unsigned long long unsigned_long_long;
MAKE_STANDARD_BITFIELD_FOR_TYPE(unsigned_long_long)
#undef MAKE_STANDARD_BITFIELD_FOR_TYPE
template<typename T>
void
TestNonConvertibilityForOneType()
{
using mozilla::IsConvertible;
static_assert(!IsConvertible<T, bool>::value, "should not be convertible");
static_assert(!IsConvertible<T, int>::value, "should not be convertible");
static_assert(!IsConvertible<T, uint64_t>::value, "should not be convertible");
static_assert(!IsConvertible<bool, T>::value, "should not be convertible");
static_assert(!IsConvertible<int, T>::value, "should not be convertible");
static_assert(!IsConvertible<uint64_t, T>::value, "should not be convertible");
}
template<typename TypedEnum>
void
TestTypedEnumBasics()
{
const TypedEnum a = TypedEnum::A;
int unused = int(a);
(void) unused;
RequireLiteralType(TypedEnum::A);
RequireLiteralType(a);
TestNonConvertibilityForOneType<TypedEnum>();
}
// Op wraps a bitwise binary operator, passed as a char template parameter,
// and applies it to its arguments (aT1, aT2). For example,
//
// Op<'|'>(aT1, aT2)
//
// is the same as
//
// aT1 | aT2.
//
template<char o, typename T1, typename T2>
auto Op(const T1& aT1, const T2& aT2)
-> decltype(aT1 | aT2) // See the static_assert's below --- the return type
// depends solely on the operands type, not on the
// choice of operation.
{
using mozilla::IsSame;
static_assert(IsSame<decltype(aT1 | aT2), decltype(aT1 & aT2)>::value,
"binary ops should have the same result type");
static_assert(IsSame<decltype(aT1 | aT2), decltype(aT1 ^ aT2)>::value,
"binary ops should have the same result type");
static_assert(o == '|' ||
o == '&' ||
o == '^', "unexpected operator character");
return o == '|' ? aT1 | aT2
: o == '&' ? aT1 & aT2
: aT1 ^ aT2;
}
// OpAssign wraps a bitwise binary operator, passed as a char template
// parameter, and applies the corresponding compound-assignment operator to its
// arguments (aT1, aT2). For example,
//
// OpAssign<'|'>(aT1, aT2)
//
// is the same as
//
// aT1 |= aT2.
//
template<char o, typename T1, typename T2>
T1& OpAssign(T1& aT1, const T2& aT2)
{
static_assert(o == '|' ||
o == '&' ||
o == '^', "unexpected operator character");
switch (o) {
case '|': return aT1 |= aT2;
case '&': return aT1 &= aT2;
case '^': return aT1 ^= aT2;
default: MOZ_CRASH();
}
}
// Tests a single binary bitwise operator, using a single set of three operands.
// The operations tested are:
//
// result = aT1 Op aT2;
// result Op= aT3;
//
// Where Op is the operator specified by the char template parameter 'o' and
// can be any of '|', '&', '^'.
//
// Note that the operands aT1, aT2, aT3 are intentionally passed with free
// types (separate template parameters for each) because their type may
// actually be different from TypedEnum:
//
// 1) Their type could be CastableTypedEnumResult<TypedEnum> if they are
// the result of a bitwise operation themselves;
// 2) In the non-c++11 legacy path, the type of enum values is also
// different from TypedEnum.
//
template<typename TypedEnum, char o, typename T1, typename T2, typename T3>
void TestBinOp(const T1& aT1, const T2& aT2, const T3& aT3)
{
typedef typename mozilla::detail::UnsignedIntegerTypeForEnum<TypedEnum>::Type
UnsignedIntegerType;
// Part 1:
// Test the bitwise binary operator i.e.
// result = aT1 Op aT2;
auto result = Op<o>(aT1, aT2);
typedef decltype(result) ResultType;
RequireLiteralType<ResultType>();
TestNonConvertibilityForOneType<ResultType>();
UnsignedIntegerType unsignedIntegerResult =
Op<o>(UnsignedIntegerType(aT1), UnsignedIntegerType(aT2));
MOZ_RELEASE_ASSERT(unsignedIntegerResult == UnsignedIntegerType(result));
MOZ_RELEASE_ASSERT(TypedEnum(unsignedIntegerResult) == TypedEnum(result));
MOZ_RELEASE_ASSERT((!unsignedIntegerResult) == (!result));
MOZ_RELEASE_ASSERT((!!unsignedIntegerResult) == (!!result));
MOZ_RELEASE_ASSERT(bool(unsignedIntegerResult) == bool(result));
// Part 2:
// Test the compound-assignment operator, i.e.
// result Op= aT3;
TypedEnum newResult = result;
OpAssign<o>(newResult, aT3);
UnsignedIntegerType unsignedIntegerNewResult = unsignedIntegerResult;
OpAssign<o>(unsignedIntegerNewResult, UnsignedIntegerType(aT3));
MOZ_RELEASE_ASSERT(TypedEnum(unsignedIntegerNewResult) == newResult);
// Part 3:
// Test additional boolean operators that we unfortunately had to add to
// CastableTypedEnumResult at some point to please some compiler,
// even though bool convertibility should have been enough.
MOZ_RELEASE_ASSERT(result == TypedEnum(result));
MOZ_RELEASE_ASSERT(!(result != TypedEnum(result)));
MOZ_RELEASE_ASSERT((result && true) == bool(result));
MOZ_RELEASE_ASSERT((result && false) == false);
MOZ_RELEASE_ASSERT((true && result) == bool(result));
MOZ_RELEASE_ASSERT((false && result && false) == false);
MOZ_RELEASE_ASSERT((result || false) == bool(result));
MOZ_RELEASE_ASSERT((result || true) == true);
MOZ_RELEASE_ASSERT((false || result) == bool(result));
MOZ_RELEASE_ASSERT((true || result) == true);
// Part 4:
// Test short-circuit evaluation.
auto Explode = [] {
// This function should never be called. Return an arbitrary value.
MOZ_RELEASE_ASSERT(false);
return false;
};
if (result) {
MOZ_RELEASE_ASSERT(result || Explode());
MOZ_RELEASE_ASSERT(!(!result && Explode()));
} else {
MOZ_RELEASE_ASSERT(!(result && Explode()));
MOZ_RELEASE_ASSERT(!result || Explode());
}
}
// Similar to TestBinOp but testing the unary ~ operator.
template<typename TypedEnum, typename T>
void TestTilde(const T& aT)
{
typedef typename mozilla::detail::UnsignedIntegerTypeForEnum<TypedEnum>::Type
UnsignedIntegerType;
auto result = ~aT;
typedef decltype(result) ResultType;
RequireLiteralType<ResultType>();
TestNonConvertibilityForOneType<ResultType>();
UnsignedIntegerType unsignedIntegerResult = ~(UnsignedIntegerType(aT));
MOZ_RELEASE_ASSERT(unsignedIntegerResult == UnsignedIntegerType(result));
MOZ_RELEASE_ASSERT(TypedEnum(unsignedIntegerResult) == TypedEnum(result));
MOZ_RELEASE_ASSERT((!unsignedIntegerResult) == (!result));
MOZ_RELEASE_ASSERT((!!unsignedIntegerResult) == (!!result));
MOZ_RELEASE_ASSERT(bool(unsignedIntegerResult) == bool(result));
}
// Helper dispatching a given triple of operands to all operator-specific
// testing functions.
template<typename TypedEnum, typename T1, typename T2, typename T3>
void TestAllOpsForGivenOperands(const T1& aT1, const T2& aT2, const T3& aT3)
{
TestBinOp<TypedEnum, '|'>(aT1, aT2, aT3);
TestBinOp<TypedEnum, '&'>(aT1, aT2, aT3);
TestBinOp<TypedEnum, '^'>(aT1, aT2, aT3);
TestTilde<TypedEnum>(aT1);
}
// Helper building various triples of operands using a given operator,
// and testing all operators with them.
template<typename TypedEnum, char o>
void TestAllOpsForOperandsBuiltUsingGivenOp()
{
// The type of enum values like TypedEnum::A may be different from
// TypedEnum. That is the case in the legacy non-C++11 path. We want to
// ensure good test coverage even when these two types are distinct.
// To that effect, we have both 'auto' typed variables, preserving the
// original type of enum values, and 'plain' typed variables, that
// are plain TypedEnum's.
const TypedEnum a_plain = TypedEnum::A;
const TypedEnum b_plain = TypedEnum::B;
const TypedEnum c_plain = TypedEnum::C;
auto a_auto = TypedEnum::A;
auto b_auto = TypedEnum::B;
auto c_auto = TypedEnum::C;
auto ab_plain = Op<o>(a_plain, b_plain);
auto bc_plain = Op<o>(b_plain, c_plain);
auto ab_auto = Op<o>(a_auto, b_auto);
auto bc_auto = Op<o>(b_auto, c_auto);
// On each row below, we pass a triple of operands. Keep in mind that this
// is going to be received as (aT1, aT2, aT3) and the actual tests performed
// will be of the form
//
// result = aT1 Op aT2;
// result Op= aT3;
//
// For this reason, we carefully ensure that the values of (aT1, aT2)
// systematically cover all types of such pairs; to limit complexity,
// we are not so careful with aT3, and we just try to pass aT3's
// that may lead to nontrivial bitwise operations.
TestAllOpsForGivenOperands<TypedEnum>(a_plain, b_plain, c_plain);
TestAllOpsForGivenOperands<TypedEnum>(a_plain, bc_plain, b_auto);
TestAllOpsForGivenOperands<TypedEnum>(ab_plain, c_plain, a_plain);
TestAllOpsForGivenOperands<TypedEnum>(ab_plain, bc_plain, a_auto);
TestAllOpsForGivenOperands<TypedEnum>(a_plain, b_auto, c_plain);
TestAllOpsForGivenOperands<TypedEnum>(a_plain, bc_auto, b_auto);
TestAllOpsForGivenOperands<TypedEnum>(ab_plain, c_auto, a_plain);
TestAllOpsForGivenOperands<TypedEnum>(ab_plain, bc_auto, a_auto);
TestAllOpsForGivenOperands<TypedEnum>(a_auto, b_plain, c_plain);
TestAllOpsForGivenOperands<TypedEnum>(a_auto, bc_plain, b_auto);
TestAllOpsForGivenOperands<TypedEnum>(ab_auto, c_plain, a_plain);
TestAllOpsForGivenOperands<TypedEnum>(ab_auto, bc_plain, a_auto);
TestAllOpsForGivenOperands<TypedEnum>(a_auto, b_auto, c_plain);
TestAllOpsForGivenOperands<TypedEnum>(a_auto, bc_auto, b_auto);
TestAllOpsForGivenOperands<TypedEnum>(ab_auto, c_auto, a_plain);
TestAllOpsForGivenOperands<TypedEnum>(ab_auto, bc_auto, a_auto);
}
// Tests all bitwise operations on a given TypedEnum bitfield.
template<typename TypedEnum>
void
TestTypedEnumBitField()
{
TestTypedEnumBasics<TypedEnum>();
TestAllOpsForOperandsBuiltUsingGivenOp<TypedEnum, '|'>();
TestAllOpsForOperandsBuiltUsingGivenOp<TypedEnum, '&'>();
TestAllOpsForOperandsBuiltUsingGivenOp<TypedEnum, '^'>();
}
// Checks that enum bitwise expressions have the same non-convertibility
// properties as c++11 enum classes do, i.e. not implicitly convertible to
// anything (though *explicitly* convertible).
void TestNoConversionsBetweenUnrelatedTypes()
{
using mozilla::IsConvertible;
// Two typed enum classes having the same underlying integer type, to ensure
// that we would catch bugs accidentally allowing conversions in that case.
typedef CharEnumBitField T1;
typedef Nested::CharEnumBitField T2;
static_assert(!IsConvertible<T1, T2>::value,
"should not be convertible");
static_assert(!IsConvertible<T1, decltype(T2::A)>::value,
"should not be convertible");
static_assert(!IsConvertible<T1, decltype(T2::A | T2::B)>::value,
"should not be convertible");
static_assert(!IsConvertible<decltype(T1::A), T2>::value,
"should not be convertible");
static_assert(!IsConvertible<decltype(T1::A), decltype(T2::A)>::value,
"should not be convertible");
static_assert(!IsConvertible<decltype(T1::A), decltype(T2::A | T2::B)>::value,
"should not be convertible");
static_assert(!IsConvertible<decltype(T1::A | T1::B), T2>::value,
"should not be convertible");
static_assert(!IsConvertible<decltype(T1::A | T1::B), decltype(T2::A)>::value,
"should not be convertible");
static_assert(!IsConvertible<decltype(T1::A | T1::B), decltype(T2::A | T2::B)>::value,
"should not be convertible");
}
enum class Int8EnumWithHighBits : int8_t {
A = 0x20,
B = 0x40
};
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(Int8EnumWithHighBits)
enum class Uint8EnumWithHighBits : uint8_t {
A = 0x40,
B = 0x80
};
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(Uint8EnumWithHighBits)
enum class Int16EnumWithHighBits : int16_t {
A = 0x2000,
B = 0x4000
};
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(Int16EnumWithHighBits)
enum class Uint16EnumWithHighBits : uint16_t {
A = 0x4000,
B = 0x8000
};
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(Uint16EnumWithHighBits)
enum class Int32EnumWithHighBits : int32_t {
A = 0x20000000,
B = 0x40000000
};
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(Int32EnumWithHighBits)
enum class Uint32EnumWithHighBits : uint32_t {
A = 0x40000000u,
B = 0x80000000u
};
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(Uint32EnumWithHighBits)
enum class Int64EnumWithHighBits : int64_t {
A = 0x2000000000000000ll,
B = 0x4000000000000000ll
};
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(Int64EnumWithHighBits)
enum class Uint64EnumWithHighBits : uint64_t {
A = 0x4000000000000000ull,
B = 0x8000000000000000ull
};
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(Uint64EnumWithHighBits)
// Checks that we don't accidentally truncate high bits by coercing to the wrong
// integer type internally when implementing bitwise ops.
template<typename EnumType, typename IntType>
void TestIsNotTruncated()
{
EnumType a = EnumType::A;
EnumType b = EnumType::B;
MOZ_RELEASE_ASSERT(IntType(a));
MOZ_RELEASE_ASSERT(IntType(b));
MOZ_RELEASE_ASSERT(a | EnumType::B);
MOZ_RELEASE_ASSERT(a | b);
MOZ_RELEASE_ASSERT(EnumType::A | EnumType::B);
EnumType c = EnumType::A | EnumType::B;
MOZ_RELEASE_ASSERT(IntType(c));
MOZ_RELEASE_ASSERT(c & c);
MOZ_RELEASE_ASSERT(c | c);
MOZ_RELEASE_ASSERT(c == (EnumType::A | EnumType::B));
MOZ_RELEASE_ASSERT(a != (EnumType::A | EnumType::B));
MOZ_RELEASE_ASSERT(b != (EnumType::A | EnumType::B));
MOZ_RELEASE_ASSERT(c & EnumType::A);
MOZ_RELEASE_ASSERT(c & EnumType::B);
EnumType d = EnumType::A;
d |= EnumType::B;
MOZ_RELEASE_ASSERT(d == c);
}
int
main()
{
TestTypedEnumBasics<AutoEnum>();
TestTypedEnumBasics<CharEnum>();
TestTypedEnumBasics<Nested::AutoEnum>();
TestTypedEnumBasics<Nested::CharEnum>();
TestTypedEnumBitField<AutoEnumBitField>();
TestTypedEnumBitField<CharEnumBitField>();
TestTypedEnumBitField<Nested::AutoEnumBitField>();
TestTypedEnumBitField<Nested::CharEnumBitField>();
TestTypedEnumBitField<BitFieldFor_uint8_t>();
TestTypedEnumBitField<BitFieldFor_int8_t>();
TestTypedEnumBitField<BitFieldFor_uint16_t>();
TestTypedEnumBitField<BitFieldFor_int16_t>();
TestTypedEnumBitField<BitFieldFor_uint32_t>();
TestTypedEnumBitField<BitFieldFor_int32_t>();
TestTypedEnumBitField<BitFieldFor_uint64_t>();
TestTypedEnumBitField<BitFieldFor_int64_t>();
TestTypedEnumBitField<BitFieldFor_char>();
TestTypedEnumBitField<BitFieldFor_signed_char>();
TestTypedEnumBitField<BitFieldFor_unsigned_char>();
TestTypedEnumBitField<BitFieldFor_short>();
TestTypedEnumBitField<BitFieldFor_unsigned_short>();
TestTypedEnumBitField<BitFieldFor_int>();
TestTypedEnumBitField<BitFieldFor_unsigned_int>();
TestTypedEnumBitField<BitFieldFor_long>();
TestTypedEnumBitField<BitFieldFor_unsigned_long>();
TestTypedEnumBitField<BitFieldFor_long_long>();
TestTypedEnumBitField<BitFieldFor_unsigned_long_long>();
TestNoConversionsBetweenUnrelatedTypes();
TestIsNotTruncated<Int8EnumWithHighBits, int8_t>();
TestIsNotTruncated<Int16EnumWithHighBits, int16_t>();
TestIsNotTruncated<Int32EnumWithHighBits, int32_t>();
TestIsNotTruncated<Int64EnumWithHighBits, int64_t>();
TestIsNotTruncated<Uint8EnumWithHighBits, uint8_t>();
TestIsNotTruncated<Uint16EnumWithHighBits, uint16_t>();
TestIsNotTruncated<Uint32EnumWithHighBits, uint32_t>();
TestIsNotTruncated<Uint64EnumWithHighBits, uint64_t>();
return 0;
}
| [
"[email protected]"
]
| |
c826477a720a35c4b450658ab22c4c71138b22e4 | bd9370392b0fb5aaffc5ce2c6e0088fca58e1a62 | /RakNet/Source/cat/Config.hpp | fc26407a609be71bc59b08ef4c6bc415c3162bc2 | [
"BSD-3-Clause"
]
| permissive | FearlessSon/Colin-AIE-Term-Project | 6151537375e0a623afb3669a430bb7afe8771d5e | b706335451669fc58dff6ea4c097f7661a9c483a | refs/heads/master | 2021-01-10T20:03:24.169449 | 2013-06-13T17:02:49 | 2013-06-13T17:02:49 | 10,132,201 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,472 | hpp | /*
Copyright (c) 2009-2010 Christopher A. Taylor. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of LibCat nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CAT_CONFIG_HPP
#define CAT_CONFIG_HPP
namespace cat {
// This definition overrides CAT_BUILD_DLL below. Neuters CAT_EXPORT macro so symbols are
// neither exported or imported.
//#define CAT_NEUTER_EXPORT
// This definition changes the meaning of the CAT_EXPORT macro on Windows. When defined,
// the CAT_EXPORT macro will export the associated symbol. When undefined, it will import it.
//#define CAT_BUILD_DLL
// If you want to remove server-side code from a binary distribution of a client program:
//#define CAT_OMIT_SERVER_CODE
// If you know the endianness of your target, uncomment one of these for better performance.
//#define __LITTLE_ENDIAN__
//#define __BIG_ENDIAN__
// If you want to use faster 384-bit or 512-bit math, define this:
//#define CAT_UNROLL_OVER_256_BITS
// Adjust if your architecture uses larger than 128-bit cache line
#define CAT_DEFAULT_CACHE_LINE_SIZE 16
} // namespace cat
#endif // CAT_CONFIG_HPP
| [
"[email protected]"
]
| |
379de8ccefc2d4ebe67da8afb6d99a6548bed11b | 4335e39b1d955a987e43c734357e6f19debec0c4 | /accumulate.hpp | 469593cb3c4ee9af05619321a04a93211e39e3c3 | [
"MIT"
]
| permissive | amichai-H/it-cp-a | aaa27a0f2c7ad6d661c057cf5e67c6e6173d81fa | 7dd6fc503ae436c1a3a95e48217ce70562a21ab8 | refs/heads/master | 2022-10-06T00:47:13.162945 | 2020-06-10T16:03:37 | 2020-06-10T16:03:37 | 271,322,187 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,123 | hpp | //
// Created by amichai hadad on 08/06/2020.
//
#ifndef ITERTOOLS_CFAR_A_MASTER_ACCUMULATE_HPP
#define ITERTOOLS_CFAR_A_MASTER_ACCUMULATE_HPP
#include "range.hpp"
#include <iterator>
namespace itertools {
typedef struct {
template<typename T>
T operator()(T a, T b) const {
return a+b;
}
}myFunc;
template <typename VAC, typename FUNC = myFunc>
class accumulate {
VAC data;
FUNC func;
public:
explicit accumulate(VAC x,FUNC f = myFunc()) : data(x), func(f) {}
class iterator{
decltype (*(data.begin())) _it_data;
typename VAC::iterator _iter;
typename VAC::iterator _it_end;
FUNC _it_func;
public:
explicit iterator(typename VAC::iterator it, typename VAC::iterator end, FUNC func)
: _iter(it), _it_end(end), _it_func(func), _it_data(*it){};
iterator(const iterator& other) = default;
iterator& operator=(const iterator& other) {
if (&other != this){
iterator(other._iter,other._it_end,other._it_func);
}
return *this;
}
iterator& operator++(){
++_iter;
if(_iter != _it_end)
_it_data = _it_func(_it_data, *_iter);
return *this;
}
iterator operator++(int){
iterator temp = *this;
++(*this);
return temp;
}
bool operator==(const iterator& other) {
return (_iter == other._iter);
}
bool operator!=(const iterator& other) {
return (_iter != other._iter);
}
auto operator*(){
return _it_data;
}
};
iterator begin(){
return iterator(data.begin(), data.end(), func);
}
iterator end(){
return iterator(data.end(), data.end(), func);
}
};
};
#endif //ITERTOOLS_CFAR_A_MASTER_ACCUMULATE_HPP
| [
"[email protected]"
]
| |
750240a328879a6d4034f3b1ebff211db899fe63 | 575ca804ab3745e681994823c92a273e1e690eed | /lv_cpp/widgets/LvImg.cpp | d85a924a549d4df3b5339ad74bd769404131bbae | [
"MIT"
]
| permissive | HowToMeetLadies/lv_binding_cpp | 3851826cea9562de214af5dd102045304b4cdc45 | 5ce27254ac8526dd1ca61e883785ed2606076a68 | refs/heads/master | 2023-08-05T21:05:15.280138 | 2021-09-14T13:53:59 | 2021-09-14T13:53:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,615 | cpp | /*
* LvImg.cpp
*
*/
#include "LvImg.h"
namespace lvglpp {
LvImg::LvImg() : LvImg(NULL) {
}
LvImg::LvImg(LvObj* Parent) : LvObj(Parent) {
if(Parent)
cObj.reset(lv_img_create(Parent->raw()));
else
cObj.reset(lv_img_create(lv_scr_act()));
setUserData(this);
}
LvImg::~LvImg() {
}
LvImg& LvImg::setSrc(const void *src){
lv_img_set_src(cObj.get(),src);
return *this;
}
LvImg& LvImg::setOffsetX(lv_coord_t x){
lv_img_set_offset_x(cObj.get(),x);
return *this;
}
LvImg& LvImg::setOffsetY(lv_coord_t y){
lv_img_set_offset_y(cObj.get(),y);
return *this;
}
LvImg& LvImg::setAngle(int16_t angle){
lv_img_set_angle(cObj.get(),angle);
return *this;
}
LvImg& LvImg::setPivot(lv_coord_t x, lv_coord_t y){
lv_img_set_pivot(cObj.get(),x,y);
return *this;
}
LvImg& LvImg::setZoom(uint16_t zoom){
lv_img_set_zoom(cObj.get(),zoom);
return *this;
}
LvImg& LvImg::setAntialias(bool antialias){
lv_img_set_antialias(cObj.get(),antialias);
return *this;
}
const void *LvImg::getSrc() const noexcept {
return lv_img_get_src(cObj.get());
}
lv_coord_t LvImg::getOffsetX() const noexcept {
return lv_img_get_offset_x(cObj.get());
}
lv_coord_t LvImg::getOffsetY() const noexcept {
return lv_img_get_offset_y(cObj.get());
}
uint16_t LvImg::getAngle() const noexcept {
return lv_img_get_angle(cObj.get());
}
LvImg& LvImg::getPivot(lv_point_t *pivot){
lv_img_get_pivot(cObj.get(),pivot);
return *this;
}
uint16_t LvImg::getZoom() const noexcept {
return lv_img_get_zoom(cObj.get());
}
bool LvImg::getAntialias() const noexcept {
return lv_img_get_antialias(cObj.get());
}
} /* namespace lvglpp */
| [
"[email protected]"
]
| |
3f13a654c440951120e2bbaefcddc13ddf1c0dec | 4c378a1be91f9574cffb428ea1a493dbe7306773 | /Eugene_and_an_array.cpp | 2a2ce35f92277d3560091498ae9746109ba49754 | []
| no_license | nishantprajapati123/competitive-coding | 81c09976833ff49d079e4edd0c5254203d0552d7 | 8cbac4be5cd36c3626af4676a8385a638f98654e | refs/heads/master | 2021-07-07T14:02:21.646254 | 2020-08-26T07:36:28 | 2020-08-26T07:36:28 | 160,255,056 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,130 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define pb push_back
#define mk make_pair
#define deb(x) cout << #x << "=" << x << endl
#define all(x) x.begin(), x.end()
#define clr(x) memset(x, 0, sizeof(x))
#define sortall(x) sort(all(x))
#define PI 3.1415926535897932384626
#define MOD 1000000007
#define INF (int)1e9
#define fastIO ios::sync_with_stdio(0); cin.tie(0);
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
int A[200002];
void solve()
{
int n;
scanf("%d", &n);
ll sum = 0;
int mx = 0;
map<ll,int>mp;
ll ans = 0;
mp[0] = -1;
for(int i=1;i<=n;i++)
{
cin>>A[i];
sum += A[i];
if(mp.find(sum)!=mp.end())
{
if(sum == 0 && mp[0] == -1)
mx = max(mx,1);
else
mx = max(mx,mp[sum]+1);
}
mp[sum] = i;
ans += i - mx;
}
printf("%lld\n",ans);
}
int main()
{
fastIO
solve();
return 0;
} | [
"[email protected]"
]
| |
b50ebd140203ac5c15cf2939d1bc76371466dca5 | 798b409c2262078dfe770960586160fc47434fae | /include/sbstd/sb_shared_ptr.h | 6d7962908161fb4409ea5011d51ce97077920e82 | []
| no_license | andryblack/sandbox | b53fe7b148901442d24d2bcfc411ddce531b7664 | 6fcffae0e00ecf31052c98d2437dbed242509438 | refs/heads/master | 2021-01-25T15:52:16.330633 | 2019-08-26T09:24:00 | 2019-08-26T09:24:00 | 2,220,342 | 5 | 8 | null | 2018-06-18T15:41:44 | 2011-08-17T07:10:54 | C++ | UTF-8 | C++ | false | false | 11,968 | h | /*
* sb_shared_ptr.h
* SR
*
* Created by Андрей Куницын on 06.02.11.
* Copyright 2011 andryblack. All rights reserved.
*
*/
#ifndef SB_SHARED_PTR_H
#define SB_SHARED_PTR_H
#include <cstring>
#include "sb_assert.h"
#include "sb_pointer.h"
namespace sb {
template <class T> class weak_ptr;
template <class T> class shared_ptr;
template <class T> class enable_shared_from_this;
namespace implement {
template <class T> struct destroyer {
void operator () (const T *d) const {
delete d;
}
};
struct counter_base {
counter_base(size_t refs_,size_t weaks_) :
refs(refs_),weaks(weaks_) {}
size_t refs;
size_t weaks;
virtual void destruct(const void*) = 0;
virtual ~counter_base() {}
};
template <class T>
struct default_counter_t : counter_base {
default_counter_t(size_t refs_,size_t weaks_) :
counter_base(refs_,weaks_) {}
virtual void destruct(const void* v) {
delete static_cast<const T*>(v);
}
};
template <class T,class D>
struct counter_t : public counter_base{
counter_t(size_t refs_,size_t weaks_,D deleter_) :
counter_base(refs_,weaks_),deleter(deleter_) {}
counter_t(size_t refs_,size_t weaks_) :
counter_base(refs_,weaks_),deleter() {}
D deleter;
virtual void destruct(const void* v) { deleter(static_cast<const T*>(v)); }
};
template <class T> struct counter_with_buffer_t : default_counter_t<T> {
counter_with_buffer_t(size_t refs_,size_t weaks_) :
default_counter_t<T>(refs_,weaks_) {}
char buf[sizeof(T)];
virtual void destruct(const void* v) {
static_cast<const T*>(v)->~T();
}
};
template <class T,class Y>
inline void shared_from_this_support( int /*fake*/,const enable_shared_from_this<T>* ptr, const shared_ptr<Y>* sptr ) {
if (ptr) {
const_cast<enable_shared_from_this<T>*>(ptr)->internal_get_weak() = weak_ptr<T>(*sptr);
}
}
inline void shared_from_this_support( int /*fake*/,...) {
}
}
template <class T> class shared_ptr {
public:
shared_ptr() : ptr(0), counter(0) {}
template <class U>
explicit shared_ptr(U* ptr_) : ptr(ptr_),counter(ptr ? new implement::default_counter_t<U>(1,0) : 0) {
implement::shared_from_this_support(0,ptr,this);
}
template <class U,class D>
shared_ptr(U* ptr_,D deleter) : ptr(ptr_),counter(ptr ? new implement::counter_t<U,D>(1,0,deleter) : 0) {
implement::shared_from_this_support(0,ptr,this);
}
shared_ptr(T* ptr_,implement::counter_base* counter_) : ptr(ptr_),counter(counter_) {
if (this->counter)
this->counter->refs++;
implement::shared_from_this_support(0,ptr,this);
}
~shared_ptr() {
release();
}
shared_ptr(const shared_ptr& other ) : ptr(other.get()),counter(other.get_counter()) {
if (counter) counter->refs++;
}
template <class U>
shared_ptr(const shared_ptr<U>& other ) : ptr(other.get()),counter(other.get_counter()) {
if (counter) counter->refs++;
}
template <class U>
shared_ptr(const shared_ptr<U>& other,const implement::static_cast_tag& ) : ptr(static_cast<T*>(other.get())),counter(other.get_counter()) {
if (counter) counter->refs++;
}
template <class U>
shared_ptr(const shared_ptr<U>& other,const implement::dynamic_cast_tag& ) : ptr(dynamic_cast<T*>(other.get())),counter(other.get_counter()) {
if (counter) counter->refs++;
}
shared_ptr& operator = (const shared_ptr& other) {
if ((other.get()!=ptr) || (other.get_counter()!=counter)) {
release();
ptr = other.get();
counter = other.get_counter();
if (counter) counter->refs++;
}
return *this;
}
template <class U>
shared_ptr& operator = (const shared_ptr<U>& other) {
if ((other.get()!=ptr) || (other.get_counter()!=counter)) {
release();
ptr = other.get();
counter = other.get_counter();
if (counter) counter->refs++;
}
return *this;
}
T* operator -> () const { sb_assert(ptr);return ptr; }
T & operator*() const { sb_assert(ptr);return *ptr; }
bool operator == (const int val) const {
sb_assert(val==0);
return ptr==(T*)(val);
}
bool operator == (const shared_ptr<T>& other) const {
return (ptr == other.ptr) && (counter == other.counter);
}
bool operator != (const shared_ptr<T>& other) const {
return (ptr != other.ptr) || (counter != other.counter);
}
T* get() const { return ptr;}
typedef T* shared_ptr::*unspecified_bool_type;
operator unspecified_bool_type() const {
return ptr ? &shared_ptr::ptr : 0;
}
void reset() {
release();
}
template <class U>
void reset(U* v) {
shared_ptr other(v);
*this = other;
}
implement::counter_base* get_counter() const { return counter;}
private:
void release() {
if (counter) {
sb_assert(counter->refs>0);
implement::counter_base* cntr = counter;
counter = 0;
if (cntr->refs==1) {
T* obj = ptr;
ptr = 0;
if (obj) cntr->destruct(obj);
}
if (--cntr->refs==0) {
if (cntr->weaks==0) {
delete cntr;
}
}
}
}
T* ptr;
implement::counter_base* counter;
};
template <class T> class weak_ptr {
public:
weak_ptr() : ptr(0), counter(0) {}
~weak_ptr() {
release();
}
weak_ptr(const weak_ptr& other) : ptr(other.get_ptr()),counter(other.get_counter()) {
if (counter) counter->weaks++;
}
template <class U>
weak_ptr(const weak_ptr<U>& other) : ptr(other.get_ptr()),counter(other.get_counter()) {
if (counter) counter->weaks++;
}
weak_ptr(const shared_ptr<T>& shared) : ptr(shared.get()),counter(shared.get_counter()) {
if (counter) counter->weaks++;
}
template <class U>
weak_ptr(const shared_ptr<U>& shared) : ptr(shared.get()),counter(shared.get_counter()) {
if (counter) counter->weaks++;
}
weak_ptr& operator = (const weak_ptr& other) {
if (&other!=this) {
release();
ptr = other.get_ptr();
counter = other.get_counter();
if (counter) counter->weaks++;
}
return *this;
}
template <class U>
weak_ptr& operator = (const weak_ptr<U>& other) {
if (&other!=this) {
release();
ptr = other.get_ptr();
counter = other.get_counter();
if (counter) counter->weaks++;
}
return *this;
}
weak_ptr& operator = (const shared_ptr<T>& shared) {
release();
ptr = shared.get();
counter = shared.get_counter();
if (counter) counter->weaks++;
return *this;
}
template <class U>
weak_ptr& operator = (const shared_ptr<U>& shared) {
release();
ptr = shared.get();
counter = shared.get_counter();
if (counter) counter->weaks++;
return *this;
}
shared_ptr<T> lock() const {
if (ptr && counter && counter->refs)
return shared_ptr<T>(ptr,counter);
return shared_ptr<T>();
}
implement::counter_base* get_counter() const { return counter;}
T* get_ptr() const { return ptr;}
private:
void release() {
if (counter) {
sb_assert(counter->weaks>0);
if (--counter->weaks==0) {
if (counter->refs==0) {
delete counter;
}
}
}
ptr = 0;
counter = 0;
}
T* ptr;
implement::counter_base* counter;
};
template <class T> class enable_shared_from_this {
public:
shared_ptr<T> shared_from_this() { return weak.lock();}
protected:
enable_shared_from_this() : weak() {}
~enable_shared_from_this() {}
enable_shared_from_this(const enable_shared_from_this&) {}
enable_shared_from_this& operator = (const enable_shared_from_this& ) {
return *this;
}
private:
weak_ptr<T> weak;
public:
weak_ptr<T>& internal_get_weak() { return weak;}
};
template <class T,class U>
inline shared_ptr<T> static_pointer_cast( const shared_ptr<U>& ptr) {
return shared_ptr<T>(ptr,implement::static_cast_tag());
}
template <class T,class U>
inline shared_ptr<T> dynamic_pointer_cast( const shared_ptr<U>& ptr) {
return shared_ptr<T>(ptr,implement::dynamic_cast_tag());
}
template <class T>
inline shared_ptr<T> make_shared() {
typedef implement::counter_with_buffer_t<T> cntr_t;
cntr_t* cntr = new cntr_t(0,0);
return shared_ptr<T>(new (cntr->buf) T(),static_cast<implement::counter_base*>(cntr));
}
template <class T,class A1>
inline shared_ptr<T> make_shared(A1 a1) {
typedef implement::counter_with_buffer_t<T> cntr_t;
cntr_t* cntr = new cntr_t(0,0);
return shared_ptr<T>(new (cntr->buf) T(a1),static_cast<implement::counter_base*>(cntr));
}
template <class T,class A1,class A2>
inline shared_ptr<T> make_shared(A1 a1,A2 a2) {
typedef implement::counter_with_buffer_t<T> cntr_t;
cntr_t* cntr = new cntr_t(0,0);
return shared_ptr<T>(new (cntr->buf) T(a1,a2),static_cast<implement::counter_base*>(cntr));
}
template <class T,class A1,class A2,class A3>
inline shared_ptr<T> make_shared(A1 a1,A2 a2,A3 a3) {
typedef implement::counter_with_buffer_t<T> cntr_t;
cntr_t* cntr = new cntr_t(0,0);
return shared_ptr<T>(new (cntr->buf) T(a1,a2,a3),static_cast<implement::counter_base*>(cntr));
}
template <class T,class A1,class A2,class A3,class A4>
inline shared_ptr<T> make_shared(A1 a1,A2 a2,A3 a3,A4 a4) {
typedef implement::counter_with_buffer_t<T> cntr_t;
cntr_t* cntr = new cntr_t(0,0);
return shared_ptr<T>(new (cntr->buf) T(a1,a2,a3,a4),static_cast<implement::counter_base*>(cntr));
}
template <class T,class A1,class A2,class A3,class A4,class A5>
inline shared_ptr<T> make_shared(A1 a1,A2 a2,A3 a3,A4 a4,A5 a5) {
typedef implement::counter_with_buffer_t<T> cntr_t;
cntr_t* cntr = new cntr_t(0,0);
return shared_ptr<T>(new (cntr->buf) T(a1,a2,a3,a4,a5),static_cast<implement::counter_base*>(cntr));
}
}
#endif /*SB_SHARED_PTR_H*/
| [
"[email protected]"
]
| |
5d1a89baeeb377bc2abd94fde7ed56fa9588929a | 7b64779fb8894e1fc1657fb3e09f6cb976b632c3 | /tilde~/graphicobjects/Grid.cpp | ea1a42e3275bcf643941cadf2f5504b536b3e953 | []
| no_license | njazz/tilde | 5780c2c958a7ca20d16592033dd97b9158a4ad0d | 0b97df749e678a9855518723e52af0afb967bd88 | refs/heads/master | 2022-08-27T01:04:24.422269 | 2022-08-14T12:27:12 | 2022-08-14T12:27:12 | 83,314,714 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 506 | cpp | // (c) 2017 Alex Nadzharov
// License: GPL3
#include "Grid.h"
#include <QPainter>
namespace tilde {
Grid::Grid()
{
_gridStep = 20;
}
void Grid::paint(QPainter* p, const QStyleOptionGraphicsItem*, QWidget*)
{
p->setPen(QPen(QColor(224, 224, 224), 1, Qt::DotLine, Qt::SquareCap, Qt::BevelJoin));
for (int x = 0; x < width(); x += _gridStep) {
p->drawLine(x, 0, x, height());
}
for (int y = 0; y < height(); y += _gridStep) {
p->drawLine(0, y, width(), y);
}
};
}
| [
"[email protected]"
]
| |
9bbd868810f5f875e912496a15886182c7047512 | 91c4e70da29d611198fdb4fde04a1401972b7e95 | /Source/Shoot/InfinitTerrainGameMode.cpp | 22fca72dce215ccf0bdc2826d718a1464b52ca39 | []
| no_license | TAZO0608/Shoot | 2d161ba4f2f93d1eef2ea8f6e762fca36c789140 | 2c44b62942d4f995196e3240c69ef4004a42f995 | refs/heads/master | 2021-01-24T08:16:42.065111 | 2018-02-26T23:08:59 | 2018-02-26T23:08:59 | 120,256,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 810 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "InfinitTerrainGameMode.h"
AInfinitTerrainGameMode::AInfinitTerrainGameMode()
{
NavMeshBoundsVolumePool = CreateDefaultSubobject<UMyPool>(FName("Nav Mesh Bounds Volume Pool"));
}
void AInfinitTerrainGameMode::PopulateBoundsVolumePool()
{
TActorIterator<ANavMeshBoundsVolume> VolumeIterator = TActorIterator<ANavMeshBoundsVolume>(GetWorld());
while (VolumeIterator)
{
AddToPool(*VolumeIterator);
UE_LOG(LogTemp, Warning, TEXT("add"));
++VolumeIterator;
}
}
void AInfinitTerrainGameMode::AddToPool(ANavMeshBoundsVolume* VolumeToAdd)
{
if (VolumeToAdd == nullptr) { return; }
//UE_LOG(LogTemp, Warning, TEXT("Found Actor: %s"), *VolumeToAdd->GetName());
NavMeshBoundsVolumePool->Add(VolumeToAdd);
}
| [
"[email protected]"
]
| |
e5498b4a0eeb8c9922fae106601d55dd950b3d8f | 2173de8a7714f2fbc35f9519c2e742ae8f37c49b | /rrating.cpp | d6d6c220a2a32f8470cbadbf044508ecc1df8ceb | []
| no_license | sanjeev1779/codechef | b7e3b8bfe05989037f4e78f3f7191368abba7b10 | a132632f543ee192cf49f0280333f976908e7be5 | refs/heads/master | 2021-01-25T08:28:48.487194 | 2014-07-28T01:05:46 | 2014-07-28T01:05:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 210 | cpp | #include<iostream>
#include<vector>
#include<string.h>
#include<stdio.h>
#include<map>
#include<math.h>
#include<algorithm>
#define LL long long
#define pb push_back
using namespace std;
main()
{
return 0;
}
| [
"[email protected]"
]
| |
b616782f52e2db17dcfe4abb5ab5821f1c7cc709 | 55cec48a0f9c3312a8e87a3f657a79422e6855b1 | /Source/Utility/LostDream/Reflection/Serialization.cpp | 87e94bbf953d11babc4f74fcb0d4a9bf8a68569c | [
"MIT"
]
| permissive | killvxk/PaintsNow | 65313cf445e0ac07169a7c9c412f41bb31500710 | f30aa83b419f75dc8af95f87827c4147cf75800f | refs/heads/master | 2020-04-11T20:31:09.750644 | 2018-12-16T14:09:12 | 2018-12-16T14:09:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,369 | cpp | #include "Serialization.h"
#include "../../../Core/Common/ZMemoryStream.h"
using namespace PaintsNow;
using namespace PaintsNow::NsLostDream;
struct MyType : public IReflectObjectComplex {
virtual TObject<IReflect>& operator () (IReflect& reflect) {
ReflectClass(MyType);
if (reflect.IsReflectProperty()) {
ReflectProperty(hi);
}
return *this;
}
String hi;
};
struct MarshallInfo : public IReflectObjectComplex {
MarshallInfo() : dynType(nullptr) {}
virtual ~MarshallInfo() {
if (dynType != nullptr) {
dynType->ReleaseObject();
}
for (size_t i = 0; i < dynVector.size(); i++) {
IReflectObjectComplex* c = dynVector[i];
if (c != nullptr) {
c->ReleaseObject();
}
}
}
virtual TObject<IReflect>& operator () (IReflect& reflect) {
ReflectClass(MarshallInfo);
if (reflect.IsReflectProperty()) {
ReflectProperty(name);
ReflectProperty(value);
ReflectProperty(test);
ReflectProperty(mytype);
ReflectProperty(mytype2);
ReflectProperty(IterateVector(arr));
ReflectProperty(IterateVector(arrmytype));
ReflectProperty(dynType);
ReflectProperty(IterateVector(dynVector));
}
return *this;
}
String name;
int value;
double test;
MyType mytype;
MyType mytype2;
IReflectObjectComplex* dynType;
std::vector<int> arr;
std::vector<MyType> arrmytype;
std::vector<IReflectObjectComplex*> dynVector;
};
struct Another : public IReflectObjectComplex {
virtual TObject<IReflect>& operator () (IReflect& reflect) {
ReflectClass(Another);
if (reflect.IsReflectProperty()) {
ReflectProperty(magic);
}
return *this;
}
short magic;
};
struct Derived : public MarshallInfo {
public:
virtual TObject<IReflect>& operator () (IReflect& reflect) {
ReflectClass(Derived)[Interface(MarshallInfo)];
if (reflect.IsReflectProperty()) {
ReflectProperty(ch);
ReflectProperty(extra);
}
return *this;
}
char ch;
String extra;
};
#include "../../../Driver/Filter/Pod/ZFilterPod.h"
bool Serialization::Initialize() {
Creatable<MyType>::Init();
return true;
}
bool Serialization::Run(int randomSeed, int length) {
MarshallInfo info;
info.name = "HAHA";
info.value = 123;
info.test = 0.5;
info.mytype.hi = "Hello, world!";
info.mytype2.hi = "ALOHA";
info.arr.push_back(1);
info.arr.push_back(3);
MyType s;
s.hi = "In Container";
MyType t;
t.hi = "ArrString";
info.arrmytype.push_back(t);
info.arrmytype.push_back(t);
MyType* d = new MyType();
d->hi = "Dynamic!!";
info.dynType = d;
MyType* vec = new MyType();
vec->hi = "Vectorized~!";
info.dynVector.push_back(vec);
Derived derived;
derived.name = "Derived";
derived.value = 456;
derived.test = 0.3;
derived.mytype.hi = "MyTYPE";
derived.mytype2.hi = "HI2";
derived.ch = 'a';
derived.extra = "Extra";
ZMemoryStream stream(0x1000, true);
ZFilterPod pod;
IStreamBase* filter = pod.CreateFilter(stream);
// NoFilter filter;
*filter << info;
*filter << derived;
filter->ReleaseObject();
MarshallInfo target;
Derived targetDerived;
String str;
stream.Seek(IStreamBase::BEGIN, 0);
IStreamBase* filterAgain = pod.CreateFilter(stream);
*filterAgain >> target;
*filterAgain >> targetDerived;
filterAgain->ReleaseObject();
return true;
}
void Serialization::Summary() {
}
TObject<IReflect>& Serialization::operator () (IReflect& reflect) {
ReflectClass(Serialization);
return *this;
} | [
"[email protected]"
]
| |
aba00e354c8cf6d414c1206ff66491af143c375b | 33a92a350d18515613a7c5bac8518556c2c1d799 | /VS 2012/小甲鱼Win SDK/015窗口绘画/015窗口绘画/stdafx.cpp | 034ecb37b09437a31aae2fe86666b85bd6fd5d2b | []
| no_license | WemtFox/MyLearningCode | 7b35345524f7cc047e364ab3d9f54892776213fa | e7df5692ea57756ae9563a84a5345e0b688c470d | refs/heads/master | 2020-04-12T07:50:30.255469 | 2015-12-05T01:47:40 | 2015-12-05T01:47:40 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 267 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// 015窗口绘画.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用
| [
"[email protected]"
]
| |
604f4573c95b2c5afae38b858f42858c55975921 | 0b75287e40702c3d0a2d8e40a8a30634b9a7e14b | /HeapSort.h | 7ac420cc77ef6c4cd3ad17baebfe3a6c1c76402d | []
| no_license | MartinKarlikov/StudentDataSorting | 4efe68fb95141da8eac4e261e634b490a084329c | 081a6f277d568fe37091bac38cf95c148a242b33 | refs/heads/master | 2020-03-15T11:53:48.774787 | 2018-06-21T11:19:59 | 2018-06-21T11:19:59 | 132,131,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,813 | h | #pragma once
#include "DynamicArray.h"
#include "StudentData.h"
//Basic heapsort , nothing special
//uses the siftDown technique
template <typename T>
void ArrSwap(DynamicArray<StudentData<T>>& array, size_t firstIndex, size_t secondIndex)
{
StudentData<T> temp = array[firstIndex];
array[firstIndex] = array[secondIndex];
array[secondIndex] = temp;
}
size_t findParent(size_t index);
size_t findLeftChild(size_t index);
size_t findRightChild(size_t index);
template <typename T>
void heapsort(DynamicArray<StudentData<T>>& toSort, size_t size);
template <typename T>
void heapify(DynamicArray<StudentData<T>>& toheapify, size_t size);
template <typename T>
void siftDown(DynamicArray<StudentData<T>>& toFix, size_t start, size_t end);
template<typename T>
inline void heapsort(DynamicArray<StudentData<T>>& toSort, size_t size)
{
heapify(toSort, size);
size_t end = size - 1;
while (end > 0)
{
ArrSwap(toSort, end, 0);
end--;
siftDown(toSort, 0, end);
}
}
template<typename T>
inline void heapify(DynamicArray<StudentData<T>>& toheapify, size_t size)
{
int start = findParent(size - 1);
while (start >= 0)
{
siftDown(toheapify, start, size - 1);
start--;
}
}
template<typename T>
inline void siftDown(DynamicArray<StudentData<T>>& toFix, size_t start, size_t end)
{
size_t root = start;
size_t swap, child;
while (findLeftChild(root) <= end)
{
child = findLeftChild(root);
swap = root;
if (toFix[swap] < toFix[child])
{
swap = child;
}
if (child + 1 <= end && toFix[swap] < toFix[child + 1])
{
swap = child + 1;
}
if (swap == root)
{
return;
}
else
{
ArrSwap(toFix, root, swap);
root = swap;
}
}
}
| [
"[email protected]"
]
| |
849de9feeaa78f21512b1b97ef6248bb72970f42 | 682838aa69ccbf57be2ae2690737f072c0fdc5b5 | /libraries/IrRanger/IrRanger.ino | bc2d6b4f92a0e0bfb623dcec01bea8f2bad42f40 | []
| no_license | SuperheRos52/sketchbook | 3a6e4603a61f0fd2d0195532beb4bd923e2fe78e | 3c13a97120d2a4a9f48dd9001382eee2bf194dbe | refs/heads/master | 2021-01-19T06:34:17.006015 | 2015-08-13T15:36:23 | 2015-08-13T15:36:23 | 40,664,262 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,442 | ino | /*
* rosserial IR Ranger Example
*
* This example is calibrated for the Sharp GP2D120XJ00F.
*/
#include <ros.h>
#include <ros/time.h>
#include <sensor_msgs/Range.h>
ros::NodeHandle nh;
sensor_msgs::Range range_msg;
ros::Publisher pub_range( "range_data", &range_msg);
const int analog_pin = 8;
unsigned long range_timer;
char frameid[] = "/ir_ranger";
float v_ref = 5.0;
float adc_max = 1024.0;
float voltage_slope = (v_ref/adc_max);
float equation_offset = 0.1836092228;
float equation_slope = 2.5513414751;
float calibration_offset = 0.02;
float voltage, meter = 0.0;
float get_distance(int pin_num)
{
int sample = analogRead(pin_num);
voltage = sample * voltage_slope;
// equation: a(x) = mx + b with a = 1/y
// -> x(y) = (1/y - b) / m
meter = ((1/voltage) - equation_offset) / equation_slope;
return meter;
}
void setup()
{
nh.initNode();
nh.advertise(pub_range);
range_msg.radiation_type = sensor_msgs::Range::INFRARED;
range_msg.header.frame_id = frameid;
range_msg.field_of_view = 0.01;
range_msg.min_range = 0.1;
range_msg.max_range = 0.8;
}
void loop()
{
// publish the range value every 50 milliseconds
// since it takes that long for the sensor to stabilize
if ( (millis() - range_timer) > 50){
range_msg.range = get_distance(analog_pin);
range_msg.header.stamp = nh.now();
pub_range.publish(&range_msg);
range_timer = millis();
}
nh.spinOnce();
}
| [
"[email protected]"
]
| |
33871a72f7664512b4867fc9935b4daf557bd8b4 | 8b5d24bb19bed33ffbbc50b0a8fb34ed60496da3 | /jollaImport/catcher.h | 57a93379330afcb9b5d032cc0f4aa282918c5f5e | []
| no_license | sailfishapps/Harmattan-SMS-Boat | cc96dc34e4c8c12a3ff7267b937c90b46f6fecec | 719104dfa23f47355ad1c91c558bc0a4d2154af9 | refs/heads/master | 2020-05-29T12:15:07.209889 | 2013-12-26T01:04:54 | 2013-12-26T01:04:54 | 15,454,709 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,379 | h | /******************************************************************************
**
** This file is part of libcommhistory.
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Reto Zingg <[email protected]>
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of the GNU Lesser General Public License version 2.1 as
** published by the Free Software Foundation.
**
** This library is distributed in the hope that it will be useful, but
** WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
** or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
** License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this library; if not, write to the Free Software Foundation, Inc.,
** 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
**
******************************************************************************/
#ifndef CATCHER_H
#define CATCHER_H
#include <QObject>
#include <QList>
#include <QCoreApplication>
#include <QDebug>
#include <CommHistory/EventModel>
namespace CommHistory {
class GroupModel;
};
class Catcher : public QObject
{
Q_OBJECT
public:
Catcher(CommHistory::EventModel *model) : ok(true), stop(false) {
connect(model, SIGNAL(eventsCommitted(QList<CommHistory::Event>,bool)),
this, SLOT(eventsCommittedSlot(QList<CommHistory::Event>,bool)));
};
Catcher(CommHistory::GroupModel *model) : ok(true), stop(false) {
connect((QObject*)model, SIGNAL(groupsCommitted(QList<int>,bool)),
this, SLOT(groupsCommittedSlot(QList<int>,bool)));
};
void reset() {
ok = true;
stop = false;
}
void waitCommit(void) {
while(!stop) {
qDebug() << ".";
QCoreApplication::instance()->processEvents(QEventLoop::WaitForMoreEvents);
}
};
bool ok;
bool stop;
public Q_SLOTS:
void eventsCommittedSlot(QList<CommHistory::Event> committedEvents, bool success) {
Q_UNUSED(committedEvents);
ok = success;
stop = true;
};
void groupsCommittedSlot(QList<int> committedGroups, bool success) {
Q_UNUSED(committedGroups);
ok = success;
stop = true;
}
};
#endif // CATCHER_H
| [
"[email protected]"
]
| |
820a8ecdadfee8915eef2ac8fcd79c09a360503d | 54e1a786248dde2ac0143d261f69a0c0ad843b7f | /LhaForge/Dialogs/SevenZipVolumeSizeDlg.h | 01f382b7561ea67e41951f0a5f625a4bde4275f4 | []
| no_license | killvxk/lhaforge | 0cc741e8143df2205fa88869b6f42c59ff1fd0bd | 3cf98291f08de1e5c0f492115f54f3e89f99ab0c | refs/heads/master | 2020-04-25T04:11:10.360033 | 2013-05-31T16:17:20 | 2013-05-31T16:17:20 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,327 | h | /*
* Copyright (c) 2005-2012, Claybird
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Claybird nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#pragma once
const struct tagZIPVOLUMEUNIT{
LPCTSTR DispName;
LPCTSTR ParamName;
}ZIP_VOLUME_UNIT[]={
{_T("MB"),_T("m")},
{_T("KB"),_T("k")},
{_T("GB"),_T("g")},
{_T("Byte"),_T("b")}
};
const int ZIP_VOLUME_UNIT_MAX_NUM=COUNTOF(ZIP_VOLUME_UNIT);
class C7Zip32VolumeSizeDialog : public CDialogImpl<C7Zip32VolumeSizeDialog>,public CWinDataExchange<C7Zip32VolumeSizeDialog>
{
protected:
public:
int VolumeSize;
int SelectIndex;
CComboBox Combo_VolumeUnit;
enum {IDD = IDD_DIALOG_7Z_VOLUME_SIZE};
// DDXマップ
BEGIN_DDX_MAP(C7Zip32VolumeSizeDialog)
DDX_INT(IDC_EDIT_7Z_VOLUME_SIZE, VolumeSize)
END_DDX_MAP()
// メッセージマップ
BEGIN_MSG_MAP_EX(C7Zip32VolumeSizeDialog)
MSG_WM_INITDIALOG(OnInitDialog)
COMMAND_ID_HANDLER_EX(IDOK, OnOK)
COMMAND_ID_HANDLER_EX(IDCANCEL, OnCancel)
END_MSG_MAP()
LRESULT OnInitDialog(HWND hWnd, LPARAM lParam){
Combo_VolumeUnit=GetDlgItem(IDC_COMBO_7Z_VOLUME_UNIT);
SelectIndex=0;
for(int i=0;i<ZIP_VOLUME_UNIT_MAX_NUM;i++){
Combo_VolumeUnit.InsertString(-1,ZIP_VOLUME_UNIT[i].DispName);
}
Combo_VolumeUnit.SetCurSel(0);
return TRUE;
}
void OnOK(UINT uNotifyCode, int nID, HWND hWndCtl){
if(!DoDataExchange(TRUE)){
return;
}
if(VolumeSize<=0){
::SetFocus(GetDlgItem(IDC_EDIT_7Z_VOLUME_SIZE));
::SendMessage(GetDlgItem(IDC_EDIT_7Z_VOLUME_SIZE),EM_SETSEL,0,-1);
ErrorMessage(CString(MAKEINTRESOURCE(IDS_ERROR_VALUE_MUST_BE_PLUS)));
return;
}
SelectIndex=Combo_VolumeUnit.GetCurSel();
if(SelectIndex<0||SelectIndex>=ZIP_VOLUME_UNIT_MAX_NUM)return;
EndDialog(nID);
}
void OnCancel(UINT uNotifyCode, int nID, HWND hWndCtl){
EndDialog(nID);
}
};
| [
"[email protected]"
]
| |
1735473f658b514ee99f3bc5c915b2f3c43dca09 | a4283571eb440b2027527740309133630738e4dc | /src/bitcoind.cpp | d13d389d1e5cda81b43527fa4988fd38b8c1da58 | [
"MIT"
]
| permissive | gelinDevs/Gelin | 1672392fb7cb4a303c3d9919bc1dd462f7c61376 | a5b851adc6f7a84898e6b7b5cc6f876134b0aa92 | refs/heads/master | 2020-03-09T19:11:02.000239 | 2018-04-12T11:34:54 | 2018-04-12T11:34:54 | 125,657,989 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,200 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "rpcclient.h"
#include "init.h"
#include <boost/algorithm/string/predicate.hpp>
void WaitForShutdown(boost::thread_group* threadGroup)
{
bool fShutdown = ShutdownRequested();
// Tell the main threads to shutdown.
while (!fShutdown)
{
MilliSleep(200);
fShutdown = ShutdownRequested();
}
if (threadGroup)
{
threadGroup->interrupt_all();
threadGroup->join_all();
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
bool fRet = false;
fHaveGUI = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
Shutdown();
}
ReadConfigFile(mapArgs, mapMultiArgs);
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to bitcoind / RPC client
std::string strUsage = _("Gelin version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" Gelind [options] " + "\n" +
" Gelind [options] <command> [params] " + _("Send command to -server or Gelind") + "\n" +
" Gelind [options] help " + _("List commands") + "\n" +
" Gelind [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "Gelin:"))
fCommandLine = true;
if (fCommandLine)
{
if (!SelectParamsFromCommandLine()) {
fprintf(stderr, "Error: invalid combination of -regtest and -testnet.\n");
return false;
}
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
#if !WIN32
fDaemon = GetBoolArg("-daemon", false);
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
CreatePidFile(GetPidFile(), pid);
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
fRet = AppInit2(threadGroup);
}
catch (std::exception& e) {
PrintException(&e, "AppInit()");
} catch (...) {
PrintException(NULL, "AppInit()");
}
if (!fRet)
{
threadGroup.interrupt_all();
// threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
// the startup-failure cases to make sure they don't result in a hang due to some
// thread-blocking-waiting-for-another-thread-during-startup case
} else {
WaitForShutdown(&threadGroup);
}
Shutdown();
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
// Connect bitcoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return (fRet ? 0 : 1);
}
| [
"[email protected]"
]
| |
ecd185b5998990fcec541bd4c9be2380567db481 | 6c9bd50bdc4790c77d4840483cd126bea3c730f3 | /2nd semester/Data-structures-and-algorithms/Laboratories/Assignment 4 P21/main.cpp | 6dc1c266c06c3f25942de6ce4a05a5073fe8ff26 | []
| no_license | toadereandreas/Babes-Bolyai-University | b9689951b88cce195726417ec55f0ced1aa4b8e6 | ca6269864e5ade872cb5522a3ceb94a206e207b3 | refs/heads/master | 2022-09-24T13:11:03.610221 | 2020-06-04T12:19:12 | 2020-06-04T12:19:12 | 268,924,167 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,712 | cpp | #include <iostream>
#include <assert.h>
#include "SLLA.h"
#include "SLLA_iterator.h"
#include "SortedMultiMap.h"
bool cond1(TElem x){
if( x.first <= 8 ) return true;
return false;
}
bool relation1(TKey cheie1, TKey cheie2) {
if (cheie1 <= cheie2) {
return true;
}
else {
return false;
}
}
bool asc(TKey c1, TKey c2) {
if (c1 <= c2) {
return true;
} else {
return false;
}
}
bool desc(TKey c1, TKey c2) {
if (c1 >= c2) {
return true;
} else {
return false;
}
}
void testCreate() {
SortedMultiMap smm = SortedMultiMap(asc);
assert(smm.size() == 0);
assert(smm.isEmpty());
for (int i = 0; i < 10; i++) {
vector<TValue> v= smm.search(i);
assert(v.size()==0);
}
for (int i = -10; i < 10; i++) {
vector<TValue> v= smm.search(i);
assert(v.size()==0);
}
}
void testSearch(Relation r) {
SortedMultiMap smm = SortedMultiMap(r);
int kMin = 0;
int kMax = 10;
for (int i = kMin; i <= kMax; i++) {
smm.add(i, i + 1);
smm.add(i, i + 2);
}
int intervalDim = 10;
for (int i = kMin; i <= kMax; i++) {
vector<TValue> v= smm.search(i);
assert(v.size()==2);
}
for (int i = kMin - intervalDim; i < kMin; i++) {
vector<TValue> v= smm.search(i);
assert(v.size()==0);
}
for (int i = kMax + 1; i < kMax + intervalDim; i++) {
vector<TValue> v= smm.search(i);
assert(v.size()==0);
}
}
void testSearch() {
testSearch(asc);
testSearch(desc);
}
void populateSMMEmpty(SortedMultiMap& smm, int min, int max) {
for (int i = min; i <= max; i++) {
smm.add(i, i);
if (i%2 ==0)
smm.add(i, i+2);
}
}
void testRemoveSearch(Relation r) {
SortedMultiMap smm = SortedMultiMap(r);
int min = 10;
int max = 20;
populateSMMEmpty(smm, min, max);
for (int c = min; c <= max; c++) {
assert(smm.remove(c, c+1) == false);
if (c%2==0)
assert(smm.remove(c,c) == true);
}
for (int c = min; c <= max; c++) {
if (c%2==1){
assert(smm.remove(c,c+1) == false);
assert(smm.remove(c,c) == true);
}
else{
assert(smm.remove(c,c+2) == true);
}
}
assert(smm.size() == 0);
}
void testRemove() {
testRemoveSearch(asc);
testRemoveSearch(desc);
}
vector<int> randomKeys(int kMin, int kMax) {
vector<int> keys;
for (int c = kMin; c <= kMax; c++) {
keys.push_back(c);
}
int n = keys.size();
for (int i = 0; i < n - 1; i++) {
int j = i + rand() % (n - i);
swap(keys[i], keys[j]);
}
return keys;
}
void testIterator(Relation r) {
SortedMultiMap smm = SortedMultiMap(r);
SMMIterator it = smm.iterator();
assert(!it.valid());
it.first();
assert(!it.valid());
int cMin = 100;
int cMax = 300;
vector<int> keys = randomKeys(cMin, cMax);
int n = keys.size();
for (int i = 0; i < n; i++) {
smm.add(keys[i], 100);
if (keys[i]%2==0) {
smm.add(keys[i], 200);
}
}
SMMIterator itsmm = smm.iterator();
assert(itsmm.valid());
itsmm.first();
assert(itsmm.valid());
TKey kPrev = itsmm.getCurrent().first;
itsmm.next();
while (itsmm.valid()) {
TKey k = itsmm.getCurrent().first;
kPrev = k;
itsmm.next();
}
}
void testIterator() {
testIterator(asc);
testIterator(desc);
}
void testAllExtended() {
testCreate();
testSearch();
testRemove();
testIterator();
}
void testAll(){
SortedMultiMap smm = SortedMultiMap(relation1);
assert(smm.size() == 0);
assert(smm.isEmpty());
smm.add(1,2);
smm.add(1,3);
assert(smm.size() == 2);
assert(!smm.isEmpty());
vector<TValue> v= smm.search(1);
assert(v.size()==2);
v= smm.search(3);
assert(v.size()==0);
SMMIterator it = smm.iterator();
it.first();
while (it.valid()){
TElem e = it.getCurrent();
it.next();
}
assert(smm.remove(1, 2) == true);
assert(smm.remove(1, 3) == true);
assert(smm.remove(2, 1) == false);
assert(smm.isEmpty());
}
int main() {
testAll();
testAllExtended();
SortedMultiMap x(relation1);
x.add(2,2);
x.add(10,3);
x.add(3,3);
x.add(7,3);
x.add(6,3);
x.add(9,9);
x.add(0,4);
x.add(9,8);
x.add(10,6);
x.add(11,10);
cout << "Initial values and size : " << x.size() << '\n';
x.print();
x.filter(cond1);
cout << "After filtering with key <= 8: Size : " << x.size() << '\n';
x.print();
return 0;
}
| [
"[email protected]"
]
| |
50fc117a7fc71625937b1fa721100abd90da77fa | e01454c3f0e75207123d38171daabd90be5cc9c1 | /testnote.h | 19d8364cfac07307cb128aa23d6e4657b8b083ef | []
| no_license | sedoy-jango-2/Coffe-check | b242e36cce8f3c9b227c9fb3bee8bfccfe29e35d | 606bd1f93411938069a7247ea11d078be2d0a226 | refs/heads/master | 2021-08-11T10:19:10.765317 | 2017-11-13T14:54:52 | 2017-11-13T14:54:52 | 110,551,403 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 739 | h | #ifndef TESTNOTE_H
#define TESTNOTE_H
#include <QString>
#include <stdio.h>
#include <stdlib.h>
#include <QStringList>
#include <QString>
#include <iostream>
#include <basenote.h>
class TestNote: public BaseNote
{
public:
TestNote();
TestNote(const TestNote ©write);
TestNote(
QString current_hours,
QString current_minutes,
QString current_day,
QString current_month,
QString current_year,
QString current_countOfCoffee
);
~TestNote();
int getCountOfCoffee();
void setCountOfCoffee(QString setmentCountOfCoffee);
virtual int getType();
virtual void show();
protected:
int countOfCoffee;
};
#endif // TESTNOTE_H
| [
"[email protected]"
]
| |
e44f77b56c1793f0bb7b894345ff334bb7b29cdc | ad74f7a42e8dec14ec7576252fcbc3fc46679f27 | /MediaMaker/ID3v2TagFrameHeader.h | 02a00e2f6b18c59db499a9ae5a0cebfd1fd7cddd | []
| no_license | radtek/TrapperKeeper | 56fed7afa259aee20d6d81e71e19786f2f0d9418 | 63f87606ae02e7c29608fedfdf8b7e65339b8e9a | refs/heads/master | 2020-05-29T16:49:29.708375 | 2013-05-15T08:33:23 | 2013-05-15T08:33:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 523 | h | // ID3v2TagFrameHeader.h
#ifndef ID3V2_TAG_FRAME_HEADER_H
#define ID3V2_TAG_FRAME_HEADER_H
class ID3v2TagFrameHeader
{
public:
ID3v2TagFrameHeader();
void Clear();
void ExtractFrameHeaderPointer(unsigned char *ptr);
unsigned char *ReturnFrameIDPointer();
unsigned int ReturnFrameSize();
void SetFrameID(char *id);
void SetFrameSize(unsigned int size);
private:
unsigned char m_frame_id[4];
unsigned char m_size[4]; // not synch safe integers
unsigned char m_flags[2];
};
#endif // ID3V2_TAG_FRAME_HEADER_H | [
"[email protected]"
]
| |
5e402ffa5d5ba017bd23d0b3838aab8f30a23028 | 2c5e0a3e492d854df0c823f19376ae33c95a9f2c | /Source/head/q8.h | 8f93f6a8c7f11d16c5b30a6d8ff0ffbf2ded32ed | [
"MIT"
]
| permissive | FWdarling/DS_homework | 0cc8a21f962500ad5c4a029be60c8d027c7035e3 | 26f43a25aba400c214855a57b4e87fa53ae51d97 | refs/heads/master | 2020-07-28T08:28:39.003919 | 2019-12-23T20:21:56 | 2019-12-23T20:21:56 | 209,364,876 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,389 | h | #include"../../Lab/prim.h"
using std::cin;
using std::cout;
using std::endl;
void instructions(){
cout << "You can choose the following actions:" << endl;
cout << "A is creating grid vertex" << endl;
cout << "B is adding grid edges" << endl;
cout << "C is Generating shortest grid" << endl;
cout << "D is displaying grid" << endl;
cout << "Q is quiting the system" << endl;
cout << endl;
cout << "Please input your operation: ";
}
int32_t find_index(char c, Vector<char> &v){
for(int32_t i = 0; i < v.get_size(); i++){
if(c == v[i]) return i;
}
cout << "Incorrect point entered!" << endl;
return -1;
}
void add_edge(MST& grid, int32_t n, Vector<char> &v){
for(int32_t i = 0; i < n; i++){
cout << "Please enter two vertices and edge: ";
char ori, tar;
int32_t len;
cin >> ori >> tar >> len;
grid.input(find_index(ori, v), find_index(tar, v), len);
}
}
void generate(MST& grid, char start, Vector<char> &v){
grid.generate(find_index(start, v));
}
void display(MST& grid, Vector<char> &v){
Vector<Edge> mst = grid.get_mst();
for(int32_t i = 0; i < mst.get_len(); i++){
char ori = v[mst[i].get_ori()];
char tar = v[mst[i].get_tar()];
int32_t len = mst[i].get_len();
cout << ori << "-<" << len << ">->" << tar << endl;
}
return;
}
| [
"[email protected]"
]
| |
20be7732b2fac3c1833d33c5182b9b6b60724781 | 8fd426c0755306b7fad2446b51d1cbf6af41a7f3 | /Empty SFML1/Empty SFML1/State.h | b3a16c4e212c7fe2c223386b1d566c560d1e7b29 | []
| no_license | MartinFarrell24/FiniteStateMachine | 1f073d5cefea29e883ba492ca4ce466950779db6 | 3ccdcb170125ce271bdc2437117f163ec1c37f25 | refs/heads/master | 2021-07-25T21:38:58.744381 | 2017-11-08T17:58:12 | 2017-11-08T17:58:12 | 108,397,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 774 | h | #pragma once
/// <summary>
/// @Author Martin Farrell c00157047
/// Date: Nov 8th 2017
/// Num of hrs: 3
/// </summary>
/// No known bugs
#include<iostream>
#include"Animation.h"
using namespace std;
class State
{
public:
virtual void idle(Animation* a)
{
cout << "State::Idling" << endl;
}
virtual void jumping(Animation* a)
{
cout << "State::Jumping" << endl;
}
virtual void climbing(Animation* a)
{
cout << "State::Climbing" << endl;
}
virtual void swordsmanship(Animation* a)
{
cout << "State::Swordsmanship" << endl;
}
virtual void shovelling(Animation* a)
{
cout << "State::Swordsmanship" << endl;
}
virtual void hammering(Animation* a)
{
cout << "State::Swordsmanship" << endl;
}
};
| [
"[email protected]"
]
| |
9c5106b7210870dfb48aa9f582bd0b6cf8a96493 | a57cc4f074203e8ceefa3285a1a72b564e831eae | /tests/unit_tests/mul_div.cpp | 5b0a74bffb79fc51274acac066d80b812729edd8 | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | trublud/kickasscoin | 286b2c9637bf92416d8e2017c6c0c15a25f8ebc8 | 8153ff2f1fe8f3a761b71eab9afb1b02876809d5 | refs/heads/master | 2020-06-19T15:58:58.218099 | 2019-07-13T23:04:47 | 2019-07-13T23:04:47 | 194,447,129 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,695 | cpp | // Copyright (c) 2014-2019, The KickAssCoin Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include "gtest/gtest.h"
#include "int-util.h"
namespace
{
TEST(mul128, handles_zero)
{
uint64_t hi, lo;
lo = mul128(0, 0, &hi);
ASSERT_EQ(lo, 0);
ASSERT_EQ(hi, 0);
lo = mul128(7, 0, &hi);
ASSERT_EQ(lo, 0);
ASSERT_EQ(hi, 0);
lo = mul128(0, 7, &hi);
ASSERT_EQ(lo, 0);
ASSERT_EQ(hi, 0);
}
TEST(mul128, handles_one)
{
uint64_t hi, lo;
lo = mul128(1, 1, &hi);
ASSERT_EQ(lo, 1);
ASSERT_EQ(hi, 0);
lo = mul128(7, 1, &hi);
ASSERT_EQ(lo, 7);
ASSERT_EQ(hi, 0);
lo = mul128(1, 7, &hi);
ASSERT_EQ(lo, 7);
ASSERT_EQ(hi, 0);
}
TEST(mul128_without_carry, multiplies_correctly)
{
uint64_t hi, lo;
lo = mul128(0x3333333333333333, 5, &hi);
ASSERT_EQ(lo, 0xffffffffffffffff);
ASSERT_EQ(hi, 0);
lo = mul128(5, 0x3333333333333333, &hi);
ASSERT_EQ(lo, 0xffffffffffffffff);
ASSERT_EQ(hi, 0);
lo = mul128(0x1111111111111111, 0x1111111111111111, &hi);
ASSERT_EQ(lo, 0x0fedcba987654321);
ASSERT_EQ(hi, 0x0123456789abcdf0);;
}
TEST(mul128_with_carry_1_only, multiplies_correctly)
{
uint64_t hi, lo;
lo = mul128(0xe0000000e0000000, 0xe0000000e0000000, &hi);
ASSERT_EQ(lo, 0xc400000000000000);
ASSERT_EQ(hi, 0xc400000188000000);
}
TEST(mul128_with_carry_2_only, multiplies_correctly)
{
uint64_t hi, lo;
lo = mul128(0x10000000ffffffff, 0x10000000ffffffff, &hi);
ASSERT_EQ(lo, 0xdffffffe00000001);
ASSERT_EQ(hi, 0x0100000020000000);
}
TEST(mul128_with_carry_1_and_2, multiplies_correctly)
{
uint64_t hi, lo;
lo = mul128(0xf1f2f3f4f5f6f7f8, 0xf9f0fafbfcfdfeff, &hi);
ASSERT_EQ(lo, 0x52118e5f3b211008);
ASSERT_EQ(hi, 0xec39104363716e59);
lo = mul128(0xffffffffffffffff, 0xffffffffffffffff, &hi);
ASSERT_EQ(lo, 0x0000000000000001);
ASSERT_EQ(hi, 0xfffffffffffffffe);
}
TEST(div128_32, handles_zero)
{
uint32_t reminder;
uint64_t hi;
uint64_t lo;
reminder = div128_32(0, 0, 7, &hi, &lo);
ASSERT_EQ(reminder, 0);
ASSERT_EQ(hi, 0);
ASSERT_EQ(lo, 0);
// Division by zero is UB, so can be tested correctly
}
TEST(div128_32, handles_one)
{
uint32_t reminder;
uint64_t hi;
uint64_t lo;
reminder = div128_32(0, 7, 1, &hi, &lo);
ASSERT_EQ(reminder, 0);
ASSERT_EQ(hi, 0);
ASSERT_EQ(lo, 7);
reminder = div128_32(7, 0, 1, &hi, &lo);
ASSERT_EQ(reminder, 0);
ASSERT_EQ(hi, 7);
ASSERT_EQ(lo, 0);
}
TEST(div128_32, handles_if_dividend_less_divider)
{
uint32_t reminder;
uint64_t hi;
uint64_t lo;
reminder = div128_32(0, 1383746, 1645825, &hi, &lo);
ASSERT_EQ(reminder, 1383746);
ASSERT_EQ(hi, 0);
ASSERT_EQ(lo, 0);
}
TEST(div128_32, handles_if_dividend_dwords_less_divider)
{
uint32_t reminder;
uint64_t hi;
uint64_t lo;
reminder = div128_32(0x5AD629E441074F28, 0x0DBCAB2B231081F1, 0xFE735CD6, &hi, &lo);
ASSERT_EQ(reminder, 0xB9C924E9);
ASSERT_EQ(hi, 0x000000005B63C274);
ASSERT_EQ(lo, 0x9084FC024383E48C);
}
TEST(div128_32, works_correctly)
{
uint32_t reminder;
uint64_t hi;
uint64_t lo;
reminder = div128_32(2, 0, 2, &hi, &lo);
ASSERT_EQ(reminder, 0);
ASSERT_EQ(hi, 1);
ASSERT_EQ(lo, 0);
reminder = div128_32(0xffffffffffffffff, 0, 0xffffffff, &hi, &lo);
ASSERT_EQ(reminder, 0);
ASSERT_EQ(hi, 0x0000000100000001);
ASSERT_EQ(lo, 0);
reminder = div128_32(0xffffffffffffffff, 5846, 0xffffffff, &hi, &lo);
ASSERT_EQ(reminder, 5846);
ASSERT_EQ(hi, 0x0000000100000001);
ASSERT_EQ(lo, 0);
reminder = div128_32(0xffffffffffffffff - 1, 0, 0xffffffff, &hi, &lo);
ASSERT_EQ(reminder, 0xfffffffe);
ASSERT_EQ(hi, 0x0000000100000000);
ASSERT_EQ(lo, 0xfffffffefffffffe);
reminder = div128_32(0x2649372534875028, 0xaedbfedc5adbc739, 0x27826534, &hi, &lo);
ASSERT_EQ(reminder, 0x1a6dc2e5);
ASSERT_EQ(hi, 0x00000000f812c1f8);
ASSERT_EQ(lo, 0xddf2fdb09bc2e2e9);
}
}
| [
"[email protected]"
]
| |
55628c6880242c0c3212805ce1c2b5c474f8cbd8 | 9079a555d1fd22ad9701227c58151ae1ca3595d3 | /Codechef/CLUSCL.cpp | 71a8e603f3a225eb6ad0137f653809704e699754 | []
| no_license | DebRC/My-Competitve-Programming-Solutions | c2a03b18f15cebd3793ce1c288dbb51fc0a33ef4 | fe956eed619a21bd24a5fd647791d4c56cd1b021 | refs/heads/main | 2023-02-04T08:28:13.915967 | 2020-12-28T09:11:29 | 2020-12-28T09:11:29 | 324,591,343 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,081 | cpp | #include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#define ll long long
#define M 1000000007
#define sz(a) (ll)a.size()
#define pll pair<ll,ll>
#define rep(i,a,b) for(ll i=(ll)a;i<(ll)b;i++)
#define sep(i,a,b) for(ll i=(ll)a;i>=(ll)b;i--)
#define mll map<ll,ll>
#define vl vector<ll>
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define all(a) a.begin(),a.end()
#define F first
#define S second
using namespace __gnu_pbds;
using namespace std;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
ll f(ll p,ll q)
{
return p/q+1;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
ll t,p,q,n;
cin>>t;
while(t--)
{
cin>>p>>q>>n;
//if((2*abs(p-q))%q==0)
cout<<f((n-1)*q,2*abs(p-q))<<"\n";
//else if(((n-1)*q)%(2*abs(p-q))==0)
// cout<<(n-1)*q/(2*abs(p-q))+1<<"\n";
//else
// cout<<f(n*q,2*abs(p-q))<<"\n";
}
}
| [
"[email protected]"
]
| |
c969b832530ce4bbc328a22354f1c3bf2125f0a6 | 96dbdaeb27f33b006ce3ca876ee53fcf00c0e7ac | /sayi.cpp | df4d08c396fa99247844fe9f14a4e72c617eabd4 | []
| no_license | fatihinz/C_course | 56aa74626a69d69058d42f6ce3e82768d8db884a | 3d767981fc3fab7122abb596d54513f4def93549 | refs/heads/master | 2021-07-16T09:15:07.493223 | 2020-06-08T15:59:54 | 2020-06-08T15:59:54 | 165,135,335 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 202 | cpp | #include <stdio.h>
int main(){
int n;
printf("bir sayi giriniz :");
scanf("%d",&n);
int i;
int c=0;
for(i=1;i<n;i=i*2){
c++;
printf("%di, %dn,%dc \n",i,n,c);
}
printf("%d\n",c);
}
| [
"[email protected]"
]
| |
9fe9b44d5e3035e72f00e7589caa8d31df2ce1ed | e53fc7abb5a40fee791d3a0b5fac83ab36196a39 | /Intermediate/Build/Win64/UE4Editor/Inc/BuildingEscape/PositionReport.gen.cpp | 5b774e16dfa96668b57af07136e8c7f43ac64565 | []
| no_license | CesarChaMal/UnrealSection_03_BuildingEscape | 9eb39e0306b60273d651286038efb04c65e9f879 | 4d8472da2398e437575e016a49304a13a25488c2 | refs/heads/master | 2022-08-02T17:26:12.879198 | 2020-05-24T02:24:41 | 2020-05-24T02:24:41 | 263,173,186 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,326 | cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "BuildingEscape/PositionReport.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodePositionReport() {}
// Cross Module References
BUILDINGESCAPE_API UClass* Z_Construct_UClass_UPositionReport_NoRegister();
BUILDINGESCAPE_API UClass* Z_Construct_UClass_UPositionReport();
ENGINE_API UClass* Z_Construct_UClass_UActorComponent();
UPackage* Z_Construct_UPackage__Script_BuildingEscape();
// End Cross Module References
void UPositionReport::StaticRegisterNativesUPositionReport()
{
}
UClass* Z_Construct_UClass_UPositionReport_NoRegister()
{
return UPositionReport::StaticClass();
}
struct Z_Construct_UClass_UPositionReport_Statics
{
static UObject* (*const DependentSingletons[])();
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_UPositionReport_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_UActorComponent,
(UObject* (*)())Z_Construct_UPackage__Script_BuildingEscape,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UPositionReport_Statics::Class_MetaDataParams[] = {
{ "BlueprintSpawnableComponent", "" },
{ "ClassGroupNames", "Custom" },
{ "IncludePath", "PositionReport.h" },
{ "ModuleRelativePath", "PositionReport.h" },
};
#endif
const FCppClassTypeInfoStatic Z_Construct_UClass_UPositionReport_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<UPositionReport>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UPositionReport_Statics::ClassParams = {
&UPositionReport::StaticClass,
"Engine",
&StaticCppClassTypeInfo,
DependentSingletons,
nullptr,
nullptr,
nullptr,
ARRAY_COUNT(DependentSingletons),
0,
0,
0,
0x00B000A4u,
METADATA_PARAMS(Z_Construct_UClass_UPositionReport_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_UPositionReport_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_UPositionReport()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UPositionReport_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(UPositionReport, 2151782);
template<> BUILDINGESCAPE_API UClass* StaticClass<UPositionReport>()
{
return UPositionReport::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UPositionReport(Z_Construct_UClass_UPositionReport, &UPositionReport::StaticClass, TEXT("/Script/BuildingEscape"), TEXT("UPositionReport"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UPositionReport);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| [
"[email protected]"
]
| |
a16ba9c21511b3a49b0f0d8f03d2d5c40827516d | 5c8645d9c4deee4e77c7a9ca649d24c49794ce6f | /CPP/801-900/Q827. Making A Large Island.cpp | 34c2a83cf33b3e8d5ceaaa9fd3d9dd6e31c22849 | []
| no_license | XiandaChen/LeetCode | 51e9c851f739a5e47195745a2dddc87462a0efbf | fb8b5c67b3876f4a6752cdbe8c8b8979e185ab93 | refs/heads/master | 2022-10-23T20:34:56.375847 | 2022-10-17T06:06:27 | 2022-10-17T06:06:27 | 205,062,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,307 | cpp | class Solution {
public:
int largestIsland(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size(), res = 0;
bool hasZero = false;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) continue;
hasZero = true;
grid[i][j] = 1; // change 0 to 1, then search num ones starting from [i][j]
vector<vector<bool>> visited(m, vector<bool>(n, false));
res = max(res, helper(grid, i, j, visited));
if (res == m * n) return res; // NOTE
grid[i][j] = 0; // reset [i][j]
}
}
return (hasZero) ? res : m * n;
}
int helper(vector<vector<int>>& grid, int i, int j, vector<vector<bool>> & visited) {
int m = grid.size(), n = grid[0].size();
if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0 || visited[i][j]) return 0;
visited[i][j] = true;
vector<vector<int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int res = 1; // 1 for current [i][j]
for (auto & dir : dirs) {
res += helper(grid, i + dir[0], j + dir[1], visited);
}
return res;
}
};
| [
"[email protected]"
]
| |
a1e4a226eeb869d040b457cd4b6832ed9ce7815d | 38b7b48e02a077f266183c9521b2a3427fa179c9 | /packages/github.com/boostorg/array/tests/array_import_test.cc | 77ced05e5325f8947eee788c4eac9201e154e61b | []
| no_license | MarkusTeufelberger/BBW | 01ab1c1f6d420b637b0bd983ff0e9d3a331dba53 | 24164f7770d9dac7e35c3b117ed327ebaa5c2a06 | refs/heads/master | 2021-01-25T08:07:32.959662 | 2017-07-16T22:27:00 | 2017-07-16T22:27:00 | 93,719,368 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 123 | cc | #include <stdio.h>
#include <boost/array.hpp>
int main(int argc, char **argv)
{
printf("Hello Bazel!\n");
return 0;
}
| [
"[email protected]"
]
| |
0366f36f5b76285303cbc0c7e3c0b719f7ce2062 | f57aafcb05140bd174d9f272d9fa37572d6ac728 | /ThirdParty/maslib/src/common/mas/core/queue.h | 45654b1c28882c8355a2333dce2274bf032b82be | [
"BSD-2-Clause"
]
| permissive | millerhooks/GMM-FEM | 003ca4bc2d9e820d728b407b6bd63016552a7037 | 045d5d9c19ef152c5268c04c111bbb9252a8b809 | refs/heads/master | 2021-06-13T19:51:59.300452 | 2017-03-09T18:23:30 | 2017-03-09T18:23:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,646 | h | #ifndef MAS_CORE_QUEUE_H_
#define MAS_CORE_QUEUE_H_
#include <vector>
#include <stack>
namespace mas {
namespace queue {
// Null callback
template<typename ReferenceType, typename SizeType>
struct null_callback {
void operator()(ReferenceType v, const SizeType a, const SizeType b) {}
};
/**
* @brief A modified version of the priority queue, using mas::heap
* to control heap operations. Allows specification of a "moved callback"
* that is useful to track positions of elements in the queue.
*
* The move callback function must define the operation:<br>
* <code>
* move(Sequence::value_type& val, const Sequence::size_type a, const Sequence::size_type b);
* </code>
* which will be called after <code>val</code> is moved from location <code>a</code> to <code>b</code>
* in the queue. The callback can either be an operator on a struct, or a general function handler (e.g. lambda in c++11).
*
*/
template<typename ValueType, typename Sequence = std::vector<ValueType>,
typename Compare = std::less<typename Sequence::value_type>,
typename MoveCallback = mas::queue::null_callback<typename Sequence::reference,
typename Sequence::size_type> >
class priority_queue {
public:
typedef typename Sequence::value_type value_type;
typedef typename Sequence::reference reference;
typedef typename Sequence::const_reference const_reference;
typedef typename Sequence::size_type size_type;
typedef Sequence container_type;
protected:
// See queue::c for notes on these names.
Sequence c;
Compare comp;
MoveCallback mov;
public:
bool empty() const;
size_type size() const;
const_reference top() const;
void push(const value_type& x);
void pop();
#if __cplusplus < 201103L
explicit priority_queue(const Compare& x = Compare(), const Sequence& s =
Sequence(), const MoveCallback& m = MoveCallback());
template<typename InputIterator>
priority_queue(InputIterator first, InputIterator last, const Compare& x =
Compare(), const Sequence& s = Sequence(), const MoveCallback& m =
MoveCallback());
#else
// duplicated due to possible ambiguity for default constructors
explicit priority_queue(const Compare& x = Compare(), Sequence&& s =
Sequence(), const MoveCallback& m = MoveCallback());
template<typename InputIterator>
priority_queue(InputIterator first, InputIterator last, const Compare& x =
Compare(), Sequence&& s = Sequence(), const MoveCallback& m = MoveCallback());
explicit priority_queue(const Compare& x, const Sequence& s, const MoveCallback& m =
MoveCallback());
template<typename InputIterator>
priority_queue(InputIterator first, InputIterator last, const Compare& x,
const Sequence& s, const MoveCallback& m = MoveCallback());
void push(value_type&& x);
template<typename ... _Args>
void emplace(_Args&&... __args);
void swap(
priority_queue& __pq)
noexcept(noexcept(swap(c, __pq.c)) && noexcept(swap(comp, __pq.comp)) && noexcept(swap(mov, __pq.mov)));
#endif // __cplusplus
// NON-STANDARD pop and retrieve top element in queue
value_type pop_top();
void pop_top(reference top);
value_type pop(size_type loc);
const_reference peek() const;
const_reference peek(size_type loc) const;
reference get();
reference get(size_type loc);
void update();
void update(size_type loc);
bool is_valid() const;
template<typename IterateCallback>
void iterate(const IterateCallback& cb);
};
}// mas
} // queue
#include "mas/core/queue.hpp"
#endif /* MAS_CORE_QUEUE_HPP_ */
| [
"[email protected]"
]
| |
e12a7667cc7959aa810fbdf6f576a5b318585f99 | 0f2635f18d7b47323332ab733f34c9308888e851 | /LUOGU/工程规划.cpp | bcee0c6c60e6d8ff2b3a2a228a7e0d86a2929f9f | []
| no_license | stevebraveman/Code | 2e48b3638272126653c5a2baabac3438db781157 | 4205dd6c4c2f87a8d8554a21efac39616672004e | refs/heads/master | 2020-06-30T21:55:41.313296 | 2019-11-13T22:57:51 | 2019-11-13T22:57:51 | 178,631,305 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,151 | cpp | #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <cstdlib>
#define MAXN 100010
struct Edge {
int v, nx, w;
}e[MAXN << 1];
int head[MAXN], ecnt, n, m, x, y, z, dis[MAXN], in[MAXN], ans;
bool vis[MAXN];
void add(int f, int t, int w) {
e[++ecnt] = (Edge) {t, head[f], w};
head[f] = ecnt;
}
void spfa(int s) {
for (int i = 1; i <= n + 1; i++) {
dis[i] = 0x7fffffff;
vis[i] = 0;
}
std::queue <int> q;
q.push(s);
dis[s] = 0;
while (!q.empty()) {
int u = q.front();
q.pop();
in[u]++;
if (in[u] == n) {
puts("NO SOLUTION");
exit(0);
}
vis[u] = 0;
for (int i = head[u]; i; i = e[i].nx) {
int to = e[i].v;
if (dis[to] > dis[u] + e[i].w) {
dis[to] = dis[u] + e[i].w;
if (!vis[to]) {
vis[to] = 1;
q.push(to);
}
}
}
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &x, &y, &z);
add(y, x, z);
}
for (int i = 1; i <= n; i++) {
add(n + 1, i, 0);
}
spfa(n + 1);
for (int i = 1; i <= n; i++) {
ans = std::min(ans, dis[i]);
}
for (int i = 1; i <= n; i++) {
printf("%d\n", dis[i] - ans);
}
} | [
"[email protected]"
]
| |
4d2a799f351e18d4fd90ee020b12b4740a143844 | 990a27d854cffc226ed54a7c0a2c4207a04dbb95 | /gamelist.h | 3a06381fe718c52974551081146ae6708cc3e88f | []
| no_license | AndreyKoshlan/MinesweeperBattleRoyale | ee37443e4f89dc165216b28d6e35843f56e92387 | 8d4084ad08175087cd0a4be59960b9b9f36b0820 | refs/heads/main | 2023-05-08T11:13:29.707008 | 2021-05-31T20:49:51 | 2021-05-31T20:49:51 | 372,617,167 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 414 | h | #ifndef GAMELIST_H
#define GAMELIST_H
#include <QListWidget>
#include <gameobject.h>
class GameList : public QListWidget, public GameObject
{
public:
/* placement on a graphics scene */
virtual QRectF gameObjectRect() const { return geometry();}
virtual void gameObjectMove(QPoint p) { move(p); };
virtual void gameObjectResize(QSize s) { resize(s); };
GameList();
};
#endif // GAMELIST_H
| [
"[email protected]"
]
| |
6b2a96982175a9c90fa632e63d0df85429fa9e4c | edd02c885c0146a76a3c9a9d89000335b8e3e302 | /airdcpp-webapi/web-server/ApiRouter.h | 559abef71b3a36e410c8efadbe26f919b3a3f0c7 | []
| no_license | Linconio/airdcpp-webclient | 84bc13e374d01b5c69dd392189d17f55bda85bde | a51f9f7d49791b6802e3bc98fc5eac0ab05b81ad | refs/heads/master | 2022-11-19T05:35:20.152293 | 2020-07-11T11:10:02 | 2020-07-11T11:10:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,593 | h | /*
* Copyright (C) 2011-2019 AirDC++ Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef DCPLUSPLUS_DCPP_APIROUTER_H
#define DCPLUSPLUS_DCPP_APIROUTER_H
#include "stdinc.h"
#include <airdcpp/typedefs.h>
namespace webserver {
class ApiRouter {
public:
ApiRouter();
~ApiRouter();
void handleSocketRequest(const std::string& aMessage, WebSocketPtr& aSocket, bool aIsSecure) noexcept;
api_return handleHttpRequest(const std::string& aRequestPath, const websocketpp::http::parser::request& aRequest,
json& output_, json& error_, bool aIsSecure, const string& aIp, const SessionPtr& aSession, const ApiDeferredHandler& aDeferredHandler) noexcept;
private:
api_return handleRequest(ApiRequest& aRequest, bool aIsSecure, const WebSocketPtr& aSocket, const string& aIp) noexcept;
api_return routeAuthRequest(ApiRequest& aRequest, bool aIsSecure, const WebSocketPtr& aSocket, const string& aIp);
};
}
#endif | [
"[email protected]"
]
| |
106dea093e01212cf5606bd856b65e5a68e8e2fd | 2209ddb1376fda6dcd99cf9573ffe74cd9acc362 | /map.cpp | 882f9d8aceb42cee3650806eec8e09fbd8037260 | []
| no_license | stephaniehingtgen/Harry-Potter-Basilisk | 6b3f46609aa07402f7cdd0975a43eef33a8811de | 1255d19c74e0970d5767ec78634c28ec935afa87 | refs/heads/master | 2021-10-16T07:49:19.809548 | 2019-02-09T04:20:38 | 2019-02-09T04:20:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,098 | cpp | #include "snake.h"
#include "map.h"
#include <curses.h>
#include <stdlib.h>
#include <iostream>
#include <cstdlib>
#include <vector>
#include <stdio.h>
#include <unistd.h>
#include <err.h>
#include <time.h>
using namespace std;
//This code is given from my professor
typedef struct io_message{
char msg[71];
struct io_message *next;
} io_message_t;
static io_message_t *io_head, *io_tail;
void io_queue_message(const char *format, ...)
{
io_message_t *tmp;
va_list ap;
if (!(tmp = (io_message_t *) malloc(sizeof (*tmp)))) {
perror("malloc");
exit(1);
}
tmp->next = NULL;
va_start(ap, format);
vsnprintf(tmp->msg, sizeof (tmp->msg), format, ap);
va_end(ap);
if (!io_head) {
io_head = io_tail = tmp;
} else {
io_tail->next = tmp;
io_tail = tmp;
}
}
static void io_print_message_queue(uint32_t y, uint32_t x)
{
while (io_head) {
io_tail = io_head;
//attron(COLOR_PAIR(COLOR_CYAN));
mvprintw(y, x, "%-80s", io_head->msg);
//attroff(COLOR_PAIR(COLOR_CYAN));
io_head = io_head->next;
free(io_tail);
}
io_tail = NULL;
}
//Starting my own code
void new_map(map_t *m){
int i,k, y, x;
snake *sn= new snake();
y=(rand()%46)+1;
x=(rand()%46)+1;
snake_set_alive(sn, 1);
snake_set_x(sn,x);
snake_set_y(sn,y);
m->s=sn;
m->numEggs=0;
m->numTraps=20;
for(i=0; i<50; i++){
for(k=0; k<50; k++){
m->EG[i][k]=0;
m->traps[i][k]=0;
}
}
for(i=0; i<m->numTraps; i++){
y=rand()%46 +1;
x=rand()%46 +1;
while(m->traps[y][x]==1 ||( m->s->xposition==x && m->s->yposition==y)){
y=rand()%46 +1;
x=rand()%46 +1;
}
m->traps[y][x]=1;
}
}
void delete_map(map_t *m){
delete(m->s);
int i;
/*for(i=0; i<m->numEggs; i++){
free(m->Eggs[i]);
}*/
}
void do_move(map_t *m){
move_eggs(m);
fflush(stdout);
int i;
fd_set readfs;
struct timeval tv;
FD_ZERO(&readfs);
FD_SET(0, &readfs);
tv.tv_sec=0;
tv.tv_usec=300000;
switch(select(1, &readfs,NULL, NULL, &tv)){
case -1:
case 0:
if(m->s->yOldPosition > m->s->yposition){
snake_set_oldy(m->s, m->s->yposition);
snake_set_y(m->s, (m->s->yposition)-1);
}
else{
snake_set_oldy(m->s, m->s->yposition);
snake_set_y(m->s, (m->s->yposition)+1);
}
if(m->s->xOldPosition > m->s->xposition){
snake_set_oldx(m->s, m->s->xposition);
snake_set_x(m->s, (m->s->xposition)-1);
}
else{
snake_set_oldx(m->s, m->s->xposition);
snake_set_x(m->s, (m->s->xposition)+1);
}
break;
case 1:
switch(i=getch()){
case KEY_LEFT:
case 'h':
snake_set_oldx(m->s, m->s->xposition);
snake_set_x(m->s, (m->s->xposition)-1);
break;
case KEY_DOWN:
case 'j':
snake_set_oldy(m->s, m->s->yposition);
snake_set_y(m->s, (m->s->yposition)+1);
break;
case KEY_RIGHT:
case 'l':
snake_set_oldx(m->s, m->s->xposition);
snake_set_x(m->s, (m->s->xposition)+1);
break;
case KEY_UP:
case 'k':
snake_set_oldy(m->s, m->s->yposition);
snake_set_y(m->s, (m->s->yposition)-1);
break;
}
break;
}
if(m->s->xposition==0 || m->s->xposition==48
|| m->s->yposition==0 || m->s->yposition==48){
snake_set_alive(m->s, 0);
}
for(i=0; i<(m->numEggs); i++){
if(m->Eggs[i].xposition==m->s->xposition
&& m->Eggs[i].yposition==m->s->yposition){
snake_set_alive(m->s, 0);
}
}
}
const char *mudbloods[]={
"Hermione Granger",
"Lily Potter",
"Colin Creevey",
"Mary Cattermole",
"Moaning Myrtle",
"Ted Tonks",
"Justin Finch-Fletchley",
"Mary Cattermole",
"Dennis Creevey",
"Dirk Cresswell",
"Kendra Dumbledore",
"Kevin Entwhistle",
"Johannes Jonker",
"Nobby Leach",
"Garrick Ollivander's mother",
"Tertius",
"Donaghan Tremlett",
"Wandless"
};
void move_eggs(map_t *m){
int i,k;
if(m->traps[m->s->yposition][m->s->xposition]){
k=rand()%18;
io_queue_message("You petrified %s.", mudbloods[k]);
egg *e=new egg();
e->xposition=m->s->xposition;
e->yposition=m->s->yposition;
if(m->numEggs==0){
(m->Eggs).insert(m->Eggs.begin(), *e);
}
else{
std::vector<egg>:: iterator it= m->Eggs.begin();
(m->Eggs).insert(it+1,*e);
}
m->traps[m->s->yposition][m->s->xposition]=0;
m->numTraps--;
m->EG[e->yposition][e->xposition]=1;
m->numEggs++;
}
else{
for(i=0; i<m->numEggs; i++){
if(i==0){
m->EG[m->Eggs[i].yposition][m->Eggs[i].xposition]=0;
(m->Eggs[i]).yposition=(m->Eggs[i+1]).yposition;
(m->Eggs[i]).xposition=(m->Eggs[i+1]).xposition;
m->EG[m->Eggs[i].yposition][m->Eggs[i].xposition]=1;
}
if(i==(m->numEggs -1)){
m->Eggs[i].yposition=m->s->yposition;
m->Eggs[i].xposition=m->s->xposition;
m->EG[m->Eggs[i].yposition][m->Eggs[i].xposition]=1;
}
else{
(m->Eggs[i]).yposition=(m->Eggs[i+1]).yposition;
(m->Eggs[i]).xposition=(m->Eggs[i+1]).xposition;
m->EG[m->Eggs[i].yposition][m->Eggs[i].xposition]=1;
}
}
}
}
void printMap(map_t *m){
if(m->numEggs==0){
clear();
}
init_pair(2, COLOR_GREEN, COLOR_BLACK);
init_pair(6, COLOR_CYAN, COLOR_BLACK);
int i,k;
start_color();
for(i=0; i<50; i++){
for(k=0; k<50; k++){
io_print_message_queue(1,51);
if(i==0 && k==9){
mvaddch(i,k, ' ');
}
else if(i==0 && k==10){
attron(COLOR_PAIR(6));
mvaddch(i,k, 'C');
}
else if(i==0 && k==11){
mvaddch(i,k, 'h');
}
else if(i==0 && k==12){
mvaddch(i,k, 'a');
}
else if(i==0 && k==13){
mvaddch(i,k, 'm');
}
else if(i==0 && k==14){
mvaddch(i,k, 'b');
}
else if(i==0 && k==15){
mvaddch(i,k, 'e');
}
else if(i==0 && k==16){
mvaddch(i,k, 'r');
}
else if(i==0 && k==17){
mvaddch(i,k, ' ');
}
else if(i==0 && k==18){
mvaddch(i,k, 'o');
}
else if(i==0 && k==19){
mvaddch(i,k, 'f');
}
else if(i==0 && k==20){
mvaddch(i,k, ' ');
}
else if(i==0 && k==21){
mvaddch(i,k, 'S');
}
else if(i==0 && k==22){
mvaddch(i,k, 'e');
}
else if(i==0 && k==23){
mvaddch(i,k, 'c');
}
else if(i==0 && k==24){
mvaddch(i,k, 'r');
}
else if(i==0 && k==25){
mvaddch(i,k, 'e');
}
else if(i==0 && k==26){
mvaddch(i,k, 't');
}
else if(i==0 && k==27){
mvaddch(i,k, 's');
}
else if(i==0 && k==28){
mvaddch(i,k, ' ');
attroff(COLOR_PAIR(6));
}
else if((i==0 && k!=49) || (k==0 && i!=49) || (i==48 && k!=49) || (k==48 && i!=49)){
mvaddch(i,k, 'X');
}
else if(m->s->yposition==i && m->s->xposition==k){
//green
attron(COLOR_PAIR(2));
mvaddch(i,k, 'S');
attroff(COLOR_PAIR(2));
}
else if(m->traps[i][k]==1){
mvaddch(i,k,'m');
}
else if(m->EG[i][k]==1){
attron(COLOR_PAIR(2));
mvaddch(i,k, '0');
attroff(COLOR_PAIR(2));
}
else{
mvaddch(i,k, ' ');
}
}
}
}
| [
"[email protected]"
]
| |
b1311f653b6c3af1e0f45535fa36b77e9055b345 | 2eecc41bc8ae893490b30e3abd9808bbd2bd6bdb | /Include/scge/FileSystem.h | bf14edf5656df2af7cd7aee05dd361fff2e25740 | []
| no_license | shadercoder/scge | d991230860573a56a44f3ecac2de38c4f25a67f3 | cec2bb285aa284206b4d41b9bbbf129a151bf200 | refs/heads/master | 2021-01-10T04:20:19.240225 | 2012-11-05T22:50:20 | 2012-11-05T22:50:20 | 44,643,412 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,280 | h | #ifndef __FileSystem_h__
#define __FileSystem_h__
#include <map>
#include <fstream>
#include <memory>
#include <boost\bimap.hpp>
#include <boost\bimap\unordered_set_of.hpp>
class ResourceManager;
class FileResource;
class FileSystem
{
public:
FileSystem(std::string resourceDirectory = "Resources");
~FileSystem();
void updateChangedFiles(ResourceManager &resourceManager);
std::pair<std::string, bool> getFilePath(const std::string &fileName, bool canCreate = false) const;
std::ifstream OpenFileRead(const std::string &fileName, bool binary = false) const;
std::ofstream OpenFileWrite(const std::string &fileName, bool canCreate = false, bool append = false, bool binary = false) const;
bool RegisterForFileChanges(FileResource &resource);
void UnregisterForFileChanges(FileResource &resource);
private:
std::string mResourceDirectory;
typedef boost::bimap<boost::bimaps::unordered_set_of<std::string>, boost::bimaps::set_of<FileResource*>> ResourceFileAssociations;
ResourceFileAssociations mResourceFileAssociations;
class DirectoryWatcher;
std::unique_ptr<DirectoryWatcher> mDirectoryWatcher;
FileSystem(const FileSystem &other);
FileSystem &operator=(const FileSystem &other);
};
#endif // __FileSystem_h__ | [
"quaver.smith@0469fb3b-1f0d-998d-8d12-02512b85cd7a"
]
| quaver.smith@0469fb3b-1f0d-998d-8d12-02512b85cd7a |
e4e4242e2a336e20558a884c6eb51d812151a193 | 19e382c9e5c62e79494148d007bcb4f23539147c | /include/XeSimPhysicsMessenger.hh | 621dd22d6a0cac5f9fefe49d4da4c97c75e610a9 | [
"BSD-3-Clause"
]
| permissive | l-althueser/XeSim | ad1f309f5d22b5496d1b085515a4b8364a9ab0c9 | 972ea62a35db7c80c6e4b3349987e31945651399 | refs/heads/master | 2020-09-02T05:03:45.182873 | 2020-02-03T10:20:14 | 2020-02-03T10:20:14 | 219,137,604 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 916 | hh | #ifndef __XeSimPhysicsMessenger_H__
#define __XeSimPhysicsMessenger_H__
#include <G4UImessenger.hh>
#include <globals.hh>
class XeSimPhysicsList;
class G4UIcommand;
class G4UIdirectory;
class G4UIcmdWithoutParameter;
class G4UIcmdWithAString;
class G4UIcmdWithADoubleAndUnit;
class G4UIcmdWith3Vector;
class G4UIcmdWith3VectorAndUnit;
class G4UIcmdWithAnInteger;
class G4UIcmdWithADouble;
class G4UIcmdWithABool;
class G4UIcmdWithoutParameter;
class XeSimPhysicsMessenger: public G4UImessenger
{
public:
XeSimPhysicsMessenger(XeSimPhysicsList *pPhysicsList);
~XeSimPhysicsMessenger();
void SetNewValue(G4UIcommand *pCommand, G4String hNewValues);
private:
XeSimPhysicsList *m_pPhysicsList;
G4UIdirectory *m_pDirectory;
G4UIcmdWithAString *m_pEMlowEnergyModelCmd;
G4UIcmdWithAString *m_pHadronicModelCmd;
G4UIcmdWithABool *m_pCerenkovCmd;
};
#endif
| [
"[email protected]"
]
| |
8fe26a8406359d9ec08a452c488936401a182312 | 6b49c926e0ea3bee5e45b7e93551248f55276dd9 | /C++ Projects/gekkfogeek/Chapter 9/Soln9_03.cpp | a4e69dde6d808107bd6c44ba9e33e95a35c0bde9 | []
| no_license | RaduEmanuel92/misc | 6dedf29171929c48419d52492d90c59be58a74ea | c1c03a7f2e23d5ec99434f41e3cbbf91024aa140 | refs/heads/master | 2021-06-27T22:35:04.927642 | 2017-09-10T22:34:02 | 2017-09-10T22:34:02 | 103,050,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 969 | cpp | // Exercise 9.3 A lambda expression returning the number of vector elements that begin with a given letter.
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using std::string;
int main()
{
std::vector <string> words {"apple", "pear", "plum", "orange", "peach", "grape", "greengage"};
std::cout << "Words are:\n";
for (auto word : words)
std::cout << std::setw(10) << word;
std::cout << std::endl;
auto count = [&words](char letter){
size_t n {};
for (auto& word : words)
if (letter == word[0]) ++n;
return n;
};
char ch {'p'};
std::cout << "There are " << count(ch) << " words beginning with " << ch << ".\n";
ch = 'g';
std::cout << "There are " << count(ch) << " words beginning with " << ch << ".\n";
} | [
"[email protected]"
]
| |
95ee3960969e39a28198a0ecf23dd0a0ed94afc0 | 63af6e197f3bfe77ce6c895a19e1df0719d1e11e | /round2/neo.cpp | b89c92eb2903f9018e0d97d9039201525a7cfe93 | []
| no_license | ivonaj95/BC11 | 71b9cbdce1b1d7da47e3287e6003e664b43d9476 | 85f1aef84ee43a0efc506b7f2370bc9e94b9f117 | refs/heads/master | 2020-04-07T07:58:50.707202 | 2018-11-19T12:44:06 | 2018-11-19T12:44:06 | 158,196,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9 | cpp | u izradi
| [
"[email protected]"
]
| |
9ca3e28f48c8a9ef168982e6784d1b3cb5cad869 | e53f00bbd9c8f92c8adb452cbe31807c11f6770a | /Motor_v1.h | 85e543cfa7f79dedeb729e315c06abb8e2cdddc2 | []
| no_license | luo-yq/OpenCR_Motor | dc0e8fb189923635654671481eeacd36526c3757 | 5b11c0c0c186c0520c9a909ee4c56b8e59ae73d2 | refs/heads/master | 2020-03-31T07:59:57.063320 | 2018-10-08T08:18:49 | 2018-10-08T08:18:49 | 152,041,386 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,788 | h | #ifndef Motor_v1_h
#define Motor_v1_h
#define motor_pin_l_a 6
#define motor_pin_l_b 9
#define motor_pin_r_a 10
#define motor_pin_r_b 11
#define encoder_pin_l_a 2
#define encoder_pin_l_b 4
#define encoder_pin_r_a 8
#define encoder_pin_r_b 7
#define W_KP 0.27//0.35 0.27
#define W_KI 0.0//0.0
#define W_KD 0.0//0.0
#define S_KP 20.0//25.0//20.0
#define S_KI 6.8//5.8//5.0
#define S_KD 0.02//0.6//0.0
#define motor_max_pwm 210
#define motor_Mspeed 20
#define Integral_limit 200
#define motor_time_int 10000 //us
typedef struct
{
long count;
int count_sp;
int Mspeed;
bool dir;
int encoder_a;
int encoder_b;
}Wheel;
typedef struct
{
double target;
double feedback;
double output;
double e_0; //this error
double e_1; //last error
double e_2; //pre error
double kp;
double ki;
double kd;
double Proportion;
double Integral;
double Differential;
char SetPointChang;
int mode; // incremen or location
int motorA;
int motorB;
}MOTOR_PID;
class MotorDriver
{
public:
// PID mode
#define INCREMENT 0 //default
#define LOCATION 1
#define ENCOUDER_A 0
#define ENCOUDER_B 1
Wheel wheel_motor_l;
Wheel wheel_motor_r;
MOTOR_PID motor_Wpid_l;
MOTOR_PID motor_Spid_l;
MOTOR_PID motor_Wpid_r;
MOTOR_PID motor_Spid_r;
bool motor_init(void); // motor parameters init
bool Count_and_Direction_A(Wheel *omni); // feedback Mspeed counter
bool Count_and_Direction_B(Wheel *omni);
bool Pid_Control(int left_target, int right_target, int *read_data);
bool Speed_Interrupt(void);
private:
bool SPID(MOTOR_PID *pid);
bool Motor_Star(MOTOR_PID *star);
};
#endif
| [
"[email protected]"
]
| |
bba9342478f5a73909040854474dfb3c929798aa | b3938012b6ba40bf208a9c41783c8aa06aeb71e1 | /Backtracking/로또_6603/6603.cpp | 35693a42e3f37ba206ad06f02b06702283383fb9 | []
| no_license | hansolpp/Algorithm | 008117602f62154f8de1e303c3fe06d42a8c2e58 | 40e5e689deaf485887bfb0150d4b04aa3d394198 | refs/heads/master | 2022-07-08T14:50:57.355379 | 2020-05-12T12:01:38 | 2020-05-12T12:01:38 | 233,571,497 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 812 | cpp | #include<cstdio>
using namespace std;
int N;
int numbers[12];
bool visited[12];
void get_info() {
scanf("%d", &N);
for(int i = 0; i < N; i++) {
scanf("%d", &numbers[i]);
}
return;
}
void print_case() {
int idx = 0;
while(idx != N) {
if(visited[idx]) printf("%d ", numbers[idx]);
++idx;
}
printf("\n");
return;
}
void dfs(int pos, int count) {
if(count == 6) return print_case();
if(6 - count > N - pos) return;
for(int i = pos + 1; i < N; i++) {
visited[i] = 1;
dfs(i, count+1);
visited[i] = 0;
}
return;
}
void solution() {
for(int i = 0; i < N; i++) {
if(!visited[i]) {
visited[i] = 1;
dfs(i, 1);
visited[i] = 0;
}
}
return;
}
int main() {
freopen("input.txt", "r", stdin);
while(1) {
get_info();
if(N == 0) break;
solution();
printf("\n");
}
}
| [
"[email protected]"
]
| |
f37fa1262bf1bdcde9d7b4bba5cff6d0061b7ae7 | 8a101318023566a379096c46d94816dc3237b58a | /Arduino/libraries/pfodESP8266WiFi/src/pfodESP8266WebConfig.cpp | 4109bcebf485c001b488bab49e74f6ffa93f77f6 | []
| no_license | binhpham1909/MyProject | 8aef1971073af88874adf027e5072c1df26bc1fe | 11c2ebf99bae3ea9180421324e8e886d8ab87e21 | refs/heads/master | 2021-01-20T20:15:24.575508 | 2017-05-12T09:25:11 | 2017-05-12T09:25:11 | 60,657,275 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,091 | cpp | // pfodESP8266WebConfig.cpp
/**
(c)2015 Forward Computing and Control Pty. Ltd.
This code may be freely used for both private and commerical use.
Provide this copyright is maintained.
*/
#include <stdint.h>
#include <EEPROM.h>
#include "pfodESP8266WebConfig.h"
// uncomment this next line and call setDebugStream(&Serial); to enable debug out
#define DEBUG
void pfodESP8266WebConfig::handleRoot(pfodESP8266WebConfig* ptr) {
ptr->rootHandler();
}
void pfodESP8266WebConfig::handleConfig(pfodESP8266WebConfig* ptr) {
ptr->configHandler();
}
void pfodESP8266WebConfig::handleNotFound(pfodESP8266WebConfig* ptr) {
ptr->rootHandler();
}
void pfodESP8266WebConfig::init(uint8_t _startAddress, uint8_t _mode) {
startAddress = _startAddress;
webserverPtr = &webserver;
webserverPtr->on ( "/", std::bind(&pfodESP8266WebConfig::handleRoot, this));
webserverPtr->on ( "/config", std::bind(&pfodESP8266WebConfig::handleConfig, this));
webserverPtr->onNotFound( std::bind(&pfodESP8266WebConfig::handleNotFound, this));
mode = _mode;
inConfig = false;
configHandlerCalled = false;
rootHandlerCalled = false;
needToConnect = false;
}
void pfodESP8266WebConfig::setDebugStream(Print* out) {
debugOut = out;
}
// returns 2 if config processed, 1 if root called, 0 if no change
int pfodESP8266WebConfig::handleClient() {
webserverPtr->handleClient();
if (configHandlerCalled) {
return 2;
} else if (rootHandlerCalled) {
return 1;
} //else
return 0;
}
bool pfodESP8266WebConfig::inConfigMode() {
return inConfig;
}
void pfodESP8266WebConfig::exitConfigMode() {
if (inConfig) {
WiFiClient::stopAll(); // cleans up memory
webserver.close();
WiFi.softAPdisconnect();
WiFi.mode(WIFI_STA);
needToConnect = true;
}
inConfig = false;
#ifdef DEBUG
if (debugOut) {
debugOut->println(F("Exit pfodWifiWebConfig"));
}
#endif
}
void pfodESP8266WebConfig::setupAP(const char* ssid_wifi, const char* password_wifi) {
inConfig = true;
rootHandlerCalled = false;
configHandlerCalled = false;
WiFi.mode(WIFI_AP);
aps = pfodESP8266Utils::scanForStrongestAP((char*)&ssid_found, pfodESP8266Utils::MAX_SSID_LEN + 1);
delay(0);
IPAddress local_ip = IPAddress(10, 1, 1, 1);
IPAddress gateway_ip = IPAddress(10, 1, 1, 1);
IPAddress subnet_ip = IPAddress(255, 255, 255, 0);
#ifdef DEBUG
if (debugOut) {
debugOut->print(F("configure pfodWifiWebConfig mode:"));
debugOut->println(mode);
}
#endif
WiFi.softAP(ssid_wifi, password_wifi);
#ifdef DEBUG
if (debugOut) {
debugOut->println(F("Access Point setup"));
}
#endif
WiFi.softAPConfig(local_ip, gateway_ip, subnet_ip);
#ifdef DEBUG
if (debugOut) {
debugOut->println("done");
IPAddress myIP = WiFi.softAPIP();
debugOut->print(F("AP IP address: "));
debugOut->println(myIP);
}
#endif
delay(10);
webserver.begin();
#ifdef DEBUG
if (debugOut) {
debugOut->println ( "HTTP webserver started" );
}
#endif
}
pfodESP8266WebConfig::STORAGE* pfodESP8266WebConfig::getStorage() {
return &storage;
}
pfodESP8266WebConfig::STORAGE* pfodESP8266WebConfig::loadConfig() {
uint8_t * byteStorageRead = (uint8_t *) & (pfodESP8266WebConfig::storage);
for (size_t i = 0; i < STORAGE_SIZE; i++) {
byteStorageRead[i] = EEPROM.read(startAddress + i);
}
// clean up portNo
if ((storage.portNo == 0xffff) || (storage.portNo == 0)) {
storage.portNo = 4989; // default
}
return &storage;
}
// return wifi status
int pfodESP8266WebConfig::loadConfigAndAttemptToJoinNetwork() {
loadConfig();
// Initialise wifi module
/**
#ifdef DEBUG
if (debugOut) {
debugOut->println(F("Connecting to AP"));
}
#endif
**/
return WiFi.begin(storage.ssid, storage.password);
}
void pfodESP8266WebConfig::joinWiFiIfNotConnected() {
if (WiFi.status() != WL_CONNECTED) {
if (!needToConnect) {
needToConnect = true; // set this each time we loose connection
WiFi.disconnect();
#ifdef DEBUG
if (debugOut) {
debugOut->print(F("NOT connected "));
}
#endif
}
}
if (needToConnect && (loadConfigAndAttemptToJoinNetwork() == WL_CONNECTED)) {
// did not have connection and have one now
needToConnect = false;
// do this again as when switching from DHCP to static IP do not get static IP
pfodESP8266WebConfig::STORAGE *storage = getStorage();
#ifdef DEBUG
if (debugOut) {
debugOut->print(F("Connected to ")); debugOut->println(storage->ssid);
}
#endif
if (*(storage->staticIP) != '\0') {
// config static IP
IPAddress ip(pfodESP8266Utils::ipStrToNum(storage->staticIP));
IPAddress gateway(ip[0], ip[1], ip[2], 1); // set gatway to ... 1
#ifdef DEBUG
if (debugOut) {
debugOut->print(F("Setting IP to "));
debugOut->println(storage->staticIP);
}
#endif
IPAddress subnet(255, 255, 255, 0);
WiFi.config(ip, gateway, subnet);
} else {
//leave as DHCP
#ifdef DEBUG
if (debugOut) {
debugOut->print(F("DHCP IP is ")); Serial.println(WiFi.localIP());
}
#endif
}
} else {
delay(0);
}
}
pfodESP8266WebConfig::STORAGE *pfodESP8266WebConfig::loadConfigAndJoinNetwork() {
uint8_t * byteStorageRead = (uint8_t *) & (pfodESP8266WebConfig::storage);
for (size_t i = 0; i < STORAGE_SIZE; i++) {
byteStorageRead[i] = EEPROM.read(startAddress + i);
}
// Initialise wifi module
#ifdef DEBUG
if (debugOut) {
debugOut->println();
debugOut->println(F("Connecting to AP"));
debugOut->print("ssid '");
debugOut->print(storage.ssid);
debugOut->println("'");
debugOut->print("password '");
debugOut->print(storage.password);
debugOut->println("'");
}
#endif
/**********
// do this before begin to set static IP and not enable dhcp
if (*(storage.staticIP) != '\0') {
// config static IP
IPAddress ip(pfodESP8266Utils::ipStrToNum(storage.staticIP));
IPAddress gateway(ip[0], ip[1], ip[2], 1); // set gatway to ... 1
IPAddress subnet(255, 255, 255, 0);
WiFi.config(ip, gateway, subnet);
} // else leave as DHCP
**********/
WiFi.begin(storage.ssid, storage.password);
int counter = 0;
while ((WiFi.status() != WL_CONNECTED) && (counter < 40)) {
delay(500);
counter++;
#ifdef DEBUG
if (debugOut) {
debugOut->print(".");
}
#endif
}
if (WiFi.status() != WL_CONNECTED) {
#ifdef DEBUG
if (debugOut) {
debugOut->println();
debugOut->println(F("Could not connect!"));
}
#endif
return NULL;
}
#ifdef DEBUG
if (debugOut) {
debugOut->println();
debugOut->println(F("Connected!"));
}
#endif
// do this again as when switching from DHCP to static IP do not get static IP
if (*(storage.staticIP) != '\0') {
// config static IP
IPAddress ip(pfodESP8266Utils::ipStrToNum(storage.staticIP));
IPAddress gateway(ip[0], ip[1], ip[2], 1); // set gatway to ... 1
#ifdef DEBUG
if (debugOut) {
debugOut->print(F("Setting gateway to: "));
debugOut->println(gateway);
}
#endif
IPAddress subnet(255, 255, 255, 0);
WiFi.config(ip, gateway, subnet);
} // else leave as DHCP
// Start listening for connections
#ifdef DEBUG
if (debugOut) {
// Print the IP address
debugOut->print(WiFi.localIP());
debugOut->print(':');
debugOut->println(storage.portNo);
debugOut->println(F("Start Server"));
}
#endif
return &storage;
}
void pfodESP8266WebConfig::configHandler() {
if (!rootHandlerCalled) {
rootHandler(); // always display config page first
return;
}
// set defaults
uint16_t portNo = 80;
uint32_t timeout = DEFAULT_CONNECTION_TIMEOUT_SEC * 1000; // time out in 15 sec
uint32_t baudRate = 19200;
#ifdef DEBUG
if (debugOut) {
debugOut->print("configHandler mode:");
debugOut->println(mode);
}
#endif
if (webserver.args() > 0) {
#ifdef DEBUG
if (debugOut) {
String message = "Config results\n\n";
message += "URI: ";
message += webserver.uri();
message += "\nMethod: ";
message += ( webserver.method() == HTTP_GET ) ? "GET" : "POST";
message += "\nArguments: ";
message += webserver.args();
message += "\n";
for ( uint8_t i = 0; i < webserver.args(); i++ ) {
message += " " + webserver.argName ( i ) + ": " + webserver.arg ( i ) + "\n";
}
debugOut->println(message);
}
#endif
uint8_t numOfArgs = webserver.args();
const char *strPtr;
uint8_t i = 0;
for (; (i < numOfArgs); i++ ) {
// check field numbers
if (webserver.argName(i)[0] == '1') {
pfodESP8266Utils::strncpy_safe(storage.ssid, (webserver.arg(i)).c_str(), pfodESP8266Utils::MAX_SSID_LEN);
pfodESP8266Utils::urldecode2(storage.ssid, storage.ssid); // result is always <= source so just copy over
} else if (webserver.argName(i)[0] == '2') {
pfodESP8266Utils::strncpy_safe(storage.password, (webserver.arg(i)).c_str(), pfodESP8266Utils::MAX_PASSWORD_LEN);
pfodESP8266Utils::urldecode2(storage.password, storage.password); // result is always <= source so just copy over
// if password all blanks make it empty
if (pfodESP8266Utils::isEmpty(storage.password)) {
storage.password[0] = '\0';
}
} else if (webserver.argName(i)[0] == '3') {
pfodESP8266Utils::strncpy_safe(storage.staticIP, (webserver.arg(i)).c_str(), pfodESP8266Utils::MAX_STATICIP_LEN);
pfodESP8266Utils::urldecode2(storage.staticIP, storage.staticIP); // result is always <= source so just copy over
if (pfodESP8266Utils::isEmpty(storage.staticIP)) {
// use dhcp
storage.staticIP[0] = '\0';
}
} else if (webserver.argName(i)[0] == '4') {
// convert portNo to uint16_6
const char *portNoStr = (( webserver.arg(i)).c_str());
long longPort = 0;
pfodESP8266Utils::parseLong((byte*)portNoStr, &longPort);
storage.portNo = (uint16_t)longPort;
} else if (webserver.argName(i)[0] == '5') {
// convert baud rate to int32_t
const char *baudStr = (( webserver.arg(i)).c_str());
long baud = 0;
pfodESP8266Utils::parseLong((byte*)baudStr, &baud);
storage.baudRate = (uint32_t)(baud);
} else if (webserver.argName(i)[0] == '6') {
// convert timeout to int32_t
// then *1000 to make mS and store as uint32_t
const char *timeoutStr = (( webserver.arg(i)).c_str());
long timeoutSec = 0;
pfodESP8266Utils::parseLong((byte*)timeoutStr, &timeoutSec);
if (timeoutSec > 4294967) {
timeoutSec = 4294967;
}
if (timeoutSec < 0) {
timeoutSec = 0;
}
storage.timeout = (uint32_t)(timeoutSec * 1000);
}
}
uint8_t * byteStorage = (uint8_t *)&storage;
for (size_t i = 0; i < STORAGE_SIZE; i++) {
EEPROM.write(startAddress + i, byteStorage[i]);
}
delay(0);
EEPROM.commit();
} // else if no args just return current settings
delay(0);
STORAGE storageRead;
uint8_t * byteStorageRead = (uint8_t *)&storageRead;
for (size_t i = 0; i < STORAGE_SIZE; i++) {
byteStorageRead[i] = EEPROM.read(startAddress + i);
}
String rtnMsg = "<html>"
"<head>"
"<title>pfodWifiWebConfig Server Setup</title>"
"<meta charset=\"utf-8\" />"
"<meta name=viewport content=\"width=device-width, initial-scale=1\">"
"</head>"
"<body>"
"<h2>pfodWifiWebConfig Server Settings saved.</h2><br>Power cycle to connect to ";
if (storageRead.password[0] == '\0') {
rtnMsg += "the open network ";
}
rtnMsg += "<b>";
rtnMsg += storageRead.ssid;
rtnMsg += "</b>";
if (storageRead.staticIP[0] == '\0') {
rtnMsg += "<br> using DCHP to get its IP address";
} else { // staticIP
rtnMsg += "<br> using IP addess ";
rtnMsg += "<b>";
rtnMsg += storageRead.staticIP;
rtnMsg += "</b>";
}
rtnMsg += "<br><br>Will start a server listening on port ";
rtnMsg += storageRead.portNo;
if (mode == WIFI_SHIELD_MODE) {
rtnMsg += ".<br> with connection timeout of ";
rtnMsg += storageRead.timeout / 1000;
rtnMsg += " seconds.";
rtnMsg += "<br><br>Serial baud rate set to ";
rtnMsg += storageRead.baudRate;
}
rtnMsg += "</body>"
"</html>";
webserver.send ( 200, "text/html", rtnMsg );
delay(1000); // wait a moment to send response
configHandlerCalled = true;
}
void pfodESP8266WebConfig::rootHandler() {
// got request for root
// stop flash and make light solid
rootHandlerCalled = true;
#ifdef DEBUG
if (debugOut) {
debugOut->print("rootHandler mode:");
debugOut->println(mode);
}
#endif
String msg;
msg = "<html>"
"<head>"
"<title>pfodWifiWebConfig Server Setup</title>"
"<meta charset=\"utf-8\" />"
"<meta name=viewport content=\"width=device-width, initial-scale=1\">"
"</head>"
"<body>"
"<h2>pfodWifiWebConfig Server Setup</h2>"
"<p>Use this form to configure your device to connect to your Wifi network and start as a Server listening on the specified port.</p>"
"<form class=\"form\" method=\"post\" action=\"/config\" >"
"<p class=\"name\">"
"<label for=\"name\">Network SSID</label><br>"
"<input type=\"text\" name=\"1\" id=\"ssid\" placeholder=\"wifi network name\" required "; // field 1
if (*aps != '\0') {
msg += " value=\"";
msg += aps;
msg += "\" ";
}
msg += " />"
"<p class=\"password\">"
"<label for=\"password\">Password for WEP/WPA/WPA2 (enter a space if there is no password, i.e. OPEN)</label><br>"
"<input type=\"text\" name=\"2\" id=\"password\" placeholder=\"wifi network password\" autocomplete=\"off\" required " // field 2
"</p>"
"<p class=\"static_ip\">"
"<label for=\"static_ip\">Set the Static IP for this device</label><br>"
"(If this field is empty, DHCP will be used to get an IP address)<br>"
"<input type=\"text\" name=\"3\" id=\"static_ip\" placeholder=\"192.168.4.99\" " // field 3
" pattern=\"\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b\"/>"
"</p>"
"<p class=\"portNo\">"
"<label for=\"portNo\">Set the port number that the Server will listen on for connections.</label><br>"
"<input type=\"text\" name=\"4\" id=\"portNo\" placeholder=\"80\" required" // field 4
" pattern=\"\\b([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])\\b\" />"
"</p>";
if (mode == WIFI_SHIELD_MODE) {
msg += "<p class=\"baud\">"
"<label for=\"baud\">Serial Baud Rate (limit to 19200 for Uno and Mega)</label><br>"
"<select name=\"5\" id=\"baud\" required>" // field 5
"<option value=\"9600\">9600</option>"
"<option value=\"14400\">14400</option>"
"<option selected value=\"19200\">19200</option>"
"<option value=\"28800\">28800</option>"
"<option value=\"38400\">38400</option>"
"<option value=\"57600\">57600</option>"
"<option value=\"76800\">76800</option>"
"<option value=\"115200\">115200</option>"
"</select>"
"</p>"
"<p class=\"timeout\">"
"<label for=\"timeout\">Set the server connection timeout in seconds, 0 for never timeout (not recommended).</label><br>"
"<input type=\"text\" name=\"6\" id=\"timeout\" required" // field 6
" value=\"";
msg += DEFAULT_CONNECTION_TIMEOUT_SEC;
msg += "\""
" pattern=\"\\b([0-9]{1,7})\\b\" />"
"</p>";
}
msg += "<p class=\"submit\">"
"<input type=\"submit\" value=\"Configure\" />"
"</p>"
"</form>"
"</body>"
"</html>";
webserver.send ( 200, "text/html", msg );
}
| [
"[email protected]"
]
| |
af559e1dd5e6cecf2e634c1dffec93ef68083abf | 799f7938856a320423625c6a6a3881eacdd0e039 | /clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp | 43b07360625f6aa344e6e1dc9b262c6f22c1f5a4 | [
"Apache-2.0",
"LLVM-exception",
"NCSA"
]
| permissive | shabalind/llvm-project | 3b90d1d8f140efe1b4f32390f68218c02c95d474 | d06e94031bcdfa43512bf7b0cdfd4b4bad3ca4e1 | refs/heads/main | 2022-10-18T04:13:17.818838 | 2021-02-04T13:06:43 | 2021-02-04T14:23:33 | 237,532,515 | 0 | 0 | Apache-2.0 | 2020-01-31T23:17:24 | 2020-01-31T23:17:23 | null | UTF-8 | C++ | false | false | 10,182 | cpp | //===- AMDGPUOpenMP.cpp - AMDGPUOpenMP ToolChain Implementation -*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "AMDGPUOpenMP.h"
#include "AMDGPU.h"
#include "CommonArgs.h"
#include "InputInfo.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
using namespace clang::driver;
using namespace clang::driver::toolchains;
using namespace clang::driver::tools;
using namespace clang;
using namespace llvm::opt;
namespace {
static const char *getOutputFileName(Compilation &C, StringRef Base,
const char *Postfix,
const char *Extension) {
const char *OutputFileName;
if (C.getDriver().isSaveTempsEnabled()) {
OutputFileName =
C.getArgs().MakeArgString(Base.str() + Postfix + "." + Extension);
} else {
std::string TmpName =
C.getDriver().GetTemporaryPath(Base.str() + Postfix, Extension);
OutputFileName = C.addTempFile(C.getArgs().MakeArgString(TmpName));
}
return OutputFileName;
}
static void addLLCOptArg(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs) {
if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
StringRef OOpt = "0";
if (A->getOption().matches(options::OPT_O4) ||
A->getOption().matches(options::OPT_Ofast))
OOpt = "3";
else if (A->getOption().matches(options::OPT_O0))
OOpt = "0";
else if (A->getOption().matches(options::OPT_O)) {
// Clang and opt support -Os/-Oz; llc only supports -O0, -O1, -O2 and -O3
// so we map -Os/-Oz to -O2.
// Only clang supports -Og, and maps it to -O1.
// We map anything else to -O2.
OOpt = llvm::StringSwitch<const char *>(A->getValue())
.Case("1", "1")
.Case("2", "2")
.Case("3", "3")
.Case("s", "2")
.Case("z", "2")
.Case("g", "1")
.Default("0");
}
CmdArgs.push_back(Args.MakeArgString("-O" + OOpt));
}
}
} // namespace
const char *AMDGCN::OpenMPLinker::constructLLVMLinkCommand(
Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
const ArgList &Args, StringRef SubArchName,
StringRef OutputFilePrefix) const {
ArgStringList CmdArgs;
for (const auto &II : Inputs)
if (II.isFilename())
CmdArgs.push_back(II.getFilename());
// Add an intermediate output file.
CmdArgs.push_back("-o");
const char *OutputFileName =
getOutputFileName(C, OutputFilePrefix, "-linked", "bc");
CmdArgs.push_back(OutputFileName);
const char *Exec =
Args.MakeArgString(getToolChain().GetProgramPath("llvm-link"));
C.addCommand(std::make_unique<Command>(
JA, *this, ResponseFileSupport::AtFileCurCP(), Exec, CmdArgs, Inputs,
InputInfo(&JA, Args.MakeArgString(OutputFileName))));
return OutputFileName;
}
const char *AMDGCN::OpenMPLinker::constructLlcCommand(
Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
const llvm::opt::ArgList &Args, llvm::StringRef SubArchName,
llvm::StringRef OutputFilePrefix, const char *InputFileName,
bool OutputIsAsm) const {
// Construct llc command.
ArgStringList LlcArgs;
// The input to llc is the output from opt.
LlcArgs.push_back(InputFileName);
// Pass optimization arg to llc.
addLLCOptArg(Args, LlcArgs);
LlcArgs.push_back("-mtriple=amdgcn-amd-amdhsa");
LlcArgs.push_back(Args.MakeArgString("-mcpu=" + SubArchName));
LlcArgs.push_back(
Args.MakeArgString(Twine("-filetype=") + (OutputIsAsm ? "asm" : "obj")));
for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
LlcArgs.push_back(A->getValue(0));
}
// Add output filename
LlcArgs.push_back("-o");
const char *LlcOutputFile =
getOutputFileName(C, OutputFilePrefix, "", OutputIsAsm ? "s" : "o");
LlcArgs.push_back(LlcOutputFile);
const char *Llc = Args.MakeArgString(getToolChain().GetProgramPath("llc"));
C.addCommand(std::make_unique<Command>(
JA, *this, ResponseFileSupport::AtFileCurCP(), Llc, LlcArgs, Inputs,
InputInfo(&JA, Args.MakeArgString(LlcOutputFile))));
return LlcOutputFile;
}
void AMDGCN::OpenMPLinker::constructLldCommand(
Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
const InputInfo &Output, const llvm::opt::ArgList &Args,
const char *InputFileName) const {
// Construct lld command.
// The output from ld.lld is an HSA code object file.
ArgStringList LldArgs{"-flavor", "gnu", "--no-undefined",
"-shared", "-o", Output.getFilename(),
InputFileName};
const char *Lld = Args.MakeArgString(getToolChain().GetProgramPath("lld"));
C.addCommand(std::make_unique<Command>(
JA, *this, ResponseFileSupport::AtFileCurCP(), Lld, LldArgs, Inputs,
InputInfo(&JA, Args.MakeArgString(Output.getFilename()))));
}
// For amdgcn the inputs of the linker job are device bitcode and output is
// object file. It calls llvm-link, opt, llc, then lld steps.
void AMDGCN::OpenMPLinker::ConstructJob(Compilation &C, const JobAction &JA,
const InputInfo &Output,
const InputInfoList &Inputs,
const ArgList &Args,
const char *LinkingOutput) const {
assert(getToolChain().getTriple().isAMDGCN() && "Unsupported target");
StringRef GPUArch = Args.getLastArgValue(options::OPT_march_EQ);
assert(GPUArch.startswith("gfx") && "Unsupported sub arch");
// Prefix for temporary file name.
std::string Prefix;
for (const auto &II : Inputs)
if (II.isFilename())
Prefix =
llvm::sys::path::stem(II.getFilename()).str() + "-" + GPUArch.str();
assert(Prefix.length() && "no linker inputs are files ");
// Each command outputs different files.
const char *LLVMLinkCommand =
constructLLVMLinkCommand(C, JA, Inputs, Args, GPUArch, Prefix);
const char *LlcCommand = constructLlcCommand(C, JA, Inputs, Args, GPUArch,
Prefix, LLVMLinkCommand);
constructLldCommand(C, JA, Inputs, Output, Args, LlcCommand);
}
AMDGPUOpenMPToolChain::AMDGPUOpenMPToolChain(const Driver &D,
const llvm::Triple &Triple,
const ToolChain &HostTC,
const ArgList &Args)
: ROCMToolChain(D, Triple, Args), HostTC(HostTC) {
// Lookup binaries into the driver directory, this is used to
// discover the clang-offload-bundler executable.
getProgramPaths().push_back(getDriver().Dir);
}
void AMDGPUOpenMPToolChain::addClangTargetOptions(
const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
Action::OffloadKind DeviceOffloadingKind) const {
HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
assert(DeviceOffloadingKind == Action::OFK_OpenMP &&
"Only OpenMP offloading kinds are supported.");
CC1Args.push_back("-target-cpu");
CC1Args.push_back(DriverArgs.MakeArgStringRef(GpuArch));
CC1Args.push_back("-fcuda-is-device");
CC1Args.push_back("-emit-llvm-bc");
}
llvm::opt::DerivedArgList *AMDGPUOpenMPToolChain::TranslateArgs(
const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
Action::OffloadKind DeviceOffloadKind) const {
DerivedArgList *DAL =
HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
if (!DAL)
DAL = new DerivedArgList(Args.getBaseArgs());
const OptTable &Opts = getDriver().getOpts();
if (DeviceOffloadKind != Action::OFK_OpenMP) {
for (Arg *A : Args) {
DAL->append(A);
}
}
if (!BoundArch.empty()) {
DAL->eraseArg(options::OPT_march_EQ);
DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ),
BoundArch);
}
return DAL;
}
Tool *AMDGPUOpenMPToolChain::buildLinker() const {
assert(getTriple().isAMDGCN());
return new tools::AMDGCN::OpenMPLinker(*this);
}
void AMDGPUOpenMPToolChain::addClangWarningOptions(
ArgStringList &CC1Args) const {
HostTC.addClangWarningOptions(CC1Args);
}
ToolChain::CXXStdlibType
AMDGPUOpenMPToolChain::GetCXXStdlibType(const ArgList &Args) const {
return HostTC.GetCXXStdlibType(Args);
}
void AMDGPUOpenMPToolChain::AddClangSystemIncludeArgs(
const ArgList &DriverArgs, ArgStringList &CC1Args) const {
HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
}
void AMDGPUOpenMPToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
ArgStringList &CC1Args) const {
HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
}
SanitizerMask AMDGPUOpenMPToolChain::getSupportedSanitizers() const {
// The AMDGPUOpenMPToolChain only supports sanitizers in the sense that it
// allows sanitizer arguments on the command line if they are supported by the
// host toolchain. The AMDGPUOpenMPToolChain will actually ignore any command
// line arguments for any of these "supported" sanitizers. That means that no
// sanitization of device code is actually supported at this time.
//
// This behavior is necessary because the host and device toolchains
// invocations often share the command line, so the device toolchain must
// tolerate flags meant only for the host toolchain.
return HostTC.getSupportedSanitizers();
}
VersionTuple
AMDGPUOpenMPToolChain::computeMSVCVersion(const Driver *D,
const ArgList &Args) const {
return HostTC.computeMSVCVersion(D, Args);
}
| [
"[email protected]"
]
| |
f640a2d601136f111bbdb491f7c840f1653f1317 | e2e3cf2edf60eeb6dd45adaa8a58e110bdef92d9 | /Portable/zoolib/PullPush_ZZ.cpp | aee05256aa7bd0f1d1ce5c56f13c1a902e91705a | [
"MIT"
]
| permissive | zoolib/zoolib_cxx | 0ae57b83d8b3d8c688ee718b236e678b128c0ac7 | b415ef23476afdad89d61a003543570270a85844 | refs/heads/master | 2023-03-22T20:53:40.334006 | 2023-03-11T23:44:22 | 2023-03-11T23:44:22 | 3,355,296 | 17 | 5 | MIT | 2023-03-11T23:44:23 | 2012-02-04T20:54:08 | C++ | UTF-8 | C++ | false | false | 5,909 | cpp | // Copyright (c) 2018-2019 Andrew Green. MIT License. http://www.zoolib.org
#include "zoolib/PullPush_ZZ.h"
#include "zoolib/Channer_Bin.h"
#include "zoolib/Channer_UTF.h"
#include "zoolib/Chan_Bin_Data.h"
#include "zoolib/Chan_UTF_string.h"
#include "zoolib/ChanR_UTF.h"
#include "zoolib/NameUniquifier.h"
#include "zoolib/ParseException.h"
#include "zoolib/StartOnNewThread.h"
#include "zoolib/Val_ZZ.h"
namespace ZooLib {
using std::string;
// =================================================================================================
#pragma mark -
void sFromZZ_Push_PPT(const Val_ZZ& iVal,
const ZP<Callable_ZZ_WriteFilter>& iWriteFilter,
const ChanW_PPT& iChanW)
{
if (const Seq_ZZ* theSeq = sPGet<Seq_ZZ>(iVal))
{
sPush_Start_Seq(iChanW);
for (size_t xx = 0; xx < theSeq->Count(); ++xx)
sFromZZ_Push_PPT(theSeq->Get(xx).As<Val_ZZ>(), iWriteFilter, iChanW);
sPush_End(iChanW);
}
else if (const Map_ZZ* theMap = sPGet<Map_ZZ>(iVal))
{
sPush_Start_Map(iChanW);
for (Map_ZZ::Index_t iter = theMap->Begin(), end = theMap->End();
iter != end; ++iter)
{
sPush(sName(iter->first), iChanW);
sFromZZ_Push_PPT(iter->second.As<Val_ZZ>(), iWriteFilter, iChanW);
}
sPush_End(iChanW);
}
// Could add in support for other map/seq types.
else if (const string* theString = sPGet<string>(iVal))
{
sPush(*theString, iChanW);
// sPull_UTF_Push(ChanRU_UTF_string8(*theString), iChanW);
}
else if (const Data_ZZ* theData = sPGet<Data_ZZ>(iVal))
{
sPull_Bin_Push_PPT(ChanRPos_Bin_Data<Data_ZZ>(*theData), iChanW);
}
else if (not iWriteFilter || not sCall(iWriteFilter, iVal, iChanW))
{
sPush(iVal.As<PPT>(), iChanW);
}
}
void sFromZZ_Push_PPT(const Val_ZZ& iVal,
const ChanW_PPT& iChanW)
{ sFromZZ_Push_PPT(iVal, null, iChanW); }
static void spFromZZ_Push_PPT_Disconnect(const Val_ZZ& iVal,
const ZP<Callable_ZZ_WriteFilter>& iWriteFilter,
const ZP<ChannerWCon_PPT>& iChannerWCon)
{
sFromZZ_Push_PPT(iVal, iWriteFilter, *iChannerWCon);
sDisconnectWrite(*iChannerWCon);
}
// =================================================================================================
#pragma mark - sChannerR_PPT_xx
ZP<ChannerR_PPT> sChannerR_PPT(const Val_ZZ& iVal,
const ZP<Callable_ZZ_WriteFilter>& iWriteFilter)
{
PullPushPair<PPT> thePair = sMakePullPushPair<PPT>();
sStartOnNewThread(
sBindR(sCallable(spFromZZ_Push_PPT_Disconnect),
iVal, iWriteFilter, sGetClear(thePair.first)));
return thePair.second;
}
ZP<ChannerR_PPT> sChannerR_PPT(const Val_ZZ& iVal)
{ return sChannerR_PPT(iVal, null); }
// =================================================================================================
#pragma mark -
void sPull_PPT_AsZZ(const PPT& iPPT,
const ChanR_PPT& iChanR,
const ZP<Callable_ZZ_ReadFilter>& iReadFilter,
Val_ZZ& oVal)
{
// Handle the filter *first*, in case we may have Start derivatives in the chan.
if (iReadFilter)
{
if (ZQ<bool> theQ = iReadFilter->QCall(iPPT, iChanR, oVal))
{
if (*theQ)
return;
}
}
// Handle standard stuff.
if (const string* theString = sPGet<string>(iPPT))
{
oVal = *theString;
return;
}
if (ZP<ChannerR_UTF> theChanner = sGet<ZP<ChannerR_UTF>>(iPPT))
{
oVal = sReadAllUTF8(*theChanner);
return;
}
if (const Data_ZZ* theData = sPGet<Data_ZZ>(iPPT))
{
oVal = *theData;
return;
}
if (ZP<ChannerR_Bin> theChanner = sGet<ZP<ChannerR_Bin>>(iPPT))
{
oVal = sReadAll_T<Data_ZZ>(*theChanner);
return;
}
if (sIsStart_Map(iPPT))
{
Map_ZZ theMap;
for (;;)
{
if (NotQ<Name> theNameQ = sQEReadNameOrEnd(iChanR))
{
break;
}
else if (NotQ<PPT> thePPTQ = sQRead(iChanR))
{
sThrow_ParseException("Require value after Name from ChanR_PPT");
}
else
{
Val_ZZ theVal;
sPull_PPT_AsZZ(*thePPTQ, iChanR, iReadFilter, theVal);
theMap.Set(*theNameQ, theVal.As<Val_ZZ>());
}
}
oVal = theMap;
return;
}
// This could be just Start, to generically handle Start derivatives
if (sIsStart_Seq(iPPT))
{
Seq_ZZ theSeq;
for (;;)
{
if (NotQ<PPT> thePPTQ = sQEReadPPTOrEnd(iChanR))
{
break;
}
else
{
Val_ZZ theVal;
sPull_PPT_AsZZ(*thePPTQ, iChanR, iReadFilter, theVal);
theSeq.Append(theVal.As<Val_ZZ>());
}
}
oVal = theSeq;
return;
}
oVal = iPPT.As<Val_ZZ>();
}
bool sPull_PPT_AsZZ(const ChanR_PPT& iChanR,
const ZP<Callable_ZZ_ReadFilter>& iReadFilter,
Val_ZZ& oVal)
{
if (ZQ<PPT> theQ = sQRead(iChanR))
{
sPull_PPT_AsZZ(*theQ, iChanR, iReadFilter, oVal);
return true;
}
return false;
}
bool sPull_PPT_AsZZ(const ChanR_PPT& iChanR, Val_ZZ& oVal)
{ return sPull_PPT_AsZZ(iChanR, null, oVal); }
Val_ZZ sAsZZ(const PPT& iPPT, const ChanR_PPT& iChanR)
{
Val_ZZ theVal;
sPull_PPT_AsZZ(iPPT, iChanR, null, theVal);
return theVal;
}
ZQ<Val_ZZ> sQAsZZ(const ChanR_PPT& iChanR)
{
if (ZQ<PPT> theQ = sQRead(iChanR))
return sAsZZ(*theQ, iChanR);
return null;
}
Val_ZZ sAsZZ(const ChanR_PPT& iChanR)
{
if (ZQ<PPT> theQ = sQRead(iChanR))
{
Val_ZZ theVal;
sPull_PPT_AsZZ(*theQ, iChanR, null, theVal);
return theVal;
}
return Val_ZZ();
}
static void spAsync_AsZZ(const ZP<ChannerR_PPT>& iChannerR,
const ZP<Callable_ZZ_ReadFilter>& iReadFilter,
const ZP<Promise<Val_ZZ>>& iPromise)
{
ZThread::sSetName("spAsync_AsZZ");
Val_ZZ result;
if (sPull_PPT_AsZZ(*iChannerR, iReadFilter, result))
iPromise->Deliver(result);
}
ZP<Delivery<Val_ZZ>> sStartAsync_AsZZ(const ZP<ChannerR_PPT>& iChannerR)
{ return sStartAsync_AsZZ(iChannerR, null); }
ZP<Delivery<Val_ZZ>> sStartAsync_AsZZ(const ZP<ChannerR_PPT>& iChannerR,
const ZP<Callable_ZZ_ReadFilter>& iReadFilter)
{
ZP<Promise<Val_ZZ>> thePromise = sPromise<Val_ZZ>();
sStartOnNewThread(sBindR(sCallable(spAsync_AsZZ), iChannerR, iReadFilter, thePromise));
return thePromise->GetDelivery();
}
} // namespace ZooLib
| [
"[email protected]"
]
| |
2e277febae3fef41762c8977b9a527ee30013306 | 6b0ed1000d6340fe8e0a5b5a0be609bf42ad5a50 | /1287.cpp | db01f72be0bac5843837927ea7a7056d0306a4e2 | []
| no_license | HarshRaikwar/Leetcode-Submissions | 5bcdb96b63548cf0bb4522258800ebb7a3ae8b29 | 6b7aeb5def21e6652ad7b299f472e8152bafaab0 | refs/heads/master | 2023-07-29T18:50:46.607706 | 2021-09-13T14:35:47 | 2021-09-13T14:35:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 239 | cpp | class Solution {
public:
int findSpecialInteger(vector<int>& arr) {
int n=arr.size();
int l=n/4;
for(int i=0;i<n-l;i++)
if(arr[i]==arr[i+l])
return arr[i];
return -1;
}
}; | [
"[email protected]"
]
| |
993ad30c0f7cc21303ac663d2da364a1db4da6bc | fbf49ac1585c87725a0f5edcb80f1fe7a6c2041f | /SDK/Icon_Clear_S_parameters.h | 5d57d5fbd1dc0fa01bef8a8c12e502859f3cda20 | []
| no_license | zanzo420/DBZ-Kakarot-SDK | d5a69cd4b147d23538b496b7fa7ba4802fccf7ac | 73c2a97080c7ebedc7d538f72ee21b50627f2e74 | refs/heads/master | 2021-02-12T21:14:07.098275 | 2020-03-16T10:07:00 | 2020-03-16T10:07:00 | 244,631,123 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 775 | h | #pragma once
#include "../SDK.h"
// Name: DBZKakarot, Version: 1.0.3
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function Icon_Clear_S.Icon_Clear_S_C.Construct
struct UIcon_Clear_S_C_Construct_Params
{
};
// Function Icon_Clear_S.Icon_Clear_S_C.ExecuteUbergraph_Icon_Clear_S
struct UIcon_Clear_S_C_ExecuteUbergraph_Icon_Clear_S_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
]
| |
5b34ab53ad1753129f868fd9941fd283fbdc1c47 | c1cd9648b9c2720aee02d71ea8233cb475462c77 | /SC-LeGO-LOAM_noted/SC-LeGO-LOAM/LeGO-LOAM/include/scan_context/KDTreeVectorOfVectorsAdaptor.h | 3321d95ba29b80434fabbe77991af75e3d4e3b9b | [
"BSD-3-Clause"
]
| permissive | idontlikelongname/opensource_slam_noted | 9fb953effdbc15793fbea75fe556e1625dfd9318 | 0b53d113a306b4d086c8695a170e6d5f14dd44b4 | refs/heads/master | 2023-06-22T08:34:37.525467 | 2021-07-15T05:42:01 | 2021-07-15T05:42:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,449 | h | /***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2011-16 Jose Luis Blanco ([email protected]).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#pragma once
#include <scan_context/nanoflann.hpp>
#include <vector>
// ===== This example shows how to use nanoflann with these types of containers: =======
//typedef std::vector<std::vector<double> > my_vector_of_vectors_t;
//typedef std::vector<Eigen::VectorXd> my_vector_of_vectors_t; // This requires #include <Eigen/Dense>
// =====================================================================================
/** A simple vector-of-vectors adaptor for nanoflann, without duplicating the storage.
* The i'th vector represents a point in the state space.
*
* \tparam DIM If set to >0, it specifies a compile-time fixed dimensionality for the points in the data set, allowing more compiler optimizations.
* \tparam num_t The type of the point coordinates (typically, double or float).
* \tparam Distance The distance metric to use: nanoflann::metric_L1, nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc.
* \tparam IndexType The type for indices in the KD-tree index (typically, size_t of int)
*/
template <class VectorOfVectorsType, typename num_t = double, int DIM = -1, class Distance = nanoflann::metric_L2, typename IndexType = size_t>
struct KDTreeVectorOfVectorsAdaptor
{
typedef KDTreeVectorOfVectorsAdaptor<VectorOfVectorsType,num_t,DIM,Distance> self_t;
typedef typename Distance::template traits<num_t,self_t>::distance_t metric_t;
typedef nanoflann::KDTreeSingleIndexAdaptor< metric_t,self_t,DIM,IndexType> index_t;
index_t* index; //! The kd-tree index for the user to call its methods as usual with any other FLANN index.
/// Constructor: takes a const ref to the vector of vectors object with the data points
KDTreeVectorOfVectorsAdaptor(const size_t /* dimensionality */, const VectorOfVectorsType &mat, const int leaf_max_size = 10) : m_data(mat)
{
assert(mat.size() != 0 && mat[0].size() != 0);
const size_t dims = mat[0].size();
if (DIM>0 && static_cast<int>(dims) != DIM)
throw std::runtime_error("Data set dimensionality does not match the 'DIM' template argument");
index = new index_t( static_cast<int>(dims), *this /* adaptor */, nanoflann::KDTreeSingleIndexAdaptorParams(leaf_max_size ) );
index->buildIndex();
}
~KDTreeVectorOfVectorsAdaptor() {
delete index;
}
const VectorOfVectorsType &m_data;
/** Query for the \a num_closest closest points to a given point (entered as query_point[0:dim-1]).
* Note that this is a short-cut method for index->findNeighbors().
* The user can also call index->... methods as desired.
* \note nChecks_IGNORED is ignored but kept for compatibility with the original FLANN interface.
*/
inline void query(const num_t *query_point, const size_t num_closest, IndexType *out_indices, num_t *out_distances_sq, const int nChecks_IGNORED = 10) const
{
nanoflann::KNNResultSet<num_t,IndexType> resultSet(num_closest);
resultSet.init(out_indices, out_distances_sq);
index->findNeighbors(resultSet, query_point, nanoflann::SearchParams());
}
/** @name Interface expected by KDTreeSingleIndexAdaptor
* @{ */
const self_t & derived() const {
return *this;
}
self_t & derived() {
return *this;
}
// Must return the number of data points
inline size_t kdtree_get_point_count() const {
return m_data.size();
}
// Returns the dim'th component of the idx'th point in the class:
inline num_t kdtree_get_pt(const size_t idx, const size_t dim) const {
return m_data[idx][dim];
}
// Optional bounding-box computation: return false to default to a standard bbox computation loop.
// Return true if the BBOX was already computed by the class and returned in "bb" so it can be avoided to redo it again.
// Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds)
template <class BBOX>
bool kdtree_get_bbox(BBOX & /*bb*/) const {
return false;
}
/** @} */
}; // end of KDTreeVectorOfVectorsAdaptor
| [
"[email protected]"
]
| |
2c27528533b96e12490302311f75ad58e0dee9cc | 52f5c428de18998913108f8e368b3ade5ca65217 | /VideoEffects/src/VideoTexture.cpp | cb4a42d422784dbbd5670b15654b5cf0353c3824 | []
| no_license | cache-tlb/VideoEffects | 4d6c03d43dc9943173a467f15a9e79e0055d94c7 | 755e848e5c9db4d545ee21c464d7f9e55f9a351d | refs/heads/master | 2021-01-10T22:08:29.236172 | 2017-09-13T08:02:25 | 2017-09-13T08:02:25 | 23,761,060 | 9 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,720 | cpp | #include "VideoTexture.h"
VideoTexture::VideoTexture(int w, int h, cv::VideoCapture &_cap)
: width(w), height(h), cap(_cap), timeStamp(clock()), dataSize(w*h*3)
{
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// format is GL_RGB
// type is GL_UNSIGNED_BYTE;
/*
glGenBuffersARB(2, pboIds);
glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pboIds[0]);
glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, dataSize, 0, GL_STREAM_DRAW_ARB);
glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pboIds[1]);
glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, dataSize, 0, GL_STREAM_DRAW_ARB);
glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
*/
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
}
VideoTexture::~VideoTexture() {}
void VideoTexture::play() {
timeStamp = clock();
}
void VideoTexture::bind(int unit /* = 0 */) {
glActiveTexture(GL_TEXTURE0 + unit);
glBindTexture(GL_TEXTURE_2D, textureId);
}
void VideoTexture::unbind(int unit /* = 0 */) {
glActiveTexture(GL_TEXTURE0 + unit);
glBindTexture(GL_TEXTURE_2D, 0);
}
void VideoTexture::updateFrame() {
clock_t currentTime = clock();
double elapsed_secs = double(currentTime - timeStamp) / CLOCKS_PER_SEC;
double frame_ms = cap.get(CV_CAP_PROP_POS_MSEC);
bool refreshed = false;
while (elapsed_secs*1000.0 > frame_ms){
refreshed = true;
if (cap.get(CV_CAP_PROP_POS_FRAMES) == cap.get(CV_CAP_PROP_FRAME_COUNT)) {
cap.set(CV_CAP_PROP_POS_FRAMES, 0.0);
timeStamp = currentTime;
elapsed_secs = 0;
}
cap.read(videoFrame);
frame_ms = cap.get(CV_CAP_PROP_POS_MSEC);
}
if (refreshed) {
glBindTexture(GL_TEXTURE_2D, textureId);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_BGR, GL_UNSIGNED_BYTE, videoFrame.data);
/*glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pboIds[0]);
glBufferSubData(GL_PIXEL_UNPACK_BUFFER_ARB, 0, dataSize, (void *)videoFrame.data);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_BGR, GL_UNSIGNED_BYTE, 0);*/
}
}
VideoTexture *VideoTexture::fromFile(const std::string &path) {
cv::VideoCapture cap(path);
int width = cap.get(CV_CAP_PROP_FRAME_WIDTH), height = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
VideoTexture *texture = new VideoTexture(width, height, cap);
return texture;
}
| [
"[email protected]"
]
| |
bad385786ba17e6401d74c11353c346d1baad9cf | 40ca25790d253de56dba15ec8362cf046db05ca0 | /data-structures/add_two_numbers.cpp | c01ea6c31b44af900398d38638ab69021f83d690 | []
| no_license | Hapiny/programming-problems | 63271f30c4d0bece90331101aad833231f1ae14e | 57609dee664b56646662ceab3f6f1f839e77b67f | refs/heads/master | 2022-11-27T01:31:50.561434 | 2020-08-05T20:29:30 | 2020-08-05T20:29:30 | 281,125,517 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,200 | cpp | #include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
void print_list(ListNode* head) {
ListNode* tmp = head;
while (tmp) {
cout << tmp->val << " ";
tmp = tmp->next;
}
cout << endl;
}
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int num1, num2, sum = 0, add = 0;
ListNode* lst = new ListNode();
ListNode* head = lst;
while (l1 || l2) {
num1 = l1 ? l1->val : 0;
num2 = l2 ? l2->val : 0;
sum = num1 + num2 + add;
if (sum > 9) {
lst->val = sum % 10;
if (!add)
add += 1;
} else {
lst->val = sum;
add = 0;
}
if (l1)
l1 = l1->next;
if (l2)
l2 = l2->next;
if (l1 || l2) {
lst->next = new ListNode();
lst = lst->next;
}
}
if (add) {
while (add > 9) {
lst->next = new ListNode();
lst = lst->next;
lst->val = add % 10;
add /= 10;
}
if (add) {
lst->next = new ListNode();
lst = lst->next;
lst->val = add;
}
}
return head;
}
};
int main() {
ListNode* l1 = new ListNode();
ListNode* l2 = new ListNode();
ListNode* tmp1 = l1;
ListNode* tmp2 = l2;
tmp1->val = 1;
// tmp1->next = new ListNode();
// tmp1 = tmp1->next;
//
// tmp1->val = 9;
tmp2->val = 9;
tmp2->next = new ListNode();
tmp2 = tmp2->next;
tmp2->val = 9;
cout << "First list:" << endl;
print_list(l1);
cout << "Second list:" << endl;
print_list(l2);
cout << endl;
Solution solver;
ListNode* list_sum = solver.addTwoNumbers(l1, l2);
cout << "Result list:" << endl;
print_list(list_sum);
return 0;
} | [
"[email protected]"
]
| |
663c97b30474108b634c55e412d1b68a57483ee5 | 3c09d1c279c8578791dae535852c06e09efad4a1 | /EclipseCpp/EuroDripShop2007/src/Shop.h | 37f68153d16f67a98323ecf38242fac62113a9dc | []
| no_license | rosen90/GitHub | f00653f8a65cdffc479b70d2d7ca8f9e103d3eeb | 851d210f2f6073d818e0984fa9daab96e833b066 | refs/heads/master | 2016-09-12T23:57:19.530896 | 2016-05-04T22:09:03 | 2016-05-04T22:09:03 | 58,085,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 822 | h | #ifndef SHOP_H_
#define SHOP_H_
#include "Sales.h"
#include "CashDesk.h"
#include "Date.h"
#include "scrappingClothes.h"
#include "StockLoad.h"
class Shop {
public:
Shop(StockLoad, Sales, scrappingClothes, CashDesk);
virtual ~Shop();
const scrappingClothes& getScapChloths() const;
void setScapChloths(const scrappingClothes& scapChloths);
const CashDesk& getShopCash() const;
void setShopCash(const CashDesk& shopCash);
const Sales& getShopSales() const;
void setShopSales(const Sales& shopSales);
const StockLoad& getShopStockLoad() const;
void setShopStockLoad(const StockLoad& shopStockLoad);
void printInfo();
void printiMoney();
void cashNow();
void saleInfo();
void cashAfterSale();
private:
StockLoad shopStockLoad;
Sales shopSales;
scrappingClothes scapChloths;
CashDesk shopCash;
};
#endif
| [
"[email protected]"
]
| |
e893dddbc0f817dfec1737f354a390d5ce232063 | 02987503becabd24aa359d6ceabcb332ad8c6302 | /sgpp-1.1.0/datadriven/src/sgpp/datadriven/application/BatchLearner.cpp | c944061c152ca507506945678f951eab047227f0 | []
| no_license | HappyTiger1/Sparse-Grids | a9c07527481ee28fe24abed6dad378ca9fc6d466 | 2832b262c1aeaa25312a3f7e48c5a67c90d183a5 | refs/heads/master | 2020-05-07T14:06:20.673900 | 2016-08-08T17:57:12 | 2016-08-08T17:57:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,985 | cpp | // Copyright (C) 2008-today The SG++ project
// This file is part of the SG++ project. For conditions of distribution and
// use, please see the copyright notice provided with SG++ or at
// sgpp.sparsegrids.org
#include <sgpp/datadriven/application/BatchLearner.hpp>
#include <sgpp/base/datatypes/DataVector.hpp>
#include <sgpp/base/grid/Grid.hpp>
#include <sgpp/base/grid/GridStorage.hpp>
#include <sgpp/base/grid/generation/GridGenerator.hpp>
#include <sgpp/base/operation/hash/OperationEval.hpp>
#include <sgpp/base/operation/BaseOpFactory.hpp>
#include <sgpp/datadriven/tools/ARFFTools.hpp>
#include <sgpp/base/grid/type/LinearGrid.hpp>
#include <sgpp/datadriven/algorithm/DensitySystemMatrix.hpp>
#include <sgpp/solver/SLESolver.hpp>
#include <sgpp/solver/sle/ConjugateGradients.hpp>
#include <sgpp/solver/sle/BiCGStab.hpp>
#include <sgpp/base/operation/hash/OperationMatrix.hpp>
#include <sgpp/datadriven/tools/Dataset.hpp>
#include <sgpp/base/grid/generation/functors/SurplusRefinementFunctor.hpp>
#include <sgpp/base/exception/application_exception.hpp>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <cstdlib>
#include <vector>
#include <sstream>
#include <cmath>
#include <deque>
#include <algorithm>
#include <utility>
#include <limits>
// using base;
using std::string;
using std::cout;
using std::endl;
using std::vector;
using std::numeric_limits;
using std::max;
using std::deque;
namespace SGPP {
namespace datadriven {
BatchLearner::BatchLearner(
base::BatchConfiguration batchConfig,
base::RegularGridConfiguration gridConfig,
solver::SLESolverConfiguration solverConfig,
base::AdpativityConfiguration adaptConfig) {
batchConf = batchConfig;
gridConf = gridConfig;
solverConf = solverConfig;
adaptConf = adaptConfig;
// cofigure solver
if (solverConf.type_ == solver::SLESolverType::CG)
myCG = new solver::ConjugateGradients(solverConf.maxIterations_,
solverConf.eps_);
else if (solverConf.type_ == solver::SLESolverType::BiCGSTAB)
myCG = new solver::BiCGStab(solverConf.maxIterations_, solverConf.eps_);
else // not supported
throw base::application_exception("BatchLearner: An unsupported SLE solver type was chosen!");
// open file
reader.open(batchConf.filename.c_str());
if (!reader) {
cout << "ERROR: file does not exist: " << batchConf.filename << endl;
throw 20;
}
}
// read input, save result to dataFound and last entry to classFound,
// based on ARFFTools.readARFF(..)
void BatchLearner::stringToDataVector(string input, base::DataVector& dataFound,
int& classFound) {
size_t cur_pos = 0;
size_t cur_find = 0;
string cur_value;
float_t dbl_cur_value;
base::DataVector temprow(dimensions);
for (size_t j = 0; j <= dimensions; j++) {
cur_find = input.find(",", cur_pos);
cur_value = input.substr(cur_pos, cur_find - cur_pos);
dbl_cur_value = atof(cur_value.c_str());
if (j == dimensions)
classFound = static_cast<int>(dbl_cur_value);
else
temprow.set(j, dbl_cur_value);
cur_pos = cur_find + 1;
}
dataFound.resize(temprow.getSize());
dataFound.copyFrom(temprow);
}
// if (mapdata): data is mapped, dataFound/classesFound will not be changed
void BatchLearner::stringToDataMatrix(string& input, base::DataMatrix& dataFound,
base::DataVector& classesFound, bool mapData) {
if (mapData) {
dataInBatch.clear();
} else {
dataFound.resize(0, dimensions);
dataFound.setAll(0.0f); // needed?
classesFound.resize(0);
classesFound.setAll(0.0f); // needed?
}
// as data in input is provided as a string containing all lines: split them at '\n'
// to vector data to iterate over
vector <string> data;
size_t start = 0, end = 0;
while ((end = input.find('\n', start)) != string::npos) {
data.push_back(input.substr(start, end - start));
start = end + 1;
}
data.push_back(input.substr(start));
// iterate over all found lines
for (size_t i = 0; i < data.size() - 1; i++) {
size_t classesHere = static_cast<size_t>(
count(data[i].begin(), data[i].end(), ','));
// the first data entry ever found determines the number of dimensions of the data
if (dimensions == 0) {
dimensions = classesHere;
dataFound.resize(dimensions, 0);
dataFound.setAll(0.0f);
} else if (classesHere != dimensions) {
cout << "skipping line " << i <<
" because it contains too few or too many classes (previous/now): " <<
dimensions << "/" << classesHere << endl;
continue;
}
base::DataVector lineData(0);
int lineClass = -1;
stringToDataVector(data[i], lineData, lineClass);
if (mapData) {
if (dataInBatch.find(lineClass) ==
dataInBatch.end()) // first data entry for this class in this batch
dataInBatch.insert(std::pair<int, base::DataMatrix*>(lineClass, new base::DataMatrix(0,
dimensions, float_t(-1.0) )));
// add found data entry to correct base::DataMatrix in map
dataInBatch.at(lineClass)->appendRow(lineData);
} else {
dataFound.appendRow(lineData);
classesFound.append(static_cast<float_t>(lineClass));
}
}
}
base::DataVector BatchLearner::applyWeight(base::DataVector alpha, int grid) {
// wMode 4: only the last batch is relevant -> no further calculations needed, alpha = new
if (batchConf.wMode == 4)
return alpha;
if (alphaStorage.find(grid) == alphaStorage.end()) {
// if there is no previous alpha known for this grid: store this alpha and return the input
deque<base::DataVector> temp;
alphaStorage.insert(std::make_pair(grid, temp));
alphaStorage.at(grid).push_back(alpha);
return alpha;
}
// wMode 5: weigh old alpha with new alpha by occurences
if (batchConf.wMode == 5) {
float_t k = (float_t) dataInBatch.at(grid)->getNrows();
float_t n = (float_t) occurences.at(grid);
float_t wNew = max(k / (n + k), (float_t)batchConf.wArgument);
if (batchConf.verbose)
cout << "old weight: " << 1.0 - wNew << " new weight: " << wNew << endl;
base::DataVector* old = new base::DataVector(alphaStorage.at(grid)[0]); // old alpha
old->mult(1.0 - wNew);
base::DataVector* now = new base::DataVector(alpha); // new alpha
now->mult(wNew);
old->resizeZero(now->getSize()); // refinement
now->add(*old);
alphaStorage.at(grid)[0].resizeZero(now->getSize()); // refinement
alphaStorage.at(grid)[0].copyFrom(*now);
return *now;
} else { // store all alphas if not in wMode 4 or 5
alphaStorage.at(grid).push_back(alpha);
}
// move old alphas to add new one
if (alphaStorage.at(grid).size() > batchConf.stack && batchConf.stack != 0) {
// remove the last item (assumtion: only need to delete one bcs only added here
alphaStorage.at(grid).pop_front();
}
size_t count = alphaStorage.at(
grid).size(); // count of old alphas available for calculation
vector<float_t> factors;
// previous alphas exist
// calc factors
float_t sum = 0.0f;
for (size_t i = 0; i < count; i++) {
if (batchConf.wMode == 0) {
factors.push_back((float_t)1); // temp: all alphas are equal
} else if (batchConf.wMode == 1) {
factors.push_back((float_t)(i + 1)*batchConf.wArgument); // linear
} else if (batchConf.wMode == 2) {
factors.push_back((float_t)pow(batchConf.wArgument,
static_cast<float_t>(i + 1))); // exp
} else if (batchConf.wMode == 3) {
factors.push_back((float_t)batchConf.wArgument / (float_t)(
i + 1)); // 1/x bzw arg/x
} else if (batchConf.wMode != 4
&& batchConf.wMode != 5) { // 4 and 5 treated elsewhere
cout << "unsupported weighting mode (mode/arg): " << batchConf.wMode << "/" <<
batchConf.wArgument << endl;
throw 42;
}
sum += factors[i];
}
// calc new alphass
base::DataVector* temp = new base::DataVector(alpha.getSize());
temp->setAll(0.0f);
for (size_t i = 0; i < count; i++) {
alphaStorage.at(grid)[i].resizeZero(
temp->getSize()); // should have been done already, just to be save
base::DataVector* t2 = new base::DataVector(alphaStorage.at(grid)[i]);
// if (batchConf.verbose)
// cout << "mult with " << factors[i] << "/" << sum << " = " << factors[i]*1.0f/sum << endl;
t2->mult(factors[i] * 1.0f / sum);
temp->add(*t2);
}
return *temp;
}
// predict on the data, return the vector of classes predicted
base::DataVector BatchLearner::predict(base::DataMatrix& testDataset, bool updateNorm) {
if (updateNorm) {
// update norm factors
for (auto const& p : grids) {
// for each grid
float_t evalsum = 0;
for (float x = 0; x < batchConf.samples; x++) {
// generate points per grid
base::DataVector pt(dimensions);
// only sample within [0.1,0.9]
for (size_t d = 0; d < dimensions; d++) // generate point
pt[d] = 0.1 + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX / (0.9)));
// add norm factor
base::OperationEval* opEval = op_factory::createOperationEval(*grids.at(
p.first));
float_t temp = opEval->eval(*alphaVectors.at(p.first), pt);
if (batchConf.verbose && fabs(temp) > 100)
cout << "warning abs>100: " << temp << " for " << pt.toString() << endl;
evalsum += temp;
}
evalsum = evalsum / (float_t) batchConf.samples;
// update the normFactor
normFactors.at(p.first) = evalsum;
if (batchConf.verbose)
cout << "grid " << p.first << ", norm factor: " << normFactors.at(
p.first) << endl;
}
}
// predict
base::DataVector result(testDataset.getNrows());
result.setAll(-2.0f);
for (unsigned int i = 0; i < testDataset.getNrows(); i++) {
base::DataVector pt(testDataset.getNcols());
testDataset.getRow(i, pt);
// Compute maximum of all density functions:
int max_index = -1;
float_t max = -1.0f * numeric_limits<float_t>::max();
for (auto const& g : grids) {
base::OperationEval* Eval = op_factory::createOperationEval(
*g.second);
// posterior = likelihood*prior
float_t res = Eval->eval(*alphaVectors.at(g.first), pt);
delete Eval;
if (batchConf.samples != 0)
res /= normFactors.at(g.first);
// this->prior[class_index]
if (res > max) {
max = res;
max_index = g.first;
}
}
result[i] = static_cast<float_t>(max_index);
}
return result;
}
void BatchLearner::processBatch(string workData) {
base::DataMatrix temp(0, 0);
base::DataVector temp2(0);
stringToDataMatrix(workData, temp, temp2, true);
// data is now mapped to dataInBatch
// iterate over the found classes
for (auto const& p : dataInBatch) {
if (grids.find(p.first) == grids.end()) {
// this class has never been seen before
// init new grid etc
grids.insert(std::pair<int, base::LinearGrid*>(p.first, new base::LinearGrid(dimensions)));
occurences.insert(std::pair<int, int>(p.first, 0));
// Generate regular Grid with LEVELS Levels
base::GridGenerator* myGenerator = grids.at(
p.first)->createGridGenerator();
myGenerator->regular(gridConf.level_);
if (batchConf.verbose)
cout << "found new class " << p.first << ", points in grid " << p.first << ": "
<< grids.at(p.first)->getSize() << endl;
alphaVectors.insert(std::pair<int, base::DataVector*>(p.first,
new base::DataVector(grids.at(p.first)->getSize())));
alphaVectors.at(p.first)->setAll(0.0);
normFactors.insert(std::pair<int, float_t>(p.first, 1));
}
// calculate the new surplusses for the items found of this class in this batch
// Solve the system for every class and store coefficients in newAlpha
// set up everything to be able to solve
base::DataVector newAlpha(grids.at(p.first)->getSize());
newAlpha.setAll(0.0);
base::OperationMatrix* id = op_factory::createOperationIdentity(*grids.at(
p.first));
datadriven::DensitySystemMatrix DMatrix(*grids.at(p.first),
*dataInBatch.at(p.first), *id, batchConf.lambda);
base::DataVector rhs(grids.at(p.first)->getStorage()->size());
DMatrix.generateb(rhs);
myCG->setMaxIterations(solverConf.maxIterations_);
myCG->setEpsilon(solverConf.eps_);
// solve euqation to get new alpha
myCG->solve(DMatrix, newAlpha, rhs, false, false, -1.0);
free(id);
// apply weighting
alphaVectors.at(p.first)->copyFrom(applyWeight(newAlpha, p.first));
// refine the grids
if (batchConf.refineEvery != 0 && batchnum != 0
&& batchnum % batchConf.refineEvery == 0) {
if (batchConf.verbose)
cout << "refining ..." << endl;
base::SurplusRefinementFunctor* myRefineFunc = new base::SurplusRefinementFunctor(
alphaVectors.at(p.first), adaptConf.noPoints_, adaptConf.threshold_);
grids.at(p.first)->createGridGenerator()->refine(myRefineFunc);
// change alpha, zeroes to new entries until they will be filled
alphaVectors.at(p.first)->resizeZero(grids.at(p.first)->getSize());
delete myRefineFunc;
}
occurences.at(p.first) += p.second->getSize();
}
}
void BatchLearner::trainBatch() {
int startLine = dataLine;
string line = "";
string test = "";
unsigned int ts = 0;
// collect data from arff to process
while (bs + ts != batchConf.batchsize + batchConf.testsize) {
isFinished = reader.eof();
if (isFinished) {
reader.close();
return;
}
// read another line from arff
getline(reader, line);
if (!reachedData && line.find("@DATA") != string::npos) {
reachedData = true;
continue;
}
if (!reachedData)
continue;
// only count lines after @DATA
dataLine++;
if (bs < batchConf.batchsize) {
batch += line + "\n";
bs++;
} else if (ts < batchConf.testsize) {
test += line + "\n";
ts++;
}
}
// process the batch
if (batchConf.verbose)
cout << "Processing Data " << batchnum << " @" << startLine << "-" << dataLine
<< " ..." << endl;
processBatch(batch);
// automatic testing if wanted by user
if (batchConf.testsize > 0 && test.size() > 0) {
base::DataMatrix testData(0, 0);
base::DataVector testClasses(0);
stringToDataMatrix(test, testData, testClasses, false);
// predict
base::DataVector result = predict(testData, batchConf.samples != 0);
if (batchConf.verbose)
cout << "Testing Data (" << result.getSize() << " items)..." << endl;
// caluclate accuracy
if (result.getSize() > 0) {
if (batchConf.verbose) {
cout << "result: " << result.toString() << endl;
cout << "should: " << testClasses.toString() << endl;
}
// count correct entries
int correct = 0;
for (size_t i = 0; i < result.getSize(); i++) {
if (result.get(i) == testClasses.get(i))
correct++;
}
// calc accuracy for this batch and all tests
t_total += static_cast<int>(result.getSize());
t_correct += correct;
acc_current = (float_t)(100.0 * correct / (float_t)result.getSize());
acc_global = (float_t)(100.0 * t_correct / (float_t)t_total);
// output accuracy
cout << "batch:\t" << acc_current << "% (" << correct << "/" << result.getSize()
<< ")" << endl;
cout << "total:\t" << acc_global << "% (" << t_correct << "/" << t_total << ")"
<< endl;
}
}
batch = "";
batch += test;
bs = ts;
batchnum++;
}
} // namespace datadriven
} // namespace SGPP
| [
"[email protected]"
]
| |
d72df3619b6a618dddcfb407beb9b9bbcc920229 | 5456502f97627278cbd6e16d002d50f1de3da7bb | /chrome/browser/ui/autofill/save_card_bubble_controller_impl.h | 081784f31a24afb55eb1b30263b68bc7723c1ca4 | [
"BSD-3-Clause"
]
| permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,254 | h | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_AUTOFILL_SAVE_CARD_BUBBLE_CONTROLLER_IMPL_H_
#define CHROME_BROWSER_UI_AUTOFILL_SAVE_CARD_BUBBLE_CONTROLLER_IMPL_H_
#include <memory>
#include "base/macros.h"
#include "base/timer/elapsed_timer.h"
#include "chrome/browser/ui/autofill/save_card_bubble_controller.h"
#include "components/autofill/core/browser/credit_card.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
namespace autofill {
// Implementation of per-tab class to control the save credit card bubble and
// Omnibox icon.
class SaveCardBubbleControllerImpl
: public SaveCardBubbleController,
public content::WebContentsObserver,
public content::WebContentsUserData<SaveCardBubbleControllerImpl> {
public:
// Sets up the controller for local save and shows the bubble.
// |save_card_callback| will be invoked if and when the Save button is
// pressed.
void ShowBubbleForLocalSave(const CreditCard& card,
const base::Closure& save_card_callback);
// Sets up the controller for upload and shows the bubble.
// |save_card_callback| will be invoked if and when the Save button is
// pressed. The contents of |legal_message| will be displayed in the bubble.
void ShowBubbleForUpload(const CreditCard& card,
std::unique_ptr<base::DictionaryValue> legal_message,
const base::Closure& save_card_callback);
void HideBubble();
void ReshowBubble();
// Returns true if Omnibox save credit card icon should be visible.
bool IsIconVisible() const;
// Returns nullptr if no bubble is currently shown.
SaveCardBubbleView* save_card_bubble_view() const;
// SaveCardBubbleController:
base::string16 GetWindowTitle() const override;
base::string16 GetExplanatoryMessage() const override;
const CreditCard GetCard() const override;
void OnSaveButton() override;
void OnCancelButton() override;
void OnLearnMoreClicked() override;
void OnLegalMessageLinkClicked(const GURL& url) override;
void OnBubbleClosed() override;
const LegalMessageLines& GetLegalMessageLines() const override;
protected:
explicit SaveCardBubbleControllerImpl(content::WebContents* web_contents);
~SaveCardBubbleControllerImpl() override;
// Returns the time elapsed since |timer_| was initialized.
// Exists for testing.
virtual base::TimeDelta Elapsed() const;
// content::WebContentsObserver:
void DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) override;
private:
friend class content::WebContentsUserData<SaveCardBubbleControllerImpl>;
void ShowBubble();
// Update the visibility and toggled state of the Omnibox save card icon.
void UpdateIcon();
void OpenUrl(const GURL& url);
// Weak reference. Will be nullptr if no bubble is currently shown.
SaveCardBubbleView* save_card_bubble_view_;
// Callback to run if user presses Save button in the bubble.
// If save_card_callback_.is_null() is true then no bubble is available to
// show and the icon is not visible.
base::Closure save_card_callback_;
// Governs whether the upload or local save version of the UI should be shown.
bool is_uploading_;
// Whether ReshowBubble() has been called since ShowBubbleFor*() was called.
bool is_reshow_;
// Contains the details of the card that will be saved if the user accepts.
CreditCard card_;
// If no legal message should be shown then this variable is an empty vector.
LegalMessageLines legal_message_lines_;
// Used to measure the amount of time on a page; if it's less than some
// reasonable limit, then don't close the bubble upon navigation.
std::unique_ptr<base::ElapsedTimer> timer_;
DISALLOW_COPY_AND_ASSIGN(SaveCardBubbleControllerImpl);
};
} // namespace autofill
#endif // CHROME_BROWSER_UI_AUTOFILL_SAVE_CARD_BUBBLE_CONTROLLER_IMPL_H_
| [
"[email protected]"
]
| |
24843b3b73c235b9d29296569354dfda7accbd11 | bba4b68dff933011d25f0fb68dfad0ea20f13d46 | /token.h | 11e2f0b4811640fb21d89dbc2891b5e8316f40c3 | []
| no_license | KobeHV/compiler_grammer | 7af23b67793bef50f214e7857d7d03f64d34a734 | 36a71a60d54e763eb6f988daa177c676ff22f9b6 | refs/heads/master | 2020-05-16T18:49:37.267002 | 2019-05-12T14:11:51 | 2019-05-12T14:11:51 | 183,241,468 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 299 | h | //
// Created by kobe on 2019/5/12.
//
#ifndef LR1_TOKEN_H
#define LR1_TOKEN_H
#include <fstream>
#include <iostream>
#include <string>
#include <fstream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
void ScanAnalyse(fstream&);
void print();
#endif //LR1_TOKEN_H
| [
"[email protected]"
]
| |
18cf3045f2b4c0958a03e70422171da2a0d98e8a | f2248cf4b3323a316ba08933cfe231ae608f7f82 | /Overloading/operatorOverloading.cpp | 7dfcc8c587b2b25942ec30f1d6517d4012f33566 | []
| no_license | Roy19/Cplusplus_tutorials | df9fdd70e4d9235ad48059b37744f65281051bf0 | ec30bb74e00284b8ec0ad55d622ed77838cb5f4b | refs/heads/master | 2021-01-25T11:48:37.019585 | 2018-06-15T20:36:57 | 2018-06-15T20:36:57 | 123,430,541 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 750 | cpp | #include <iostream>
using namespace std;
class Shape
{
private:
int length; // Length of a box
int width;
public:
// Constructor definition
Shape(int l = 2, int w = 2)
{
length = l;
width = w;
}
double Area()
{
return length * width;
}
int operator + (Shape shapeIn)
{
cout << this->Area() << endl;
return Area() + shapeIn.Area();
}
};
int main(void)
{
Shape sh1(4, 4); // Declare shape1
Shape sh2(2, 6); // Declare shape2
int total = sh1 + sh2;
cout << "\nsh1.Area() = " << sh1.Area();
cout << "\nsh2.Area() = " << sh2.Area();
cout << "\nTotal = "<<total;
return 0;
}
| [
"[email protected]"
]
| |
788e072a3c2f37e476fc56d5094a0461a5c63ce1 | e767f4b848a7c329df24d2efe471f3a762825356 | /APTDLLPack/APTDLLClient/APTDLLClient.h | 64e501ac396147debec297c2382ba3c9f5a1e79d | [
"MIT"
]
| permissive | draustin/PyAPT | 3bdb2fb1c37245767624745e1486c9d87f77dd74 | bd377b412e408be58f56b4d1542ef95f0ab31558 | refs/heads/master | 2022-11-18T03:21:02.081716 | 2020-07-01T15:31:57 | 2020-07-01T15:31:57 | 274,436,910 | 0 | 0 | MIT | 2020-06-23T15:07:32 | 2020-06-23T15:07:31 | null | UTF-8 | C++ | false | false | 540 | h | // APTDLLClient.h : main header file for the PROJECT_NAME application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CAPTDLLClientApp:
// See APTDLLClient.cpp for the implementation of this class
//
class CAPTDLLClientApp : public CWinApp
{
public:
CAPTDLLClientApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
};
extern CAPTDLLClientApp theApp; | [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.