hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3bb1f1a5b5b56545f05e7831643f4b80548cc8f5
| 841
|
cpp
|
C++
|
Source/Runtime/Engine/Private/GameFramework/PlayerController.cpp
|
Othereum/NoEngineGame
|
e3c9c9a330ba8e724cd96f98355b556d24e73d9d
|
[
"MIT"
] | 23
|
2020-05-21T06:25:29.000Z
|
2021-04-06T03:37:28.000Z
|
Source/Runtime/Engine/Private/GameFramework/PlayerController.cpp
|
Othereum/NoEngineGame
|
e3c9c9a330ba8e724cd96f98355b556d24e73d9d
|
[
"MIT"
] | 72
|
2020-06-09T04:46:27.000Z
|
2020-12-07T03:20:51.000Z
|
Source/Runtime/Engine/Private/GameFramework/PlayerController.cpp
|
Othereum/NoEngineGame
|
e3c9c9a330ba8e724cd96f98355b556d24e73d9d
|
[
"MIT"
] | 4
|
2020-06-10T02:23:54.000Z
|
2022-03-28T07:22:08.000Z
|
#include "GameFramework/PlayerController.hpp"
#include "Camera/PlayerCameraManager.hpp"
#include "Engine/World.hpp"
#include "GameFramework/Pawn.hpp"
namespace oeng
{
inline namespace engine
{
ViewInfo APlayerController::CalcCamera() const
{
if (const auto pcm = pcm_.lock())
return pcm->CalcCamera();
return AController::CalcCamera();
}
void APlayerController::SetCameraManagerClass(Name pcm_class)
{
if (ENSURE(!HasBegunPlay()))
{
pcm_class_ = pcm_class;
}
}
void APlayerController::OnBeginPlay()
{
auto& pcm = GetWorld().SpawnActor<APlayerCameraManager>(pcm_class_);
pcm_ = pcm.weak_from_this();
pcm.view_target = GetPawn();
}
void APlayerController::OnSetPawn()
{
if (const auto pcm = pcm_.lock())
pcm->view_target = GetPawn();
}
} // namespace engine
} // namespace oeng
| 21.025
| 72
| 0.699168
|
Othereum
|
3bb784e659ab32f3983174859ac21fc5e6474b88
| 2,529
|
cpp
|
C++
|
Kernel/Bus/USB/USBManagement.cpp
|
clarking/serenity
|
5b86698bb85dda4021b7fb9ecae081b8a656ce02
|
[
"BSD-2-Clause"
] | null | null | null |
Kernel/Bus/USB/USBManagement.cpp
|
clarking/serenity
|
5b86698bb85dda4021b7fb9ecae081b8a656ce02
|
[
"BSD-2-Clause"
] | null | null | null |
Kernel/Bus/USB/USBManagement.cpp
|
clarking/serenity
|
5b86698bb85dda4021b7fb9ecae081b8a656ce02
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Singleton.h>
#include <Kernel/Bus/PCI/API.h>
#include <Kernel/Bus/USB/UHCI/UHCIController.h>
#include <Kernel/Bus/USB/USBManagement.h>
#include <Kernel/CommandLine.h>
#include <Kernel/FileSystem/SysFS/Subsystems/Bus/USB/BusDirectory.h>
#include <Kernel/Sections.h>
namespace Kernel::USB {
static Singleton<USBManagement> s_the;
READONLY_AFTER_INIT bool s_initialized_sys_fs_directory = false;
UNMAP_AFTER_INIT USBManagement::USBManagement()
{
enumerate_controllers();
}
UNMAP_AFTER_INIT void USBManagement::enumerate_controllers()
{
if (kernel_command_line().disable_usb())
return;
MUST(PCI::enumerate([this](PCI::DeviceIdentifier const& device_identifier) {
if (!(device_identifier.class_code().value() == 0xc && device_identifier.subclass_code().value() == 0x3))
return;
if (device_identifier.prog_if().value() == 0x0) {
if (kernel_command_line().disable_uhci_controller())
return;
if (auto uhci_controller_or_error = UHCIController::try_to_initialize(device_identifier); !uhci_controller_or_error.is_error())
m_controllers.append(uhci_controller_or_error.release_value());
return;
}
if (device_identifier.prog_if().value() == 0x10) {
dmesgln("USBManagement: OHCI controller found at {} is not currently supported.", device_identifier.address());
return;
}
if (device_identifier.prog_if().value() == 0x20) {
dmesgln("USBManagement: EHCI controller found at {} is not currently supported.", device_identifier.address());
return;
}
if (device_identifier.prog_if().value() == 0x30) {
dmesgln("USBManagement: xHCI controller found at {} is not currently supported.", device_identifier.address());
return;
}
dmesgln("USBManagement: Unknown/unsupported controller at {} with programming interface 0x{:02x}", device_identifier.address(), device_identifier.prog_if().value());
}));
}
bool USBManagement::initialized()
{
return s_the.is_initialized();
}
UNMAP_AFTER_INIT void USBManagement::initialize()
{
if (!s_initialized_sys_fs_directory) {
SysFSUSBBusDirectory::initialize();
s_initialized_sys_fs_directory = true;
}
s_the.ensure_instance();
}
USBManagement& USBManagement::the()
{
return *s_the;
}
}
| 30.46988
| 173
| 0.680902
|
clarking
|
3bbd74203c29a15a3efe8bb551498b1c43cef2fa
| 3,338
|
cpp
|
C++
|
tests/TestIo/TestSerialPort.cpp
|
cvilas/grape-old
|
d8e9b184fff396982be8d230214a1f66a7a8fcc9
|
[
"BSD-3-Clause"
] | null | null | null |
tests/TestIo/TestSerialPort.cpp
|
cvilas/grape-old
|
d8e9b184fff396982be8d230214a1f66a7a8fcc9
|
[
"BSD-3-Clause"
] | 4
|
2018-06-04T08:18:21.000Z
|
2018-07-13T14:36:03.000Z
|
tests/TestIo/TestSerialPort.cpp
|
cvilas/grape-old
|
d8e9b184fff396982be8d230214a1f66a7a8fcc9
|
[
"BSD-3-Clause"
] | null | null | null |
#include "TestSerialPort.h"
//=============================================================================
TestSerialPort::TestSerialPort()
//=============================================================================
{
}
//-----------------------------------------------------------------------------
void TestSerialPort::initTestCase()
//-----------------------------------------------------------------------------
{
#ifdef WIN32
_portName = "COM6";
#else
_portName = "/dev/ttyUSB0";
#endif
}
//-----------------------------------------------------------------------------
void TestSerialPort::cleanupTestCase()
//-----------------------------------------------------------------------------
{
}
//-----------------------------------------------------------------------------
void TestSerialPort::portName()
//-----------------------------------------------------------------------------
{
// verify set/get portname
grape::SerialPort sp;
try
{
sp.setPortName(_portName);
}
catch( grape::Exception &ex )
{
QFAIL(ex.what());
}
QVERIFY2(_portName == sp.getPortName(), "get not same as set");
}
//-----------------------------------------------------------------------------
void TestSerialPort::openClose()
//-----------------------------------------------------------------------------
{
grape::SerialPort sp;
sp.setPortName(_portName);
try
{
sp.open();
}
catch(grape::Exception &ex)
{
QFAIL(ex.what());
}
QVERIFY2(sp.isOpen(), "isOpen after open");
sp.close();
QVERIFY2(!sp.isOpen(), "isOpen after close");
}
//-----------------------------------------------------------------------------
void TestSerialPort::baudRate()
//-----------------------------------------------------------------------------
{
grape::SerialPort sp;
sp.setPortName(_portName);
sp.open();
for(int i = 0; i < grape::SerialPort::BAUD_MAX; ++i)
{
try
{
sp.setBaudRate((grape::SerialPort::BaudRate)i);
}
catch(grape::Exception &ex)
{
QFAIL(ex.what());
}
}
}
//-----------------------------------------------------------------------------
void TestSerialPort::dataFormat()
//-----------------------------------------------------------------------------
{
grape::SerialPort sp;
sp.setPortName(_portName);
sp.open();
for(int i = 0; i < grape::SerialPort::DATA_FORMAT_MAX; ++i)
{
try
{
sp.setDataFormat((grape::SerialPort::DataFormat)i);
}
catch(grape::Exception &ex)
{
QFAIL(ex.what());
}
}
}
/*
//-----------------------------------------------------------------------------
void TestSerialPort::readWrite()
//-----------------------------------------------------------------------------
{
// ** This test requires hardware to be hooked up ***
Grape::SerialPort sp;
sp.setPortName(_portName);
sp.open();
if( !sp.isOpen() )
{
QFAIL(sp.lastError.getMessage().c_str());
}
if( !sp.setBaudRate(Grape::SerialPort::B115200) )
{
QFAIL(sp.lastError.getMessage().c_str());
}
if( !sp.setDataFormat(Grape::SerialPort::D8N1) )
{
QFAIL(sp.lastError.getMessage().c_str());
}
}
*/
| 26.078125
| 79
| 0.346016
|
cvilas
|
3bbea0e6239fc07e184f93e97f59ef930d701016
| 12,594
|
cpp
|
C++
|
schunk_modular_robotics/schunk_libm5api/src/Util/Message.cpp
|
briefgw/brief_schunklwa4p_simulation
|
7b148225bfca2f2d3289a9b924d6afde7507b9e8
|
[
"BSD-3-Clause"
] | 1
|
2020-11-25T13:02:50.000Z
|
2020-11-25T13:02:50.000Z
|
schunk_modular_robotics/schunk_libm5api/src/Util/Message.cpp
|
briefgw/brief_schunklwa4p_simulation
|
7b148225bfca2f2d3289a9b924d6afde7507b9e8
|
[
"BSD-3-Clause"
] | null | null | null |
schunk_modular_robotics/schunk_libm5api/src/Util/Message.cpp
|
briefgw/brief_schunklwa4p_simulation
|
7b148225bfca2f2d3289a9b924d6afde7507b9e8
|
[
"BSD-3-Clause"
] | null | null | null |
/******************************************************************************
*
* Copyright (c) 2012
*
* SCHUNK GmbH & Co. KG
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Project name: Drivers for "Amtec M5 Protocol" Electronics V4
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Email:robotics@schunk.com
*
* ToDo:
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* 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 SCHUNK GmbH & Co. KG nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License LGPL as
* published by the Free Software Foundation, either version 3 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 Lesser General Public License LGPL for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License LGPL along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
******************************************************************************/
#include "Message.h"
int g_iDebugLevel = 3;
bool g_bDebugFile = false;
bool g_bDebug = true;
const char* g_pcDebugFileName = "debug.txt";
double CMessage::m_fInitTime;
CRITICAL_SECTION* CMessage::m_csMessage = NULL;
#define ENTERCS if(m_csMessage!=NULL) EnterCriticalSection(m_csMessage);
#define LEAVECS if(m_csMessage!=NULL) LeaveCriticalSection(m_csMessage);
// ========================================================================== ;
// ;
// ---- constructors / destructor ------------------------------------------- ;
// ;
// ========================================================================== ;
CMessage::CMessage() : m_bDebug(g_bDebug), m_bDebugFile(g_bDebugFile), m_iDebugLevel(g_iDebugLevel)
{
m_acClassName[0] = 0;
}
CMessage::CMessage(const char* pcClassName, int iDebuglevel, bool bDebug, bool bDebugFile) : m_bDebug(bDebug), m_bDebugFile(bDebugFile), m_iDebugLevel(iDebuglevel)
{
strncpy(m_acClassName ,pcClassName, 50);
}
CMessage::CMessage(const CMessage& clMessage) : m_bDebug(clMessage.m_bDebug), m_bDebugFile(clMessage.m_bDebugFile), m_iDebugLevel(clMessage.m_iDebugLevel)
{
strncpy(m_acClassName ,clMessage.m_acClassName, 50);
}
CMessage::~CMessage(void)
{
}
// ========================================================================== ;
// ;
// ---- operators ----------------------------------------------------------- ;
// ;
// ========================================================================== ;
CMessage& CMessage::operator=(const CMessage& clMessage)
{
strncpy(m_acClassName ,clMessage.m_acClassName, 50);
m_bDebug = clMessage.m_bDebug;
m_bDebugFile = clMessage.m_bDebugFile;
m_iDebugLevel = clMessage.m_iDebugLevel;
return *this;
}
// ========================================================================== ;
// ;
// ---- query functions ----------------------------------------------------- ;
// ;
// ========================================================================== ;
int CMessage::getDebugLevel() const
{
return m_iDebugLevel;
}
// ========================================================================== ;
// ;
// ---- modify functions ---------------------------------------------------- ;
// ;
// ========================================================================== ;
int CMessage::initMessage(const char* pcClassName, int iDebuglevel, bool bDebug, bool bDebugFile)
{
strncpy(m_acClassName, pcClassName, 50);
m_bDebug = bDebug;
m_bDebugFile = bDebugFile;
m_iDebugLevel = iDebuglevel;
return 0;
}
void CMessage::setInitTime()
{
#if defined(__QNX__)
timespec nowTimeVal;
clock_gettime(CLOCK_REALTIME,&nowTimeVal);
m_fInitTime = (nowTimeVal.tv_sec
+(double(nowTimeVal.tv_nsec)/1e+9));
#elif defined(_WIN32)
_timeb nowTimeVal;
_ftime(&nowTimeVal);
m_fInitTime = (nowTimeVal.time
+(double(nowTimeVal.millitm)/1e+3));
#else
timeval nowTimeVal;
gettimeofday(&nowTimeVal,0);
m_fInitTime = (nowTimeVal.tv_sec
+(double(nowTimeVal.tv_usec)/1e+6));
#endif
}
void CMessage::setDebugLevel(int iLevel)
{
m_iDebugLevel = iLevel;
}
void CMessage::setDebug(bool bFlag)
{
m_bDebug = bFlag;
}
void CMessage::setDebugFile(bool bFlag)
{
m_bDebugFile = bFlag;
}
void CMessage::setCriticalSection(CRITICAL_SECTION *csMessage)
{
m_csMessage = csMessage;
}
// ========================================================================== ;
// ;
// ---- I/O functions ------------------------------------------------------- ;
// ;
// ========================================================================== ;
// ========================================================================== ;
// ;
// ---- exec functions ------------------------------------------------------ ;
// ;
// ========================================================================== ;
void CMessage::error(const char *pcErrorMessage,...) const
{
ENTERCS;
va_list args;
va_start(args, pcErrorMessage);
#if defined(__QNX__)
timespec nowTimeVal;
clock_gettime(CLOCK_REALTIME,&nowTimeVal);
double fSeconds = (nowTimeVal.tv_sec
+(double(nowTimeVal.tv_nsec)/1e+9)) - m_fInitTime;
#elif defined(_WIN32)
_timeb nowTimeVal;
_ftime(&nowTimeVal);
double fSeconds = (nowTimeVal.time
+(double(nowTimeVal.millitm)/1e+3)) - m_fInitTime;
#else
timeval nowTimeVal;
gettimeofday(&nowTimeVal,0);
double fSeconds = (nowTimeVal.tv_sec
+(double(nowTimeVal.tv_usec)/1e+6)) - m_fInitTime;
#endif
static char acBuffer[255];
static char acOutBuffer[300];
vsprintf(acBuffer, pcErrorMessage, args);
sprintf(acOutBuffer, "\nERROR: %5.3f %s::%s", fSeconds, m_acClassName, acBuffer);
if (m_bDebugFile==true)
{
FILE* hFile;
hFile=fopen(g_pcDebugFileName,"a+");
if(hFile != NULL)
{
fprintf(hFile, "%s", acOutBuffer);
fclose(hFile);
}
}
#ifdef WIN32
OutputDebugString(acOutBuffer);
#else
fprintf(stderr, "%s",acOutBuffer);
#endif
va_end(args);
LEAVECS;
exit(-1);
};
void CMessage::error(const int iErrorCode,
const char *pcErrorMessage,...)const
{
ENTERCS;
va_list args;
va_start(args, pcErrorMessage);
#if defined(__QNX__)
timespec nowTimeVal;
clock_gettime(CLOCK_REALTIME,&nowTimeVal);
double fSeconds = (nowTimeVal.tv_sec
+(double(nowTimeVal.tv_nsec)/1e+9)) - m_fInitTime;
#elif defined(_WIN32)
_timeb nowTimeVal;
_ftime(&nowTimeVal);
double fSeconds = (nowTimeVal.time
+(double(nowTimeVal.millitm)/1e+3)) - m_fInitTime;
#else
timeval nowTimeVal;
gettimeofday(&nowTimeVal,0);
double fSeconds = (nowTimeVal.tv_sec
+(double(nowTimeVal.tv_usec)/1e+6)) - m_fInitTime;
#endif
static char acBuffer[255];
static char acOutBuffer[300];
vsprintf(acBuffer, pcErrorMessage, args);
sprintf(acOutBuffer, "\nERROR: #%i %5.3f %s::%s", iErrorCode, fSeconds, m_acClassName, acBuffer);
if (m_bDebugFile==true)
{
FILE* hFile;
hFile=fopen(g_pcDebugFileName,"a+");
if(hFile != NULL)
{
fprintf(hFile, "%s", acOutBuffer);
fclose(hFile);
}
}
#ifdef WIN32
OutputDebugString(acOutBuffer);
#else
fprintf(stderr, "%s", acOutBuffer);
#endif
LEAVECS;
exit(-1);
};
void CMessage::warning(const char *pcWarningMessage,...) const
{
//UHR:use m_Debug as flag for screen output
//if(!m_bDebug)
// return;
ENTERCS;
va_list args;
va_start(args, pcWarningMessage);
#if defined(__QNX__)
timespec nowTimeVal;
clock_gettime(CLOCK_REALTIME,&nowTimeVal);
double fSeconds = (nowTimeVal.tv_sec
+(double(nowTimeVal.tv_nsec)/1e+9)) - m_fInitTime;
#elif defined(_WIN32)
_timeb nowTimeVal;
_ftime(&nowTimeVal);
double fSeconds = (nowTimeVal.time
+(double(nowTimeVal.millitm)/1e+3)) - m_fInitTime;
#else
timeval nowTimeVal;
gettimeofday(&nowTimeVal,0);
double fSeconds = (nowTimeVal.tv_sec
+(double(nowTimeVal.tv_usec)/1e+6)) - m_fInitTime;
#endif
static char acBuffer[255];
static char acOutBuffer[300];
vsprintf(acBuffer, pcWarningMessage, args);
sprintf(acOutBuffer, "\nWARNING: %5.3f %s::%s", fSeconds, m_acClassName, acBuffer);
sprintf(acOutBuffer, "\nWARNING: %s::%s", m_acClassName, acBuffer);
if (m_bDebugFile==true)
{
FILE* hFile;
hFile=fopen(g_pcDebugFileName,"a+");
if(hFile != NULL)
{
fprintf(hFile, "%s", acOutBuffer);
fclose(hFile);
}
}
#ifdef WIN32
OutputDebugString(acOutBuffer);
#else
if (m_bDebug)
fprintf(stderr, "%s", acOutBuffer);
#endif
va_end(args);
LEAVECS;
};
void CMessage::logging(const char *pcLoggingMessage,...)
{
ENTERCS;
static char acBuffer[255];
va_list args;
va_start(args, pcLoggingMessage);
vsprintf(acBuffer, pcLoggingMessage, args);
va_end(args);
FILE *m_hLogFile=fopen("log.txt","a+");
if(m_hLogFile != NULL)
{
fprintf(m_hLogFile,"%s",acBuffer);
fclose(m_hLogFile);
}
LEAVECS;
};
void CMessage::debug(const int iDebugLevel,
const char *pcDebugMessage,...) const
{
//UHR:use m_Debug as flag for screen output
//orig: if(iDebugLevel > m_iDebugLevel || !m_bDebug)
if(iDebugLevel > m_iDebugLevel )
return;
ENTERCS;
va_list args;
va_start(args, pcDebugMessage);
#if defined(__QNX__)
timespec nowTimeVal;
clock_gettime(CLOCK_REALTIME,&nowTimeVal);
double fSeconds = (nowTimeVal.tv_sec
+(double(nowTimeVal.tv_nsec)/1e+9)) - m_fInitTime;
#elif defined(_WIN32)
_timeb nowTimeVal;
_ftime(&nowTimeVal);
double fSeconds = (nowTimeVal.time
+(double(nowTimeVal.millitm)/1e+3)) - m_fInitTime;
#else
timeval nowTimeVal;
gettimeofday(&nowTimeVal,0);
double fSeconds = (nowTimeVal.tv_sec
+(double(nowTimeVal.tv_usec)/1e+6)) - m_fInitTime;
#endif
static char acBuffer[255];
static char acOutBuffer[300];
vsprintf(acBuffer, pcDebugMessage, args);
sprintf(acOutBuffer, "\nDEBUG: %i %5.3f %s::%s", iDebugLevel, fSeconds, m_acClassName, acBuffer);
if (m_bDebugFile==true)
{
FILE* hFile;
hFile=fopen(g_pcDebugFileName,"a+");
if(hFile != NULL)
{
fprintf(hFile, "%s", acOutBuffer);
fclose(hFile);
}
}
#ifdef WIN32
OutputDebugString(acOutBuffer);
#else
if (m_bDebug)
{
fprintf(stderr, "%s", acOutBuffer);
}
#endif
va_end(args);
LEAVECS;
};
| 29.70283
| 164
| 0.529379
|
briefgw
|
3bbf38d95987b28ea4f93d45ebe6288a0372fe54
| 87,627
|
cpp
|
C++
|
opencl/test/unit_test/command_queue/enqueue_svm_tests.cpp
|
maleadt/compute-runtime
|
5d90e2ab1defd413dc9633fe237a44c2a1298185
|
[
"Intel",
"MIT"
] | null | null | null |
opencl/test/unit_test/command_queue/enqueue_svm_tests.cpp
|
maleadt/compute-runtime
|
5d90e2ab1defd413dc9633fe237a44c2a1298185
|
[
"Intel",
"MIT"
] | null | null | null |
opencl/test/unit_test/command_queue/enqueue_svm_tests.cpp
|
maleadt/compute-runtime
|
5d90e2ab1defd413dc9633fe237a44c2a1298185
|
[
"Intel",
"MIT"
] | null | null | null |
/*
* Copyright (C) 2018-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/command_stream/command_stream_receiver.h"
#include "shared/source/debug_settings/debug_settings_manager.h"
#include "shared/source/helpers/aligned_memory.h"
#include "shared/source/memory_manager/allocations_list.h"
#include "shared/source/memory_manager/surface.h"
#include "shared/source/memory_manager/unified_memory_manager.h"
#include "shared/source/os_interface/device_factory.h"
#include "shared/test/common/cmd_parse/hw_parse.h"
#include "shared/test/common/helpers/debug_manager_state_restore.h"
#include "shared/test/common/libult/ult_command_stream_receiver.h"
#include "shared/test/common/mocks/mock_graphics_allocation.h"
#include "shared/test/common/mocks/mock_svm_manager.h"
#include "shared/test/common/test_macros/test.h"
#include "shared/test/unit_test/page_fault_manager/mock_cpu_page_fault_manager.h"
#include "shared/test/unit_test/utilities/base_object_utils.h"
#include "opencl/source/event/user_event.h"
#include "opencl/test/unit_test/command_queue/command_queue_fixture.h"
#include "opencl/test/unit_test/command_queue/enqueue_map_buffer_fixture.h"
#include "opencl/test/unit_test/fixtures/buffer_fixture.h"
#include "opencl/test/unit_test/fixtures/cl_device_fixture.h"
#include "opencl/test/unit_test/mocks/mock_command_queue.h"
#include "opencl/test/unit_test/mocks/mock_context.h"
#include "opencl/test/unit_test/mocks/mock_kernel.h"
#include "opencl/test/unit_test/test_macros/test_checks_ocl.h"
using namespace NEO;
struct EnqueueSvmTest : public ClDeviceFixture,
public CommandQueueHwFixture,
public ::testing::Test {
typedef CommandQueueHwFixture CommandQueueFixture;
EnqueueSvmTest() {
}
void SetUp() override {
REQUIRE_SVM_OR_SKIP(defaultHwInfo);
ClDeviceFixture::SetUp();
CommandQueueFixture::SetUp(pClDevice, 0);
ptrSVM = context->getSVMAllocsManager()->createSVMAlloc(256, {}, context->getRootDeviceIndices(), context->getDeviceBitfields());
}
void TearDown() override {
if (defaultHwInfo->capabilityTable.ftrSvm == false) {
return;
}
context->getSVMAllocsManager()->freeSVMAlloc(ptrSVM);
CommandQueueFixture::TearDown();
ClDeviceFixture::TearDown();
}
std::pair<ReleaseableObjectPtr<Buffer>, void *> createBufferAndMapItOnGpu() {
DebugManagerStateRestore restore{};
DebugManager.flags.DisableZeroCopyForBuffers.set(1);
BufferDefaults::context = this->context;
ReleaseableObjectPtr<Buffer> buffer = clUniquePtr(BufferHelper<>::create());
void *mappedPtr = pCmdQ->enqueueMapBuffer(buffer.get(), CL_TRUE, CL_MAP_READ, 0, buffer->getSize(), 0, nullptr, nullptr, retVal);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_NE(nullptr, mappedPtr);
return {std::move(buffer), mappedPtr};
}
cl_int retVal = CL_SUCCESS;
void *ptrSVM = nullptr;
};
TEST_F(EnqueueSvmTest, GivenInvalidSvmPtrWhenMappingSvmThenInvalidValueErrorIsReturned) {
void *svmPtr = nullptr;
retVal = this->pCmdQ->enqueueSVMMap(
CL_FALSE, // cl_bool blocking_map
CL_MAP_READ, // cl_map_flags map_flags
svmPtr, // void *svm_ptr
0, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // const cL_event *event_wait_list
nullptr, // cl_event *event
false);
EXPECT_EQ(CL_INVALID_VALUE, retVal);
}
TEST_F(EnqueueSvmTest, GivenValidParamsWhenMappingSvmThenSuccessIsReturned) {
retVal = this->pCmdQ->enqueueSVMMap(
CL_FALSE, // cl_bool blocking_map
CL_MAP_READ, // cl_map_flags map_flags
ptrSVM, // void *svm_ptr
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // const cL_event *event_wait_list
nullptr, // cl_event *event
false);
EXPECT_EQ(CL_SUCCESS, retVal);
}
TEST_F(EnqueueSvmTest, GivenValidParamsWhenMappingSvmWithBlockingThenSuccessIsReturned) {
retVal = this->pCmdQ->enqueueSVMMap(
CL_TRUE, // cl_bool blocking_map
CL_MAP_READ, // cl_map_flags map_flags
ptrSVM, // void *svm_ptr
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // const cL_event *event_wait_list
nullptr, // cl_event *event
false);
EXPECT_EQ(CL_SUCCESS, retVal);
}
TEST_F(EnqueueSvmTest, GivenValidParamsWhenMappingSvmWithEventsThenSuccessIsReturned) {
UserEvent uEvent;
cl_event eventWaitList[] = {&uEvent};
retVal = this->pCmdQ->enqueueSVMMap(
CL_FALSE, // cl_bool blocking_map
CL_MAP_READ, // cl_map_flags map_flags
ptrSVM, // void *svm_ptr
256, // size_t size
1, // cl_uint num_events_in_wait_list
eventWaitList, // const cL_event *event_wait_list
nullptr, // cl_event *event
false);
EXPECT_EQ(CL_SUCCESS, retVal);
}
TEST_F(EnqueueSvmTest, GivenInvalidSvmPtrWhenUnmappingSvmThenInvalidValueErrorIsReturned) {
void *svmPtr = nullptr;
retVal = this->pCmdQ->enqueueSVMUnmap(
svmPtr, // void *svm_ptr
0, // cl_uint num_events_in_wait_list
nullptr, // const cL_event *event_wait_list
nullptr, // cl_event *event
false);
EXPECT_EQ(CL_INVALID_VALUE, retVal);
}
TEST_F(EnqueueSvmTest, GivenValidParamsWhenUnmappingSvmThenSuccessIsReturned) {
retVal = this->pCmdQ->enqueueSVMUnmap(
ptrSVM, // void *svm_ptr
0, // cl_uint num_events_in_wait_list
nullptr, // const cL_event *event_wait_list
nullptr, // cl_event *event
false);
EXPECT_EQ(CL_SUCCESS, retVal);
}
TEST_F(EnqueueSvmTest, GivenValidParamsWhenUnmappingSvmWithEventsThenSuccessIsReturned) {
UserEvent uEvent;
cl_event eventWaitList[] = {&uEvent};
retVal = this->pCmdQ->enqueueSVMUnmap(
ptrSVM, // void *svm_ptr
1, // cl_uint num_events_in_wait_list
eventWaitList, // const cL_event *event_wait_list
nullptr, // cl_event *event
false);
EXPECT_EQ(CL_SUCCESS, retVal);
}
TEST_F(EnqueueSvmTest, GivenValidParamsWhenFreeingSvmThenSuccessIsReturned) {
DebugManagerStateRestore dbgRestore;
DebugManager.flags.EnableAsyncEventsHandler.set(false);
ASSERT_EQ(1U, this->context->getSVMAllocsManager()->getNumAllocs());
void *svmPtrs[] = {ptrSVM};
retVal = this->pCmdQ->enqueueSVMFree(
1, // cl_uint num_svm_pointers
svmPtrs, // void *svm_pointers[]
nullptr, // (CL_CALLBACK *pfn_free_func) (cl_command_queue queue, cl_uint num_svm_pointers, void *svm_pointers[])
nullptr, // void *user_data
0, // cl_uint num_events_in_wait_list
nullptr, // const cl_event *event_wait_list
nullptr // cl_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
ASSERT_EQ(0U, this->context->getSVMAllocsManager()->getNumAllocs());
}
TEST_F(EnqueueSvmTest, GivenValidParamsWhenFreeingSvmWithCallbackThenSuccessIsReturned) {
DebugManagerStateRestore dbgRestore;
DebugManager.flags.EnableAsyncEventsHandler.set(false);
void *svmPtrs[] = {ptrSVM};
bool callbackWasCalled = false;
struct ClbHelper {
ClbHelper(bool &callbackWasCalled)
: callbackWasCalled(callbackWasCalled) {}
static void CL_CALLBACK Clb(cl_command_queue queue, cl_uint numSvmPointers, void *svmPointers[], void *usrData) {
ClbHelper *data = (ClbHelper *)usrData;
data->callbackWasCalled = true;
}
bool &callbackWasCalled;
} userData(callbackWasCalled);
retVal = this->pCmdQ->enqueueSVMFree(
1, // cl_uint num_svm_pointers
svmPtrs, // void *svm_pointers[]
ClbHelper::Clb, // (CL_CALLBACK *pfn_free_func) (cl_command_queue queue, cl_uint num_svm_pointers, void *svm_pointers[])
&userData, // void *user_data
0, // cl_uint num_events_in_wait_list
nullptr, // const cl_event *event_wait_list
nullptr // cl_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_TRUE(callbackWasCalled);
}
TEST_F(EnqueueSvmTest, GivenValidParamsWhenFreeingSvmWithCallbackAndEventThenSuccessIsReturned) {
DebugManagerStateRestore dbgRestore;
DebugManager.flags.EnableAsyncEventsHandler.set(false);
void *svmPtrs[] = {ptrSVM};
bool callbackWasCalled = false;
struct ClbHelper {
ClbHelper(bool &callbackWasCalled)
: callbackWasCalled(callbackWasCalled) {}
static void CL_CALLBACK Clb(cl_command_queue queue, cl_uint numSvmPointers, void *svmPointers[], void *usrData) {
ClbHelper *data = (ClbHelper *)usrData;
data->callbackWasCalled = true;
}
bool &callbackWasCalled;
} userData(callbackWasCalled);
cl_event event = nullptr;
retVal = this->pCmdQ->enqueueSVMFree(
1, // cl_uint num_svm_pointers
svmPtrs, // void *svm_pointers[]
ClbHelper::Clb, // (CL_CALLBACK *pfn_free_func) (cl_command_queue queue, cl_uint num_svm_pointers, void *svm_pointers[])
&userData, // void *user_data
0, // cl_uint num_events_in_wait_list
nullptr, // const cl_event *event_wait_list
&event // cl_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_TRUE(callbackWasCalled);
auto pEvent = (Event *)event;
delete pEvent;
}
TEST_F(EnqueueSvmTest, GivenValidParamsWhenFreeingSvmWithBlockingThenSuccessIsReturned) {
DebugManagerStateRestore dbgRestore;
DebugManager.flags.EnableAsyncEventsHandler.set(false);
void *svmPtrs[] = {ptrSVM};
UserEvent uEvent;
cl_event eventWaitList[] = {&uEvent};
retVal = this->pCmdQ->enqueueSVMFree(
1, // cl_uint num_svm_pointers
svmPtrs, // void *svm_pointers[]
nullptr, // (CL_CALLBACK *pfn_free_func) (cl_command_queue queue, cl_uint num_svm_pointers, void *svm_pointers[])
nullptr, // void *user_data
1, // cl_uint num_events_in_wait_list
eventWaitList, // const cl_event *event_wait_list
nullptr // cl_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
}
TEST_F(EnqueueSvmTest, GivenNullDstPtrWhenCopyingMemoryThenInvalidVaueErrorIsReturned) {
DebugManagerStateRestore dbgRestore;
DebugManager.flags.EnableAsyncEventsHandler.set(false);
void *pDstSVM = nullptr;
void *pSrcSVM = context->getSVMAllocsManager()->createSVMAlloc(256, {}, context->getRootDeviceIndices(), context->getDeviceBitfields());
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_INVALID_VALUE, retVal);
context->getSVMAllocsManager()->freeSVMAlloc(pSrcSVM);
}
TEST_F(EnqueueSvmTest, GivenNullSrcPtrWhenCopyingMemoryThenInvalidVaueErrorIsReturned) {
void *pDstSVM = ptrSVM;
void *pSrcSVM = nullptr;
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_INVALID_VALUE, retVal);
}
TEST_F(EnqueueSvmTest, givenSrcHostPtrAndEventWhenEnqueueSVMMemcpyThenEventCommandTypeIsCorrectlySet) {
char srcHostPtr[260] = {};
void *pDstSVM = ptrSVM;
void *pSrcSVM = srcHostPtr;
cl_event event = nullptr;
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
&event // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
constexpr cl_command_type expectedCmd = CL_COMMAND_SVM_MEMCPY;
cl_command_type actualCmd = castToObjectOrAbort<Event>(event)->getCommandType();
EXPECT_EQ(expectedCmd, actualCmd);
clReleaseEvent(event);
}
TEST_F(EnqueueSvmTest, givenSrcHostPtrAndSizeZeroWhenEnqueueSVMMemcpyThenReturnSuccess) {
char srcHostPtr[260] = {};
void *pDstSVM = ptrSVM;
void *pSrcSVM = srcHostPtr;
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
0, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
}
HWTEST_F(EnqueueSvmTest, givenSrcHostPtrWhenEnqueueSVMMemcpyThenEnqueuWriteBufferIsCalled) {
char srcHostPtr[260];
void *pSrcSVM = srcHostPtr;
void *pDstSVM = ptrSVM;
MockCommandQueueHw<FamilyType> myCmdQ(context, pClDevice, 0);
retVal = myCmdQ.enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(myCmdQ.lastCommandType, static_cast<cl_command_type>(CL_COMMAND_WRITE_BUFFER));
auto tempAlloc = myCmdQ.getGpgpuCommandStreamReceiver().getTemporaryAllocations().peekHead();
EXPECT_EQ(0u, tempAlloc->countSuccessors());
EXPECT_EQ(pSrcSVM, reinterpret_cast<void *>(tempAlloc->getGpuAddress()));
auto srcAddress = myCmdQ.kernelParams.srcPtr;
auto srcOffset = myCmdQ.kernelParams.srcOffset.x;
auto dstAddress = myCmdQ.kernelParams.dstPtr;
auto dstOffset = myCmdQ.kernelParams.dstOffset.x;
EXPECT_EQ(alignDown(pSrcSVM, 4), srcAddress);
EXPECT_EQ(ptrDiff(pSrcSVM, alignDown(pSrcSVM, 4)), srcOffset);
EXPECT_EQ(alignDown(pDstSVM, 4), dstAddress);
EXPECT_EQ(ptrDiff(pDstSVM, alignDown(pDstSVM, 4)), dstOffset);
}
HWTEST_F(EnqueueSvmTest, givenDstHostPtrWhenEnqueueSVMMemcpyThenEnqueuReadBufferIsCalled) {
char dstHostPtr[260];
void *pDstSVM = dstHostPtr;
void *pSrcSVM = ptrSVM;
MockCommandQueueHw<FamilyType> myCmdQ(context, pClDevice, 0);
retVal = myCmdQ.enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(myCmdQ.lastCommandType, static_cast<cl_command_type>(CL_COMMAND_READ_BUFFER));
auto tempAlloc = myCmdQ.getGpgpuCommandStreamReceiver().getTemporaryAllocations().peekHead();
EXPECT_EQ(0u, tempAlloc->countSuccessors());
EXPECT_EQ(pDstSVM, reinterpret_cast<void *>(tempAlloc->getGpuAddress()));
auto srcAddress = myCmdQ.kernelParams.srcPtr;
auto srcOffset = myCmdQ.kernelParams.srcOffset.x;
auto dstAddress = myCmdQ.kernelParams.dstPtr;
auto dstOffset = myCmdQ.kernelParams.dstOffset.x;
EXPECT_EQ(alignDown(pSrcSVM, 4), srcAddress);
EXPECT_EQ(ptrDiff(pSrcSVM, alignDown(pSrcSVM, 4)), srcOffset);
EXPECT_EQ(alignDown(pDstSVM, 4), dstAddress);
EXPECT_EQ(ptrDiff(pDstSVM, alignDown(pDstSVM, 4)), dstOffset);
}
TEST_F(EnqueueSvmTest, givenDstHostPtrAndEventWhenEnqueueSVMMemcpyThenEventCommandTypeIsCorrectlySet) {
char dstHostPtr[260];
void *pDstSVM = dstHostPtr;
void *pSrcSVM = ptrSVM;
cl_event event = nullptr;
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
&event // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
constexpr cl_command_type expectedCmd = CL_COMMAND_SVM_MEMCPY;
cl_command_type actualCmd = castToObjectOrAbort<Event>(event)->getCommandType();
EXPECT_EQ(expectedCmd, actualCmd);
clReleaseEvent(event);
}
TEST_F(EnqueueSvmTest, givenDstHostPtrAndSizeZeroWhenEnqueueSVMMemcpyThenReturnSuccess) {
char dstHostPtr[260];
void *pDstSVM = dstHostPtr;
void *pSrcSVM = ptrSVM;
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
0, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
}
HWTEST_F(EnqueueSvmTest, givenDstHostPtrAndSrcHostPtrWhenEnqueueNonBlockingSVMMemcpyThenEnqueuWriteBufferIsCalled) {
char dstHostPtr[] = {0, 0, 0};
char srcHostPtr[] = {1, 2, 3};
void *pDstSVM = dstHostPtr;
void *pSrcSVM = srcHostPtr;
MockCommandQueueHw<FamilyType> myCmdQ(context, pClDevice, 0);
retVal = myCmdQ.enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
3, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(myCmdQ.lastCommandType, static_cast<cl_command_type>(CL_COMMAND_WRITE_BUFFER));
auto tempAlloc = myCmdQ.getGpgpuCommandStreamReceiver().getTemporaryAllocations().peekHead();
EXPECT_EQ(1u, tempAlloc->countSuccessors());
EXPECT_EQ(pSrcSVM, reinterpret_cast<void *>(tempAlloc->getGpuAddress()));
EXPECT_EQ(pDstSVM, reinterpret_cast<void *>(tempAlloc->next->getGpuAddress()));
auto srcAddress = myCmdQ.kernelParams.srcPtr;
auto srcOffset = myCmdQ.kernelParams.srcOffset.x;
auto dstAddress = myCmdQ.kernelParams.dstPtr;
auto dstOffset = myCmdQ.kernelParams.dstOffset.x;
EXPECT_EQ(alignDown(pSrcSVM, 4), srcAddress);
EXPECT_EQ(ptrDiff(pSrcSVM, alignDown(pSrcSVM, 4)), srcOffset);
EXPECT_EQ(alignDown(pDstSVM, 4), dstAddress);
EXPECT_EQ(ptrDiff(pDstSVM, alignDown(pDstSVM, 4)), dstOffset);
}
HWTEST_F(EnqueueSvmTest, givenDstHostPtrAndSrcHostPtrWhenEnqueueBlockingSVMMemcpyThenEnqueuWriteBufferIsCalled) {
char dstHostPtr[] = {0, 0, 0};
char srcHostPtr[] = {1, 2, 3};
void *pDstSVM = dstHostPtr;
void *pSrcSVM = srcHostPtr;
MockCommandQueueHw<FamilyType> myCmdQ(context, pClDevice, 0);
retVal = myCmdQ.enqueueSVMMemcpy(
true, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
3, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(myCmdQ.lastCommandType, static_cast<cl_command_type>(CL_COMMAND_WRITE_BUFFER));
auto srcAddress = myCmdQ.kernelParams.srcPtr;
auto srcOffset = myCmdQ.kernelParams.srcOffset.x;
auto dstAddress = myCmdQ.kernelParams.dstPtr;
auto dstOffset = myCmdQ.kernelParams.dstOffset.x;
EXPECT_EQ(alignDown(pSrcSVM, 4), srcAddress);
EXPECT_EQ(ptrDiff(pSrcSVM, alignDown(pSrcSVM, 4)), srcOffset);
EXPECT_EQ(alignDown(pDstSVM, 4), dstAddress);
EXPECT_EQ(ptrDiff(pDstSVM, alignDown(pDstSVM, 4)), dstOffset);
}
TEST_F(EnqueueSvmTest, givenDstHostPtrAndSrcHostPtrAndSizeZeroWhenEnqueueSVMMemcpyThenReturnSuccess) {
char dstHostPtr[260] = {};
char srcHostPtr[260] = {};
void *pDstSVM = dstHostPtr;
void *pSrcSVM = srcHostPtr;
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
0, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
}
HWTEST_F(EnqueueSvmTest, givenSvmToSvmCopyTypeWhenEnqueueNonBlockingSVMMemcpyThenSvmMemcpyCommandIsEnqueued) {
void *pDstSVM = ptrSVM;
void *pSrcSVM = context->getSVMAllocsManager()->createSVMAlloc(256, {}, context->getRootDeviceIndices(), context->getDeviceBitfields());
MockCommandQueueHw<FamilyType> myCmdQ(context, pClDevice, 0);
retVal = myCmdQ.enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(myCmdQ.lastCommandType, static_cast<cl_command_type>(CL_COMMAND_SVM_MEMCPY));
auto tempAlloc = myCmdQ.getGpgpuCommandStreamReceiver().getTemporaryAllocations().peekHead();
EXPECT_EQ(nullptr, tempAlloc);
auto srcAddress = myCmdQ.kernelParams.srcPtr;
auto srcOffset = myCmdQ.kernelParams.srcOffset.x;
auto dstAddress = myCmdQ.kernelParams.dstPtr;
auto dstOffset = myCmdQ.kernelParams.dstOffset.x;
EXPECT_EQ(alignDown(pSrcSVM, 4), srcAddress);
EXPECT_EQ(ptrDiff(pSrcSVM, alignDown(pSrcSVM, 4)), srcOffset);
EXPECT_EQ(alignDown(pDstSVM, 4), dstAddress);
EXPECT_EQ(ptrDiff(pDstSVM, alignDown(pDstSVM, 4)), dstOffset);
context->getSVMAllocsManager()->freeSVMAlloc(pSrcSVM);
}
TEST_F(EnqueueSvmTest, givenSvmToSvmCopyTypeWhenEnqueueBlockingSVMMemcpyThenSuccessIsReturned) {
void *pDstSVM = ptrSVM;
void *pSrcSVM = context->getSVMAllocsManager()->createSVMAlloc(256, {}, context->getRootDeviceIndices(), context->getDeviceBitfields());
retVal = this->pCmdQ->enqueueSVMMemcpy(
true, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
context->getSVMAllocsManager()->freeSVMAlloc(pSrcSVM);
}
TEST_F(EnqueueSvmTest, GivenValidParamsWhenCopyingMemoryWithBlockingThenSuccessisReturned) {
void *pDstSVM = ptrSVM;
void *pSrcSVM = context->getSVMAllocsManager()->createSVMAlloc(256, {}, context->getRootDeviceIndices(), context->getDeviceBitfields());
auto uEvent = make_releaseable<UserEvent>();
cl_event eventWaitList[] = {uEvent.get()};
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
256, // size_t size
1, // cl_uint num_events_in_wait_list
eventWaitList, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
context->getSVMAllocsManager()->freeSVMAlloc(pSrcSVM);
uEvent->setStatus(-1);
}
TEST_F(EnqueueSvmTest, GivenCoherencyWhenCopyingMemoryThenSuccessIsReturned) {
void *pDstSVM = ptrSVM;
SVMAllocsManager::SvmAllocationProperties svmProperties;
svmProperties.coherent = true;
void *pSrcSVM = context->getSVMAllocsManager()->createSVMAlloc(256, svmProperties, context->getRootDeviceIndices(), context->getDeviceBitfields());
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
context->getSVMAllocsManager()->freeSVMAlloc(pSrcSVM);
}
TEST_F(EnqueueSvmTest, GivenCoherencyWhenCopyingMemoryWithBlockingThenSuccessIsReturned) {
void *pDstSVM = ptrSVM;
SVMAllocsManager::SvmAllocationProperties svmProperties;
svmProperties.coherent = true;
void *pSrcSVM = context->getSVMAllocsManager()->createSVMAlloc(256, svmProperties, context->getRootDeviceIndices(), context->getDeviceBitfields());
auto uEvent = make_releaseable<UserEvent>();
cl_event eventWaitList[] = {uEvent.get()};
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
256, // size_t size
1, // cl_uint num_events_in_wait_list
eventWaitList, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
context->getSVMAllocsManager()->freeSVMAlloc(pSrcSVM);
uEvent->setStatus(-1);
}
HWTEST_F(EnqueueSvmTest, givenUnalignedAddressWhenEnqueueMemcpyThenDispatchInfoHasAlignedAddressAndProperOffset) {
void *pDstSVM = reinterpret_cast<void *>(0x17);
void *pSrcSVM = ptrSVM;
MockCommandQueueHw<FamilyType> myCmdQ(context, pClDevice, 0);
retVal = myCmdQ.enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
0, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
auto srcAddress = myCmdQ.kernelParams.srcPtr;
auto srcOffset = myCmdQ.kernelParams.srcOffset.x;
auto dstAddress = myCmdQ.kernelParams.dstPtr;
auto dstOffset = myCmdQ.kernelParams.dstOffset.x;
EXPECT_EQ(alignDown(pSrcSVM, 4), srcAddress);
EXPECT_EQ(ptrDiff(pSrcSVM, alignDown(pSrcSVM, 4)), srcOffset);
EXPECT_EQ(alignDown(pDstSVM, 4), dstAddress);
EXPECT_EQ(ptrDiff(pDstSVM, alignDown(pDstSVM, 4)), dstOffset);
}
TEST_F(EnqueueSvmTest, GivenNullSvmPtrWhenFillingMemoryThenInvalidValueErrorIsReturned) {
void *svmPtr = nullptr;
const float pattern[1] = {1.2345f};
const size_t patternSize = sizeof(pattern);
retVal = this->pCmdQ->enqueueSVMMemFill(
svmPtr, // void *svm_ptr
pattern, // const void *pattern
patternSize, // size_t pattern_size
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_INVALID_VALUE, retVal);
}
HWTEST_F(EnqueueSvmTest, givenSvmAllocWhenEnqueueSvmFillThenSuccesIsReturnedAndAddressIsProperlyAligned) {
const float pattern[1] = {1.2345f};
const size_t patternSize = sizeof(pattern);
MockCommandQueueHw<FamilyType> myCmdQ(context, pClDevice, 0);
retVal = myCmdQ.enqueueSVMMemFill(
ptrSVM, // void *svm_ptr
pattern, // const void *pattern
patternSize, // size_t pattern_size
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
auto dstAddress = myCmdQ.kernelParams.dstPtr;
auto dstOffset = myCmdQ.kernelParams.dstOffset.x;
EXPECT_EQ(alignDown(ptrSVM, 4), dstAddress);
EXPECT_EQ(ptrDiff(ptrSVM, alignDown(ptrSVM, 4)), dstOffset);
}
TEST_F(EnqueueSvmTest, GivenValidParamsWhenFillingMemoryWithBlockingThenSuccessIsReturned) {
const float pattern[1] = {1.2345f};
const size_t patternSize = sizeof(pattern);
auto uEvent = make_releaseable<UserEvent>();
cl_event eventWaitList[] = {uEvent.get()};
retVal = this->pCmdQ->enqueueSVMMemFill(
ptrSVM, // void *svm_ptr
pattern, // const void *pattern
patternSize, // size_t pattern_size
256, // size_t size
1, // cl_uint num_events_in_wait_list
eventWaitList, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
uEvent->setStatus(-1);
}
TEST_F(EnqueueSvmTest, GivenRepeatCallsWhenFillingMemoryThenSuccessIsReturnedForEachCall) {
const float pattern[1] = {1.2345f};
const size_t patternSize = sizeof(pattern);
retVal = this->pCmdQ->enqueueSVMMemFill(
ptrSVM, // void *svm_ptr
pattern, // const void *pattern
patternSize, // size_t pattern_size
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
retVal = this->pCmdQ->enqueueSVMMemFill(
ptrSVM, // void *svm_ptr
pattern, // const void *pattern
patternSize, // size_t pattern_size
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
}
TEST_F(EnqueueSvmTest, givenEnqueueSVMMemFillWhenPatternAllocationIsObtainedThenItsTypeShouldBeSetToFillPattern) {
auto &csr = pCmdQ->getGpgpuCommandStreamReceiver();
ASSERT_TRUE(csr.getAllocationsForReuse().peekIsEmpty());
const float pattern[1] = {1.2345f};
const size_t patternSize = sizeof(pattern);
const size_t size = patternSize;
retVal = this->pCmdQ->enqueueSVMMemFill(
ptrSVM,
pattern,
patternSize,
size,
0,
nullptr,
nullptr);
EXPECT_EQ(CL_SUCCESS, retVal);
ASSERT_FALSE(csr.getAllocationsForReuse().peekIsEmpty());
GraphicsAllocation *patternAllocation = csr.getAllocationsForReuse().peekHead();
ASSERT_NE(nullptr, patternAllocation);
EXPECT_EQ(AllocationType::FILL_PATTERN, patternAllocation->getAllocationType());
}
TEST_F(EnqueueSvmTest, GivenSvmAllocationWhenEnqueingKernelThenSuccessIsReturned) {
auto svmData = context->getSVMAllocsManager()->getSVMAlloc(ptrSVM);
ASSERT_NE(nullptr, svmData);
GraphicsAllocation *pSvmAlloc = svmData->gpuAllocations.getGraphicsAllocation(context->getDevice(0)->getRootDeviceIndex());
EXPECT_NE(nullptr, ptrSVM);
std::unique_ptr<MockProgram> program(Program::createBuiltInFromSource<MockProgram>("FillBufferBytes", context, context->getDevices(), &retVal));
program->build(program->getDevices(), nullptr, false);
std::unique_ptr<MockKernel> kernel(Kernel::create<MockKernel>(program.get(), program->getKernelInfoForKernel("FillBufferBytes"), *context->getDevice(0), &retVal));
kernel->setSvmKernelExecInfo(pSvmAlloc);
size_t offset = 0;
size_t size = 1;
retVal = this->pCmdQ->enqueueKernel(
kernel.get(),
1,
&offset,
&size,
&size,
0,
nullptr,
nullptr);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(1u, kernel->kernelSvmGfxAllocations.size());
}
TEST_F(EnqueueSvmTest, givenEnqueueTaskBlockedOnUserEventWhenItIsEnqueuedThenSurfacesAreMadeResident) {
auto svmData = context->getSVMAllocsManager()->getSVMAlloc(ptrSVM);
ASSERT_NE(nullptr, svmData);
GraphicsAllocation *pSvmAlloc = svmData->gpuAllocations.getGraphicsAllocation(context->getDevice(0)->getRootDeviceIndex());
EXPECT_NE(nullptr, ptrSVM);
auto program = clUniquePtr(Program::createBuiltInFromSource<MockProgram>("FillBufferBytes", context, context->getDevices(), &retVal));
program->build(program->getDevices(), nullptr, false);
auto pMultiDeviceKernel = clUniquePtr(MultiDeviceKernel::create<MockKernel>(program.get(), program->getKernelInfosForKernel("FillBufferBytes"), &retVal));
auto kernel = static_cast<MockKernel *>(pMultiDeviceKernel->getKernel(rootDeviceIndex));
std::vector<Surface *> allSurfaces;
kernel->getResidency(allSurfaces);
EXPECT_EQ(1u, allSurfaces.size());
kernel->setSvmKernelExecInfo(pSvmAlloc);
auto uEvent = make_releaseable<UserEvent>();
cl_event eventWaitList[] = {uEvent.get()};
size_t offset = 0;
size_t size = 1;
retVal = this->pCmdQ->enqueueKernel(
kernel,
1,
&offset,
&size,
&size,
1,
eventWaitList,
nullptr);
EXPECT_EQ(CL_SUCCESS, retVal);
kernel->getResidency(allSurfaces);
EXPECT_EQ(3u, allSurfaces.size());
for (auto &surface : allSurfaces)
delete surface;
EXPECT_EQ(1u, kernel->kernelSvmGfxAllocations.size());
uEvent->setStatus(-1);
}
TEST_F(EnqueueSvmTest, GivenMultipleThreasWhenAllocatingSvmThenOnlyOneAllocationIsCreated) {
std::atomic<int> flag(0);
std::atomic<int> ready(0);
void *svmPtrs[15] = {};
auto allocSvm = [&](uint32_t from, uint32_t to) {
for (uint32_t i = from; i <= to; i++) {
svmPtrs[i] = context->getSVMAllocsManager()->createSVMAlloc(1, {}, context->getRootDeviceIndices(), context->getDeviceBitfields());
auto svmData = context->getSVMAllocsManager()->getSVMAlloc(svmPtrs[i]);
ASSERT_NE(nullptr, svmData);
auto ga = svmData->gpuAllocations.getGraphicsAllocation(context->getDevice(0)->getRootDeviceIndex());
EXPECT_NE(nullptr, ga);
EXPECT_EQ(ga->getUnderlyingBuffer(), svmPtrs[i]);
}
};
auto freeSvm = [&](uint32_t from, uint32_t to) {
for (uint32_t i = from; i <= to; i++) {
context->getSVMAllocsManager()->freeSVMAlloc(svmPtrs[i]);
}
};
auto asyncFcn = [&](bool alloc, uint32_t from, uint32_t to) {
flag++;
while (flag < 3)
;
if (alloc) {
allocSvm(from, to);
}
freeSvm(from, to);
ready++;
};
EXPECT_EQ(1u, context->getSVMAllocsManager()->getNumAllocs());
allocSvm(10, 14);
auto t1 = std::unique_ptr<std::thread>(new std::thread(asyncFcn, true, 0, 4));
auto t2 = std::unique_ptr<std::thread>(new std::thread(asyncFcn, true, 5, 9));
auto t3 = std::unique_ptr<std::thread>(new std::thread(asyncFcn, false, 10, 14));
while (ready < 3) {
std::this_thread::yield();
}
EXPECT_EQ(1u, context->getSVMAllocsManager()->getNumAllocs());
t1->join();
t2->join();
t3->join();
}
TEST_F(EnqueueSvmTest, GivenValidParamsWhenMigratingMemoryThenSuccessIsReturned) {
const void *svmPtrs[] = {ptrSVM};
retVal = this->pCmdQ->enqueueSVMMigrateMem(
1, // cl_uint num_svm_pointers
svmPtrs, // const void **svm_pointers
nullptr, // const size_t *sizes
0, // const cl_mem_migration_flags flags
0, // cl_uint num_events_in_wait_list
nullptr, // cl_event *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
}
HWTEST_F(EnqueueSvmTest, WhenMigratingMemoryThenSvmMigrateMemCommandTypeIsUsed) {
MockCommandQueueHw<FamilyType> commandQueue{context, pClDevice, nullptr};
const void *svmPtrs[] = {ptrSVM};
retVal = commandQueue.enqueueSVMMigrateMem(
1, // cl_uint num_svm_pointers
svmPtrs, // const void **svm_pointers
nullptr, // const size_t *sizes
0, // const cl_mem_migration_flags flags
0, // cl_uint num_events_in_wait_list
nullptr, // cl_event *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
uint32_t expectedCommandType = CL_COMMAND_SVM_MIGRATE_MEM;
EXPECT_EQ(expectedCommandType, commandQueue.lastCommandType);
}
TEST(CreateSvmAllocTests, givenVariousSvmAllocationPropertiesWhenAllocatingSvmThenSvmIsCorrectlyAllocated) {
if (!defaultHwInfo->capabilityTable.ftrSvm) {
return;
}
DebugManagerStateRestore dbgRestore;
SVMAllocsManager::SvmAllocationProperties svmAllocationProperties;
for (auto isLocalMemorySupported : ::testing::Bool()) {
DebugManager.flags.EnableLocalMemory.set(isLocalMemorySupported);
auto mockDevice = std::make_unique<MockClDevice>(MockDevice::createWithNewExecutionEnvironment<MockDevice>(defaultHwInfo.get()));
auto mockContext = std::make_unique<MockContext>(mockDevice.get());
for (auto isReadOnly : ::testing::Bool()) {
for (auto isHostPtrReadOnly : ::testing::Bool()) {
svmAllocationProperties.readOnly = isReadOnly;
svmAllocationProperties.hostPtrReadOnly = isHostPtrReadOnly;
auto ptrSVM = mockContext->getSVMAllocsManager()->createSVMAlloc(256, svmAllocationProperties, mockContext->getRootDeviceIndices(), mockContext->getDeviceBitfields());
EXPECT_NE(nullptr, ptrSVM);
mockContext->getSVMAllocsManager()->freeSVMAlloc(ptrSVM);
}
}
}
}
struct EnqueueSvmTestLocalMemory : public ClDeviceFixture,
public ::testing::Test {
void SetUp() override {
REQUIRE_SVM_OR_SKIP(defaultHwInfo);
dbgRestore = std::make_unique<DebugManagerStateRestore>();
DebugManager.flags.EnableLocalMemory.set(1);
ClDeviceFixture::SetUp();
context = std::make_unique<MockContext>(pClDevice, true);
size = 256;
svmPtr = context->getSVMAllocsManager()->createSVMAlloc(size, {}, context->getRootDeviceIndices(), context->getDeviceBitfields());
ASSERT_NE(nullptr, svmPtr);
mockSvmManager = reinterpret_cast<MockSVMAllocsManager *>(context->getSVMAllocsManager());
}
void TearDown() override {
if (defaultHwInfo->capabilityTable.ftrSvm == false) {
return;
}
context->getSVMAllocsManager()->freeSVMAlloc(svmPtr);
context.reset(nullptr);
ClDeviceFixture::TearDown();
}
cl_int retVal = CL_SUCCESS;
void *svmPtr = nullptr;
size_t size;
MockSVMAllocsManager *mockSvmManager;
std::unique_ptr<DebugManagerStateRestore> dbgRestore;
std::unique_ptr<MockContext> context;
HardwareParse hwParse;
};
HWTEST_F(EnqueueSvmTestLocalMemory, givenWriteInvalidateRegionFlagWhenMappingSvmThenMapIsSuccessfulAndReadOnlyFlagIsFalse) {
MockCommandQueueHw<FamilyType> queue(context.get(), pClDevice, nullptr);
uintptr_t offset = 64;
void *regionSvmPtr = ptrOffset(svmPtr, offset);
size_t regionSize = 64;
retVal = queue.enqueueSVMMap(
CL_TRUE,
CL_MAP_WRITE_INVALIDATE_REGION,
regionSvmPtr,
regionSize,
0,
nullptr,
nullptr,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
auto svmMap = mockSvmManager->svmMapOperations.get(regionSvmPtr);
EXPECT_FALSE(svmMap->readOnlyMap);
}
HWTEST_F(EnqueueSvmTestLocalMemory, givenMapWriteFlagWhenMappingSvmThenMapIsSuccessfulAndReadOnlyFlagIsFalse) {
MockCommandQueueHw<FamilyType> queue(context.get(), pClDevice, nullptr);
uintptr_t offset = 64;
void *regionSvmPtr = ptrOffset(svmPtr, offset);
size_t regionSize = 64;
retVal = queue.enqueueSVMMap(
CL_TRUE,
CL_MAP_WRITE,
regionSvmPtr,
regionSize,
0,
nullptr,
nullptr,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
auto svmMap = mockSvmManager->svmMapOperations.get(regionSvmPtr);
EXPECT_FALSE(svmMap->readOnlyMap);
}
HWTEST_F(EnqueueSvmTestLocalMemory, givenMapReadFlagWhenMappingSvmThenMapIsSuccessfulAndReadOnlyFlagIsTrue) {
MockCommandQueueHw<FamilyType> queue(context.get(), pClDevice, nullptr);
uintptr_t offset = 64;
void *regionSvmPtr = ptrOffset(svmPtr, offset);
size_t regionSize = 64;
retVal = queue.enqueueSVMMap(
CL_TRUE,
CL_MAP_READ,
regionSvmPtr,
regionSize,
0,
nullptr,
nullptr,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
auto svmMap = mockSvmManager->svmMapOperations.get(regionSvmPtr);
EXPECT_TRUE(svmMap->readOnlyMap);
}
HWTEST_F(EnqueueSvmTestLocalMemory, givenMapReadAndWriteFlagWhenMappingSvmThenDontSetReadOnlyProperty) {
MockCommandQueueHw<FamilyType> queue(context.get(), pClDevice, nullptr);
uintptr_t offset = 64;
void *regionSvmPtr = ptrOffset(svmPtr, offset);
size_t regionSize = 64;
retVal = queue.enqueueSVMMap(
CL_TRUE,
CL_MAP_READ | CL_MAP_WRITE,
regionSvmPtr,
regionSize,
0,
nullptr,
nullptr,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
auto svmMap = mockSvmManager->svmMapOperations.get(regionSvmPtr);
EXPECT_FALSE(svmMap->readOnlyMap);
}
HWTEST_F(EnqueueSvmTestLocalMemory, givenSvmAllocWithoutFlagsWhenMappingSvmThenMapIsSuccessfulAndReadOnlyFlagIsTrue) {
MockCommandQueueHw<FamilyType> queue(context.get(), pClDevice, nullptr);
uintptr_t offset = 64;
void *regionSvmPtr = ptrOffset(svmPtr, offset);
size_t regionSize = 64;
retVal = queue.enqueueSVMMap(
CL_TRUE,
0,
regionSvmPtr,
regionSize,
0,
nullptr,
nullptr,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
auto svmMap = mockSvmManager->svmMapOperations.get(regionSvmPtr);
EXPECT_FALSE(svmMap->readOnlyMap);
}
HWTEST_F(EnqueueSvmTestLocalMemory, givenEnabledLocalMemoryWhenEnqueueMapValidSvmPtrThenExpectSingleWalker) {
using WALKER_TYPE = typename FamilyType::WALKER_TYPE;
MockCommandQueueHw<FamilyType> queue(context.get(), pClDevice, nullptr);
LinearStream &stream = queue.getCS(0x1000);
cl_event event = nullptr;
uintptr_t offset = 64;
void *regionSvmPtr = ptrOffset(svmPtr, offset);
size_t regionSize = 64;
retVal = queue.enqueueSVMMap(
CL_FALSE,
CL_MAP_READ,
regionSvmPtr,
regionSize,
0,
nullptr,
&event,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
auto svmMap = mockSvmManager->svmMapOperations.get(regionSvmPtr);
ASSERT_NE(nullptr, svmMap);
EXPECT_EQ(regionSvmPtr, svmMap->regionSvmPtr);
EXPECT_EQ(svmPtr, svmMap->baseSvmPtr);
EXPECT_EQ(regionSize, svmMap->regionSize);
EXPECT_EQ(offset, svmMap->offset);
EXPECT_TRUE(svmMap->readOnlyMap);
queue.flush();
hwParse.parseCommands<FamilyType>(stream);
auto walkerCount = hwParse.getCommandCount<WALKER_TYPE>();
EXPECT_EQ(1u, walkerCount);
constexpr cl_command_type expectedCmd = CL_COMMAND_SVM_MAP;
cl_command_type actualCmd = castToObjectOrAbort<Event>(event)->getCommandType();
EXPECT_EQ(expectedCmd, actualCmd);
clReleaseEvent(event);
}
HWTEST_F(EnqueueSvmTestLocalMemory, givenEnabledLocalMemoryWhenEnqueueMapSvmPtrTwiceThenExpectSingleWalker) {
using WALKER_TYPE = typename FamilyType::WALKER_TYPE;
MockCommandQueueHw<FamilyType> queue(context.get(), pClDevice, nullptr);
LinearStream &stream = queue.getCS(0x1000);
uintptr_t offset = 64;
void *regionSvmPtr = ptrOffset(svmPtr, offset);
size_t regionSize = 64;
retVal = queue.enqueueSVMMap(
CL_FALSE,
CL_MAP_WRITE,
regionSvmPtr,
regionSize,
0,
nullptr,
nullptr,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
auto svmMap = mockSvmManager->svmMapOperations.get(regionSvmPtr);
ASSERT_NE(nullptr, svmMap);
EXPECT_EQ(regionSvmPtr, svmMap->regionSvmPtr);
EXPECT_EQ(svmPtr, svmMap->baseSvmPtr);
EXPECT_EQ(regionSize, svmMap->regionSize);
EXPECT_EQ(offset, svmMap->offset);
EXPECT_FALSE(svmMap->readOnlyMap);
EXPECT_EQ(1u, mockSvmManager->svmMapOperations.getNumMapOperations());
cl_event event = nullptr;
retVal = queue.enqueueSVMMap(
CL_FALSE,
CL_MAP_WRITE,
regionSvmPtr,
regionSize,
0,
nullptr,
&event,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(1u, mockSvmManager->svmMapOperations.getNumMapOperations());
queue.flush();
hwParse.parseCommands<FamilyType>(stream);
auto walkerCount = hwParse.getCommandCount<WALKER_TYPE>();
EXPECT_EQ(1u, walkerCount);
constexpr cl_command_type expectedCmd = CL_COMMAND_SVM_MAP;
cl_command_type actualCmd = castToObjectOrAbort<Event>(event)->getCommandType();
EXPECT_EQ(expectedCmd, actualCmd);
clReleaseEvent(event);
}
HWTEST_F(EnqueueSvmTestLocalMemory, givenEnabledLocalMemoryWhenNoMappedSvmPtrThenExpectNoUnmapCopyKernel) {
using WALKER_TYPE = typename FamilyType::WALKER_TYPE;
MockCommandQueueHw<FamilyType> queue(context.get(), pClDevice, nullptr);
LinearStream &stream = queue.getCS(0x1000);
cl_event event = nullptr;
retVal = queue.enqueueSVMUnmap(
svmPtr,
0,
nullptr,
&event,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
queue.flush();
hwParse.parseCommands<FamilyType>(stream);
auto walkerCount = hwParse.getCommandCount<WALKER_TYPE>();
EXPECT_EQ(0u, walkerCount);
constexpr cl_command_type expectedCmd = CL_COMMAND_SVM_UNMAP;
cl_command_type actualCmd = castToObjectOrAbort<Event>(event)->getCommandType();
EXPECT_EQ(expectedCmd, actualCmd);
clReleaseEvent(event);
}
HWTEST_F(EnqueueSvmTestLocalMemory, givenEnabledLocalMemoryWhenMappedSvmRegionIsReadOnlyThenExpectNoUnmapCopyKernel) {
using WALKER_TYPE = typename FamilyType::WALKER_TYPE;
MockCommandQueueHw<FamilyType> queue(context.get(), pClDevice, nullptr);
LinearStream &stream = queue.getCS(0x1000);
retVal = queue.enqueueSVMMap(
CL_FALSE,
CL_MAP_READ,
svmPtr,
size,
0,
nullptr,
nullptr,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(1u, mockSvmManager->svmMapOperations.getNumMapOperations());
auto svmMap = mockSvmManager->svmMapOperations.get(svmPtr);
ASSERT_NE(nullptr, svmMap);
queue.flush();
size_t offset = stream.getUsed();
hwParse.parseCommands<FamilyType>(stream);
auto walkerCount = hwParse.getCommandCount<WALKER_TYPE>();
EXPECT_EQ(1u, walkerCount);
hwParse.TearDown();
cl_event event = nullptr;
retVal = queue.enqueueSVMUnmap(
svmPtr,
0,
nullptr,
&event,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(0u, mockSvmManager->svmMapOperations.getNumMapOperations());
queue.flush();
hwParse.parseCommands<FamilyType>(stream, offset);
walkerCount = hwParse.getCommandCount<WALKER_TYPE>();
EXPECT_EQ(0u, walkerCount);
constexpr cl_command_type expectedCmd = CL_COMMAND_SVM_UNMAP;
cl_command_type actualCmd = castToObjectOrAbort<Event>(event)->getCommandType();
EXPECT_EQ(expectedCmd, actualCmd);
clReleaseEvent(event);
}
HWTEST_F(EnqueueSvmTestLocalMemory, givenNonReadOnlyMapWhenUnmappingThenSetAubTbxWritableBeforeUnmapEnqueue) {
class MyQueue : public MockCommandQueueHw<FamilyType> {
public:
using MockCommandQueueHw<FamilyType>::MockCommandQueueHw;
void enqueueHandlerHook(const unsigned int commandType, const MultiDispatchInfo &dispatchInfo) override {
waitUntilCompleteCalled++;
if (allocationToVerify) {
EXPECT_TRUE(allocationToVerify->isAubWritable(GraphicsAllocation::defaultBank));
EXPECT_TRUE(allocationToVerify->isTbxWritable(GraphicsAllocation::defaultBank));
}
}
uint32_t waitUntilCompleteCalled = 0;
GraphicsAllocation *allocationToVerify = nullptr;
};
MyQueue myQueue(context.get(), pClDevice, nullptr);
retVal = myQueue.enqueueSVMMap(CL_TRUE, CL_MAP_WRITE, svmPtr, size, 0, nullptr, nullptr, false);
EXPECT_EQ(CL_SUCCESS, retVal);
auto gpuAllocation = mockSvmManager->getSVMAlloc(svmPtr)->gpuAllocations.getGraphicsAllocation(context->getDevice(0)->getRootDeviceIndex());
myQueue.allocationToVerify = gpuAllocation;
gpuAllocation->setAubWritable(false, GraphicsAllocation::defaultBank);
gpuAllocation->setTbxWritable(false, GraphicsAllocation::defaultBank);
EXPECT_EQ(1u, myQueue.waitUntilCompleteCalled);
retVal = myQueue.enqueueSVMUnmap(svmPtr, 0, nullptr, nullptr, false);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(2u, myQueue.waitUntilCompleteCalled);
}
HWTEST_F(EnqueueSvmTestLocalMemory, givenReadOnlyMapWhenUnmappingThenDontResetAubTbxWritable) {
MockCommandQueueHw<FamilyType> queue(context.get(), pClDevice, nullptr);
retVal = queue.enqueueSVMMap(CL_TRUE, CL_MAP_READ, svmPtr, size, 0, nullptr, nullptr, false);
EXPECT_EQ(CL_SUCCESS, retVal);
auto gpuAllocation = mockSvmManager->getSVMAlloc(svmPtr)->gpuAllocations.getGraphicsAllocation(context->getDevice(0)->getRootDeviceIndex());
gpuAllocation->setAubWritable(false, GraphicsAllocation::defaultBank);
gpuAllocation->setTbxWritable(false, GraphicsAllocation::defaultBank);
retVal = queue.enqueueSVMUnmap(svmPtr, 0, nullptr, nullptr, false);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_FALSE(gpuAllocation->isAubWritable(GraphicsAllocation::defaultBank));
EXPECT_FALSE(gpuAllocation->isTbxWritable(GraphicsAllocation::defaultBank));
}
HWTEST_F(EnqueueSvmTestLocalMemory, givenEnabledLocalMemoryWhenMappedSvmRegionIsWritableThenExpectMapAndUnmapCopyKernel) {
using WALKER_TYPE = typename FamilyType::WALKER_TYPE;
MockCommandQueueHw<FamilyType> queue(context.get(), pClDevice, nullptr);
LinearStream &stream = queue.getCS(0x1000);
cl_event eventMap = nullptr;
retVal = queue.enqueueSVMMap(
CL_FALSE,
CL_MAP_WRITE,
svmPtr,
size,
0,
nullptr,
&eventMap,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(1u, mockSvmManager->svmMapOperations.getNumMapOperations());
auto svmMap = mockSvmManager->svmMapOperations.get(svmPtr);
ASSERT_NE(nullptr, svmMap);
cl_event eventUnmap = nullptr;
retVal = queue.enqueueSVMUnmap(
svmPtr,
0,
nullptr,
&eventUnmap,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(0u, mockSvmManager->svmMapOperations.getNumMapOperations());
queue.flush();
hwParse.parseCommands<FamilyType>(stream);
auto walkerCount = hwParse.getCommandCount<WALKER_TYPE>();
EXPECT_EQ(2u, walkerCount);
constexpr cl_command_type expectedMapCmd = CL_COMMAND_SVM_MAP;
cl_command_type actualMapCmd = castToObjectOrAbort<Event>(eventMap)->getCommandType();
EXPECT_EQ(expectedMapCmd, actualMapCmd);
constexpr cl_command_type expectedUnmapCmd = CL_COMMAND_SVM_UNMAP;
cl_command_type actualUnmapCmd = castToObjectOrAbort<Event>(eventUnmap)->getCommandType();
EXPECT_EQ(expectedUnmapCmd, actualUnmapCmd);
clReleaseEvent(eventMap);
clReleaseEvent(eventUnmap);
}
HWTEST_F(EnqueueSvmTestLocalMemory, givenEnabledLocalMemoryWhenMappedSvmRegionAndNoEventIsUsedIsWritableThenExpectMapAndUnmapCopyKernelAnNo) {
using WALKER_TYPE = typename FamilyType::WALKER_TYPE;
MockCommandQueueHw<FamilyType> queue(context.get(), pClDevice, nullptr);
LinearStream &stream = queue.getCS(0x1000);
retVal = queue.enqueueSVMMap(
CL_FALSE,
CL_MAP_WRITE,
svmPtr,
size,
0,
nullptr,
nullptr,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(1u, mockSvmManager->svmMapOperations.getNumMapOperations());
auto svmMap = mockSvmManager->svmMapOperations.get(svmPtr);
ASSERT_NE(nullptr, svmMap);
retVal = queue.enqueueSVMUnmap(
svmPtr,
0,
nullptr,
nullptr,
false);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(0u, mockSvmManager->svmMapOperations.getNumMapOperations());
queue.flush();
hwParse.parseCommands<FamilyType>(stream);
auto walkerCount = hwParse.getCommandCount<WALKER_TYPE>();
EXPECT_EQ(2u, walkerCount);
}
template <typename GfxFamily>
struct FailCsr : public CommandStreamReceiverHw<GfxFamily> {
using CommandStreamReceiverHw<GfxFamily>::CommandStreamReceiverHw;
bool createAllocationForHostSurface(HostPtrSurface &surface, bool requiresL3Flush) override {
return CL_FALSE;
}
};
HWTEST_F(EnqueueSvmTest, whenInternalAllocationsAreMadeResidentThenOnlyNonSvmAllocationsAreAdded) {
SVMAllocsManager::UnifiedMemoryProperties unifiedMemoryProperties(InternalMemoryType::DEVICE_UNIFIED_MEMORY, context->getRootDeviceIndices(), context->getDeviceBitfields());
unifiedMemoryProperties.device = pDevice;
auto allocationSize = 4096u;
auto svmManager = this->context->getSVMAllocsManager();
EXPECT_NE(0u, svmManager->getNumAllocs());
auto unifiedMemoryPtr = svmManager->createUnifiedMemoryAllocation(allocationSize, unifiedMemoryProperties);
EXPECT_NE(nullptr, unifiedMemoryPtr);
EXPECT_EQ(2u, svmManager->getNumAllocs());
auto &commandStreamReceiver = pDevice->getUltCommandStreamReceiver<FamilyType>();
auto &residentAllocations = commandStreamReceiver.getResidencyAllocations();
EXPECT_EQ(0u, residentAllocations.size());
svmManager->makeInternalAllocationsResident(commandStreamReceiver, InternalMemoryType::DEVICE_UNIFIED_MEMORY);
//only unified memory allocation is made resident
EXPECT_EQ(1u, residentAllocations.size());
EXPECT_EQ(residentAllocations[0]->getGpuAddress(), castToUint64(unifiedMemoryPtr));
svmManager->freeSVMAlloc(unifiedMemoryPtr);
}
HWTEST_F(EnqueueSvmTest, whenInternalAllocationsAreAddedToResidencyContainerThenOnlyExpectedAllocationsAreAdded) {
SVMAllocsManager::UnifiedMemoryProperties unifiedMemoryProperties(InternalMemoryType::DEVICE_UNIFIED_MEMORY, context->getRootDeviceIndices(), context->getDeviceBitfields());
unifiedMemoryProperties.device = pDevice;
auto allocationSize = 4096u;
auto svmManager = this->context->getSVMAllocsManager();
EXPECT_NE(0u, svmManager->getNumAllocs());
auto unifiedMemoryPtr = svmManager->createUnifiedMemoryAllocation(allocationSize, unifiedMemoryProperties);
EXPECT_NE(nullptr, unifiedMemoryPtr);
EXPECT_EQ(2u, svmManager->getNumAllocs());
ResidencyContainer residencyContainer;
EXPECT_EQ(0u, residencyContainer.size());
svmManager->addInternalAllocationsToResidencyContainer(pDevice->getRootDeviceIndex(),
residencyContainer,
InternalMemoryType::DEVICE_UNIFIED_MEMORY);
//only unified memory allocation is added to residency container
EXPECT_EQ(1u, residencyContainer.size());
EXPECT_EQ(residencyContainer[0]->getGpuAddress(), castToUint64(unifiedMemoryPtr));
svmManager->freeSVMAlloc(unifiedMemoryPtr);
}
HWTEST_F(EnqueueSvmTest, whenInternalAllocationIsTriedToBeAddedTwiceToResidencyContainerThenItIsAdded) {
SVMAllocsManager::UnifiedMemoryProperties unifiedMemoryProperties(InternalMemoryType::DEVICE_UNIFIED_MEMORY, context->getRootDeviceIndices(), context->getDeviceBitfields());
unifiedMemoryProperties.device = pDevice;
auto allocationSize = 4096u;
auto svmManager = this->context->getSVMAllocsManager();
EXPECT_NE(0u, svmManager->getNumAllocs());
auto unifiedMemoryPtr = svmManager->createUnifiedMemoryAllocation(allocationSize, unifiedMemoryProperties);
EXPECT_NE(nullptr, unifiedMemoryPtr);
EXPECT_EQ(2u, svmManager->getNumAllocs());
ResidencyContainer residencyContainer;
EXPECT_EQ(0u, residencyContainer.size());
svmManager->addInternalAllocationsToResidencyContainer(pDevice->getRootDeviceIndex(),
residencyContainer,
InternalMemoryType::DEVICE_UNIFIED_MEMORY);
//only unified memory allocation is added to residency container
EXPECT_EQ(1u, residencyContainer.size());
EXPECT_EQ(residencyContainer[0]->getGpuAddress(), castToUint64(unifiedMemoryPtr));
svmManager->addInternalAllocationsToResidencyContainer(pDevice->getRootDeviceIndex(),
residencyContainer,
InternalMemoryType::DEVICE_UNIFIED_MEMORY);
EXPECT_EQ(2u, residencyContainer.size());
svmManager->freeSVMAlloc(unifiedMemoryPtr);
}
struct createHostUnifiedMemoryAllocationTest : public ::testing::Test {
void SetUp() override {
REQUIRE_SVM_OR_SKIP(defaultHwInfo);
device0 = context.pRootDevice0;
device1 = context.pRootDevice1;
device2 = context.pRootDevice2;
svmManager = context.getSVMAllocsManager();
EXPECT_EQ(0u, svmManager->getNumAllocs());
}
const size_t allocationSize = 4096u;
const uint32_t numDevices = 3u;
MockDefaultContext context;
MockClDevice *device2;
MockClDevice *device1;
MockClDevice *device0;
SVMAllocsManager *svmManager = nullptr;
};
HWTEST_F(createHostUnifiedMemoryAllocationTest,
whenCreatingHostUnifiedMemoryAllocationThenOneAllocDataIsCreatedWithOneGraphicsAllocationPerDevice) {
NEO::SVMAllocsManager::UnifiedMemoryProperties unifiedMemoryProperties(InternalMemoryType::HOST_UNIFIED_MEMORY, context.getRootDeviceIndices(), context.getDeviceBitfields());
EXPECT_EQ(0u, svmManager->getNumAllocs());
auto unifiedMemoryPtr = svmManager->createHostUnifiedMemoryAllocation(allocationSize,
unifiedMemoryProperties);
EXPECT_NE(nullptr, unifiedMemoryPtr);
EXPECT_EQ(1u, svmManager->getNumAllocs());
auto allocData = svmManager->getSVMAlloc(unifiedMemoryPtr);
EXPECT_EQ(numDevices, allocData->gpuAllocations.getGraphicsAllocations().size());
for (uint32_t i = 0; i < allocData->gpuAllocations.getGraphicsAllocations().size(); i++) {
auto alloc = allocData->gpuAllocations.getGraphicsAllocation(i);
EXPECT_EQ(i, alloc->getRootDeviceIndex());
}
svmManager->freeSVMAlloc(unifiedMemoryPtr);
}
HWTEST_F(createHostUnifiedMemoryAllocationTest,
whenCreatingMultiGraphicsAllocationThenGraphicsAllocationPerDeviceIsCreated) {
NEO::SVMAllocsManager::UnifiedMemoryProperties unifiedMemoryProperties(InternalMemoryType::HOST_UNIFIED_MEMORY, context.getRootDeviceIndices(), context.getDeviceBitfields());
auto alignedSize = alignUp<size_t>(allocationSize, MemoryConstants::pageSize64k);
auto memoryManager = context.getMemoryManager();
auto allocationType = AllocationType::BUFFER_HOST_MEMORY;
auto maxRootDeviceIndex = numDevices - 1u;
std::vector<uint32_t> rootDeviceIndices;
rootDeviceIndices.reserve(numDevices);
rootDeviceIndices.push_back(0u);
rootDeviceIndices.push_back(1u);
rootDeviceIndices.push_back(2u);
auto rootDeviceIndex = rootDeviceIndices.at(0);
auto deviceBitfield = device0->getDeviceBitfield();
AllocationProperties allocationProperties{rootDeviceIndex,
true,
alignedSize,
allocationType,
deviceBitfield.count() > 1,
deviceBitfield.count() > 1,
deviceBitfield};
allocationProperties.flags.shareable = unifiedMemoryProperties.allocationFlags.flags.shareable;
SvmAllocationData allocData(maxRootDeviceIndex);
void *unifiedMemoryPtr = memoryManager->createMultiGraphicsAllocationInSystemMemoryPool(rootDeviceIndices, allocationProperties, allocData.gpuAllocations);
EXPECT_NE(nullptr, unifiedMemoryPtr);
EXPECT_EQ(numDevices, allocData.gpuAllocations.getGraphicsAllocations().size());
for (auto rootDeviceIndex = 0u; rootDeviceIndex <= maxRootDeviceIndex; rootDeviceIndex++) {
auto alloc = allocData.gpuAllocations.getGraphicsAllocation(rootDeviceIndex);
EXPECT_NE(nullptr, alloc);
EXPECT_EQ(rootDeviceIndex, alloc->getRootDeviceIndex());
}
for (auto gpuAllocation : allocData.gpuAllocations.getGraphicsAllocations()) {
memoryManager->freeGraphicsMemory(gpuAllocation);
}
}
HWTEST_F(createHostUnifiedMemoryAllocationTest,
whenCreatingMultiGraphicsAllocationForSpecificRootDeviceIndicesThenOnlyGraphicsAllocationPerSpecificRootDeviceIndexIsCreated) {
NEO::SVMAllocsManager::UnifiedMemoryProperties unifiedMemoryProperties(InternalMemoryType::HOST_UNIFIED_MEMORY, context.getRootDeviceIndices(), context.getDeviceBitfields());
auto alignedSize = alignUp<size_t>(allocationSize, MemoryConstants::pageSize64k);
auto memoryManager = context.getMemoryManager();
auto allocationType = AllocationType::BUFFER_HOST_MEMORY;
auto maxRootDeviceIndex = numDevices - 1u;
std::vector<uint32_t> rootDeviceIndices;
rootDeviceIndices.reserve(numDevices);
rootDeviceIndices.push_back(0u);
rootDeviceIndices.push_back(2u);
auto noProgramedRootDeviceIndex = 1u;
auto rootDeviceIndex = rootDeviceIndices.at(0);
auto deviceBitfield = device0->getDeviceBitfield();
AllocationProperties allocationProperties{rootDeviceIndex,
true,
alignedSize,
allocationType,
deviceBitfield.count() > 1,
deviceBitfield.count() > 1,
deviceBitfield};
allocationProperties.flags.shareable = unifiedMemoryProperties.allocationFlags.flags.shareable;
SvmAllocationData allocData(maxRootDeviceIndex);
void *unifiedMemoryPtr = memoryManager->createMultiGraphicsAllocationInSystemMemoryPool(rootDeviceIndices, allocationProperties, allocData.gpuAllocations);
EXPECT_NE(nullptr, unifiedMemoryPtr);
EXPECT_EQ(numDevices, allocData.gpuAllocations.getGraphicsAllocations().size());
for (auto rootDeviceIndex = 0u; rootDeviceIndex <= maxRootDeviceIndex; rootDeviceIndex++) {
auto alloc = allocData.gpuAllocations.getGraphicsAllocation(rootDeviceIndex);
if (rootDeviceIndex == noProgramedRootDeviceIndex) {
EXPECT_EQ(nullptr, alloc);
} else {
EXPECT_NE(nullptr, alloc);
EXPECT_EQ(rootDeviceIndex, alloc->getRootDeviceIndex());
}
}
for (auto gpuAllocation : allocData.gpuAllocations.getGraphicsAllocations()) {
memoryManager->freeGraphicsMemory(gpuAllocation);
}
}
struct MemoryAllocationTypeArray {
const InternalMemoryType allocationType[3] = {InternalMemoryType::HOST_UNIFIED_MEMORY,
InternalMemoryType::DEVICE_UNIFIED_MEMORY,
InternalMemoryType::SHARED_UNIFIED_MEMORY};
};
struct UpdateResidencyContainerMultipleDevicesTest : public ::testing::WithParamInterface<std::tuple<InternalMemoryType, InternalMemoryType>>,
public ::testing::Test {
void SetUp() override {
device = context.pRootDevice0;
subDevice0 = context.pSubDevice00;
subDevice1 = context.pSubDevice01;
peerDevice = context.pRootDevice1;
peerSubDevice0 = context.pSubDevice10;
peerSubDevice1 = context.pSubDevice11;
svmManager = context.getSVMAllocsManager();
EXPECT_EQ(0u, svmManager->getNumAllocs());
}
MockUnrestrictiveContextMultiGPU context;
MockClDevice *device;
ClDevice *subDevice0 = nullptr;
ClDevice *subDevice1 = nullptr;
MockClDevice *peerDevice;
ClDevice *peerSubDevice0 = nullptr;
ClDevice *peerSubDevice1 = nullptr;
SVMAllocsManager *svmManager = nullptr;
const uint32_t numRootDevices = 2;
const uint32_t maxRootDeviceIndex = numRootDevices - 1;
};
HWTEST_F(UpdateResidencyContainerMultipleDevicesTest,
givenNoAllocationsCreatedThenNoInternalAllocationsAreAddedToResidencyContainer) {
ResidencyContainer residencyContainer;
EXPECT_EQ(0u, residencyContainer.size());
svmManager->addInternalAllocationsToResidencyContainer(device->getDevice().getRootDeviceIndex(),
residencyContainer,
InternalMemoryType::DEVICE_UNIFIED_MEMORY);
EXPECT_EQ(0u, residencyContainer.size());
}
HWTEST_P(UpdateResidencyContainerMultipleDevicesTest, givenAllocationThenItIsAddedToContainerOnlyIfMaskMatches) {
uint32_t pCmdBuffer[1024];
MockGraphicsAllocation gfxAllocation(device->getDevice().getRootDeviceIndex(),
static_cast<void *>(pCmdBuffer), sizeof(pCmdBuffer));
InternalMemoryType type = std::get<0>(GetParam());
uint32_t mask = std::get<1>(GetParam());
SvmAllocationData allocData(maxRootDeviceIndex);
allocData.gpuAllocations.addAllocation(&gfxAllocation);
allocData.memoryType = type;
allocData.device = &device->getDevice();
svmManager->insertSVMAlloc(allocData);
EXPECT_EQ(1u, svmManager->getNumAllocs());
ResidencyContainer residencyContainer;
EXPECT_EQ(0u, residencyContainer.size());
svmManager->addInternalAllocationsToResidencyContainer(device->getDevice().getRootDeviceIndex(),
residencyContainer,
mask);
if (mask == static_cast<uint32_t>(type)) {
EXPECT_EQ(1u, residencyContainer.size());
EXPECT_EQ(residencyContainer[0]->getGpuAddress(), gfxAllocation.getGpuAddress());
} else {
EXPECT_EQ(0u, residencyContainer.size());
}
}
HWTEST_P(UpdateResidencyContainerMultipleDevicesTest,
whenUsingRootDeviceIndexGreaterThanMultiGraphicsAllocationSizeThenNoAllocationsAreAdded) {
uint32_t pCmdBuffer[1024];
MockGraphicsAllocation gfxAllocation(device->getDevice().getRootDeviceIndex(),
static_cast<void *>(pCmdBuffer), sizeof(pCmdBuffer));
SvmAllocationData allocData(maxRootDeviceIndex);
allocData.gpuAllocations.addAllocation(&gfxAllocation);
allocData.memoryType = InternalMemoryType::DEVICE_UNIFIED_MEMORY;
allocData.device = &device->getDevice();
uint32_t pCmdBufferPeer[1024];
MockGraphicsAllocation gfxAllocationPeer(peerDevice->getDevice().getRootDeviceIndex(),
(void *)pCmdBufferPeer, sizeof(pCmdBufferPeer));
SvmAllocationData allocDataPeer(maxRootDeviceIndex);
allocDataPeer.gpuAllocations.addAllocation(&gfxAllocationPeer);
allocDataPeer.memoryType = InternalMemoryType::DEVICE_UNIFIED_MEMORY;
allocDataPeer.device = &peerDevice->getDevice();
svmManager->insertSVMAlloc(allocData);
svmManager->insertSVMAlloc(allocDataPeer);
EXPECT_EQ(2u, svmManager->getNumAllocs());
ResidencyContainer residencyContainer;
EXPECT_EQ(0u, residencyContainer.size());
svmManager->addInternalAllocationsToResidencyContainer(numRootDevices + 1,
residencyContainer,
InternalMemoryType::DEVICE_UNIFIED_MEMORY);
EXPECT_EQ(0u, residencyContainer.size());
svmManager->addInternalAllocationsToResidencyContainer(device->getDevice().getRootDeviceIndex(),
residencyContainer,
InternalMemoryType::DEVICE_UNIFIED_MEMORY);
EXPECT_EQ(1u, residencyContainer.size());
EXPECT_EQ(residencyContainer[0]->getGpuAddress(), gfxAllocation.getGpuAddress());
}
MemoryAllocationTypeArray memoryTypeArray;
INSTANTIATE_TEST_SUITE_P(UpdateResidencyContainerMultipleDevicesTests,
UpdateResidencyContainerMultipleDevicesTest,
::testing::Combine(
::testing::ValuesIn(memoryTypeArray.allocationType),
::testing::ValuesIn(memoryTypeArray.allocationType)));
HWTEST_F(UpdateResidencyContainerMultipleDevicesTest,
whenInternalAllocationsAreAddedToResidencyContainerThenOnlyAllocationsFromSameDeviceAreAdded) {
uint32_t pCmdBuffer[1024];
MockGraphicsAllocation gfxAllocation(device->getDevice().getRootDeviceIndex(),
static_cast<void *>(pCmdBuffer), sizeof(pCmdBuffer));
SvmAllocationData allocData(maxRootDeviceIndex);
allocData.gpuAllocations.addAllocation(&gfxAllocation);
allocData.memoryType = InternalMemoryType::DEVICE_UNIFIED_MEMORY;
allocData.device = &device->getDevice();
uint32_t pCmdBufferPeer[1024];
MockGraphicsAllocation gfxAllocationPeer(peerDevice->getDevice().getRootDeviceIndex(),
(void *)pCmdBufferPeer, sizeof(pCmdBufferPeer));
SvmAllocationData allocDataPeer(maxRootDeviceIndex);
allocDataPeer.gpuAllocations.addAllocation(&gfxAllocationPeer);
allocDataPeer.memoryType = InternalMemoryType::DEVICE_UNIFIED_MEMORY;
allocDataPeer.device = &peerDevice->getDevice();
svmManager->insertSVMAlloc(allocData);
svmManager->insertSVMAlloc(allocDataPeer);
EXPECT_EQ(2u, svmManager->getNumAllocs());
ResidencyContainer residencyContainer;
EXPECT_EQ(0u, residencyContainer.size());
svmManager->addInternalAllocationsToResidencyContainer(device->getDevice().getRootDeviceIndex(),
residencyContainer,
InternalMemoryType::DEVICE_UNIFIED_MEMORY);
EXPECT_EQ(1u, residencyContainer.size());
EXPECT_EQ(residencyContainer[0]->getGpuAddress(), gfxAllocation.getGpuAddress());
}
HWTEST_F(UpdateResidencyContainerMultipleDevicesTest,
givenSharedAllocationWithNullDevicePointerThenAllocationIsAddedToResidencyContainer) {
uint32_t pCmdBuffer[1024];
MockGraphicsAllocation gfxAllocation(device->getDevice().getRootDeviceIndex(), static_cast<void *>(pCmdBuffer), sizeof(pCmdBuffer));
SvmAllocationData allocData(maxRootDeviceIndex);
allocData.gpuAllocations.addAllocation(&gfxAllocation);
allocData.memoryType = InternalMemoryType::SHARED_UNIFIED_MEMORY;
allocData.device = nullptr;
svmManager->insertSVMAlloc(allocData);
EXPECT_EQ(1u, svmManager->getNumAllocs());
ResidencyContainer residencyContainer;
EXPECT_EQ(0u, residencyContainer.size());
svmManager->addInternalAllocationsToResidencyContainer(device->getDevice().getRootDeviceIndex(),
residencyContainer,
InternalMemoryType::SHARED_UNIFIED_MEMORY);
EXPECT_EQ(1u, residencyContainer.size());
EXPECT_EQ(residencyContainer[0]->getGpuAddress(), gfxAllocation.getGpuAddress());
}
HWTEST_F(UpdateResidencyContainerMultipleDevicesTest,
givenSharedAllocationWithNonNullDevicePointerAndDifferentDeviceToOnePassedToResidencyCallThenAllocationIsNotAddedToResidencyContainer) {
uint32_t pCmdBuffer[1024];
MockGraphicsAllocation gfxAllocation(peerDevice->getDevice().getRootDeviceIndex(),
static_cast<void *>(pCmdBuffer), sizeof(pCmdBuffer));
SvmAllocationData allocData(maxRootDeviceIndex);
allocData.gpuAllocations.addAllocation(&gfxAllocation);
allocData.memoryType = InternalMemoryType::SHARED_UNIFIED_MEMORY;
allocData.device = &peerDevice->getDevice();
svmManager->insertSVMAlloc(allocData);
EXPECT_EQ(1u, svmManager->getNumAllocs());
ResidencyContainer residencyContainer;
EXPECT_EQ(0u, residencyContainer.size());
svmManager->addInternalAllocationsToResidencyContainer(device->getDevice().getRootDeviceIndex(),
residencyContainer,
InternalMemoryType::SHARED_UNIFIED_MEMORY);
EXPECT_EQ(0u, residencyContainer.size());
}
HWTEST_F(UpdateResidencyContainerMultipleDevicesTest,
givenAllocationsFromSubDevicesBelongingToTheSameTargetDeviceThenTheyAreAddedToTheResidencyContainer) {
uint32_t pCmdBuffer[1024];
MockGraphicsAllocation gfxAllocation(device->getDevice().getRootDeviceIndex(),
static_cast<void *>(pCmdBuffer), sizeof(pCmdBuffer));
SvmAllocationData allocData0(maxRootDeviceIndex);
allocData0.gpuAllocations.addAllocation(&gfxAllocation);
allocData0.memoryType = InternalMemoryType::DEVICE_UNIFIED_MEMORY;
allocData0.device = &subDevice0->getDevice();
uint32_t pCmdBufferPeer[1024];
MockGraphicsAllocation gfxAllocationPeer(device->getDevice().getRootDeviceIndex(),
(void *)pCmdBufferPeer, sizeof(pCmdBufferPeer));
SvmAllocationData allocData1(maxRootDeviceIndex);
allocData1.gpuAllocations.addAllocation(&gfxAllocationPeer);
allocData1.memoryType = InternalMemoryType::DEVICE_UNIFIED_MEMORY;
allocData1.device = &subDevice1->getDevice();
svmManager->insertSVMAlloc(allocData0);
svmManager->insertSVMAlloc(allocData1);
EXPECT_EQ(2u, svmManager->getNumAllocs());
ResidencyContainer residencyContainer;
EXPECT_EQ(0u, residencyContainer.size());
svmManager->addInternalAllocationsToResidencyContainer(device->getDevice().getRootDeviceIndex(),
residencyContainer,
InternalMemoryType::DEVICE_UNIFIED_MEMORY);
EXPECT_EQ(2u, residencyContainer.size());
}
HWTEST_F(UpdateResidencyContainerMultipleDevicesTest,
givenAllocationsFromSubDevicesNotBelongingToTheSameTargetDeviceThenTheyAreNotAddedToTheResidencyContainer) {
uint32_t pCmdBuffer[1024];
MockGraphicsAllocation gfxAllocation(device->getDevice().getRootDeviceIndex(),
static_cast<void *>(pCmdBuffer), sizeof(pCmdBuffer));
SvmAllocationData allocData0(maxRootDeviceIndex);
allocData0.gpuAllocations.addAllocation(&gfxAllocation);
allocData0.memoryType = InternalMemoryType::DEVICE_UNIFIED_MEMORY;
allocData0.device = &subDevice0->getDevice();
uint32_t pCmdBufferPeer[1024];
MockGraphicsAllocation gfxAllocationPeer(device->getDevice().getRootDeviceIndex(),
(void *)pCmdBufferPeer, sizeof(pCmdBufferPeer));
SvmAllocationData allocData1(maxRootDeviceIndex);
allocData1.gpuAllocations.addAllocation(&gfxAllocationPeer);
allocData1.memoryType = InternalMemoryType::DEVICE_UNIFIED_MEMORY;
allocData1.device = &subDevice1->getDevice();
svmManager->insertSVMAlloc(allocData0);
svmManager->insertSVMAlloc(allocData1);
EXPECT_EQ(2u, svmManager->getNumAllocs());
ResidencyContainer residencyContainer;
EXPECT_EQ(0u, residencyContainer.size());
svmManager->addInternalAllocationsToResidencyContainer(peerDevice->getDevice().getRootDeviceIndex(),
residencyContainer,
InternalMemoryType::DEVICE_UNIFIED_MEMORY);
EXPECT_EQ(0u, residencyContainer.size());
}
HWTEST_F(EnqueueSvmTest, GivenDstHostPtrWhenHostPtrAllocationCreationFailsThenReturnOutOfResource) {
char dstHostPtr[260];
void *pDstSVM = dstHostPtr;
void *pSrcSVM = ptrSVM;
MockCommandQueueHw<FamilyType> cmdQ(context, pClDevice, nullptr);
auto failCsr = std::make_unique<FailCsr<FamilyType>>(*pDevice->getExecutionEnvironment(), pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield());
CommandStreamReceiver *oldCommandStreamReceiver = cmdQ.gpgpuEngine->commandStreamReceiver;
cmdQ.gpgpuEngine->commandStreamReceiver = failCsr.get();
retVal = cmdQ.enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_OUT_OF_RESOURCES, retVal);
cmdQ.gpgpuEngine->commandStreamReceiver = oldCommandStreamReceiver;
}
HWTEST_F(EnqueueSvmTest, GivenSrcHostPtrAndSizeZeroWhenHostPtrAllocationCreationFailsThenReturnOutOfResource) {
char srcHostPtr[260];
void *pDstSVM = ptrSVM;
void *pSrcSVM = srcHostPtr;
MockCommandQueueHw<FamilyType> cmdQ(context, pClDevice, nullptr);
auto failCsr = std::make_unique<FailCsr<FamilyType>>(*pDevice->getExecutionEnvironment(), pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield());
CommandStreamReceiver *oldCommandStreamReceiver = cmdQ.gpgpuEngine->commandStreamReceiver;
cmdQ.gpgpuEngine->commandStreamReceiver = failCsr.get();
retVal = cmdQ.enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_OUT_OF_RESOURCES, retVal);
cmdQ.gpgpuEngine->commandStreamReceiver = oldCommandStreamReceiver;
}
HWTEST_F(EnqueueSvmTest, givenDstHostPtrAndSrcHostPtrWhenHostPtrAllocationCreationFailsThenReturnOutOfResource) {
char dstHostPtr[260];
char srcHostPtr[260];
void *pDstSVM = dstHostPtr;
void *pSrcSVM = srcHostPtr;
MockCommandQueueHw<FamilyType> cmdQ(context, pClDevice, nullptr);
auto failCsr = std::make_unique<FailCsr<FamilyType>>(*pDevice->getExecutionEnvironment(), pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield());
CommandStreamReceiver *oldCommandStreamReceiver = cmdQ.gpgpuEngine->commandStreamReceiver;
cmdQ.gpgpuEngine->commandStreamReceiver = failCsr.get();
retVal = cmdQ.enqueueSVMMemcpy(
false, // cl_bool blocking_copy
pDstSVM, // void *dst_ptr
pSrcSVM, // const void *src_ptr
256, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_OUT_OF_RESOURCES, retVal);
cmdQ.gpgpuEngine->commandStreamReceiver = oldCommandStreamReceiver;
}
TEST_F(EnqueueSvmTest, givenPageFaultManagerWhenEnqueueMemcpyThenAllocIsDecommitted) {
auto mockMemoryManager = std::make_unique<MockMemoryManager>();
mockMemoryManager->pageFaultManager.reset(new MockPageFaultManager());
auto memoryManager = context->getMemoryManager();
context->memoryManager = mockMemoryManager.get();
auto srcSvm = context->getSVMAllocsManager()->createSVMAlloc(256, {}, context->getRootDeviceIndices(), context->getDeviceBitfields());
mockMemoryManager->getPageFaultManager()->insertAllocation(srcSvm, 256, context->getSVMAllocsManager(), context->getSpecialQueue(pDevice->getRootDeviceIndex()), {});
mockMemoryManager->getPageFaultManager()->insertAllocation(ptrSVM, 256, context->getSVMAllocsManager(), context->getSpecialQueue(pDevice->getRootDeviceIndex()), {});
EXPECT_EQ(static_cast<MockPageFaultManager *>(mockMemoryManager->getPageFaultManager())->transferToCpuCalled, 0);
this->pCmdQ->enqueueSVMMemcpy(false, ptrSVM, srcSvm, 256, 0, nullptr, nullptr);
EXPECT_EQ(static_cast<MockPageFaultManager *>(mockMemoryManager->getPageFaultManager())->allowMemoryAccessCalled, 0);
EXPECT_EQ(static_cast<MockPageFaultManager *>(mockMemoryManager->getPageFaultManager())->protectMemoryCalled, 2);
EXPECT_EQ(static_cast<MockPageFaultManager *>(mockMemoryManager->getPageFaultManager())->transferToCpuCalled, 0);
EXPECT_EQ(static_cast<MockPageFaultManager *>(mockMemoryManager->getPageFaultManager())->transferToGpuCalled, 2);
context->getSVMAllocsManager()->freeSVMAlloc(srcSvm);
context->memoryManager = memoryManager;
}
TEST_F(EnqueueSvmTest, givenPageFaultManagerWhenEnqueueMemFillThenAllocIsDecommitted) {
char pattern[256];
auto mockMemoryManager = std::make_unique<MockMemoryManager>();
mockMemoryManager->pageFaultManager.reset(new MockPageFaultManager());
auto memoryManager = context->getMemoryManager();
context->memoryManager = mockMemoryManager.get();
mockMemoryManager->getPageFaultManager()->insertAllocation(ptrSVM, 256, context->getSVMAllocsManager(), context->getSpecialQueue(0u), {});
EXPECT_EQ(static_cast<MockPageFaultManager *>(mockMemoryManager->getPageFaultManager())->transferToCpuCalled, 0);
EXPECT_EQ(static_cast<MockPageFaultManager *>(mockMemoryManager->getPageFaultManager())->protectMemoryCalled, 0);
pCmdQ->enqueueSVMMemFill(ptrSVM, &pattern, 256, 256, 0, nullptr, nullptr);
EXPECT_EQ(static_cast<MockPageFaultManager *>(mockMemoryManager->getPageFaultManager())->allowMemoryAccessCalled, 0);
EXPECT_EQ(static_cast<MockPageFaultManager *>(mockMemoryManager->getPageFaultManager())->protectMemoryCalled, 1);
EXPECT_EQ(static_cast<MockPageFaultManager *>(mockMemoryManager->getPageFaultManager())->transferToCpuCalled, 0);
EXPECT_EQ(static_cast<MockPageFaultManager *>(mockMemoryManager->getPageFaultManager())->transferToGpuCalled, 1);
context->memoryManager = memoryManager;
}
HWTEST_F(EnqueueSvmTest, givenCopyFromMappedPtrToSvmAllocWhenCallingSvmMemcpyThenReuseMappedAllocations) {
constexpr size_t size = 1u;
auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>();
{
auto [buffer, mappedPtr] = createBufferAndMapItOnGpu();
std::ignore = buffer;
EXPECT_EQ(0u, csr.createAllocationForHostSurfaceCalled);
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
ptrSVM, // void *dst_ptr
mappedPtr, // const void *src_ptr
size, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(0u, csr.createAllocationForHostSurfaceCalled);
}
{
auto notMappedPtr = std::make_unique<char[]>(size);
EXPECT_EQ(0u, csr.createAllocationForHostSurfaceCalled);
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
ptrSVM, // void *dst_ptr
notMappedPtr.get(), // const void *src_ptr
size, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(1u, csr.createAllocationForHostSurfaceCalled);
}
}
HWTEST_F(EnqueueSvmTest, givenCopyFromSvmAllocToMappedPtrWhenCallingSvmMemcpyThenReuseMappedAllocations) {
constexpr size_t size = 1u;
auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>();
{
auto [buffer, mappedPtr] = createBufferAndMapItOnGpu();
std::ignore = buffer;
EXPECT_EQ(0u, csr.createAllocationForHostSurfaceCalled);
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
mappedPtr, // void *dst_ptr
ptrSVM, // const void *src_ptr
size, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(0u, csr.createAllocationForHostSurfaceCalled);
}
{
auto notMappedPtr = std::make_unique<char[]>(size);
EXPECT_EQ(0u, csr.createAllocationForHostSurfaceCalled);
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
notMappedPtr.get(), // void *dst_ptr
ptrSVM, // const void *src_ptr
size, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(1u, csr.createAllocationForHostSurfaceCalled);
}
}
HWTEST_F(EnqueueSvmTest, givenCopyFromMappedPtrToMappedPtrWhenCallingSvmMemcpyThenReuseMappedAllocations) {
constexpr size_t size = 1u;
auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>();
{
auto [buffer1, mappedPtr1] = createBufferAndMapItOnGpu();
auto [buffer2, mappedPtr2] = createBufferAndMapItOnGpu();
std::ignore = buffer1;
std::ignore = buffer2;
EXPECT_EQ(0u, csr.createAllocationForHostSurfaceCalled);
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
mappedPtr2, // void *dst_ptr
mappedPtr1, // const void *src_ptr
size, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(0u, csr.createAllocationForHostSurfaceCalled);
}
{
auto [buffer, mappedPtr] = createBufferAndMapItOnGpu();
std::ignore = buffer;
auto notMappedPtr = std::make_unique<char[]>(size);
EXPECT_EQ(0u, csr.createAllocationForHostSurfaceCalled);
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
mappedPtr, // void *dst_ptr
notMappedPtr.get(), // const void *src_ptr
size, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(1u, csr.createAllocationForHostSurfaceCalled);
}
{
auto notMappedPtr = std::make_unique<char[]>(size);
auto [buffer, mappedPtr] = createBufferAndMapItOnGpu();
std::ignore = buffer;
EXPECT_EQ(1u, csr.createAllocationForHostSurfaceCalled);
retVal = this->pCmdQ->enqueueSVMMemcpy(
false, // cl_bool blocking_copy
notMappedPtr.get(), // void *dst_ptr
mappedPtr, // const void *src_ptr
size, // size_t size
0, // cl_uint num_events_in_wait_list
nullptr, // cl_evebt *event_wait_list
nullptr // cL_event *event
);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(2u, csr.createAllocationForHostSurfaceCalled);
}
}
| 42.49612
| 183
| 0.689822
|
maleadt
|
3bc16a6c0b4cffec924641317bf2c3959611c851
| 30,725
|
cpp
|
C++
|
physx/source/physx/src/NpShapeManager.cpp
|
yangfengzzz/PhysX
|
aed9c3035955d4ad90e5741f7d1dcfb5c178d44f
|
[
"BSD-3-Clause"
] | null | null | null |
physx/source/physx/src/NpShapeManager.cpp
|
yangfengzzz/PhysX
|
aed9c3035955d4ad90e5741f7d1dcfb5c178d44f
|
[
"BSD-3-Clause"
] | null | null | null |
physx/source/physx/src/NpShapeManager.cpp
|
yangfengzzz/PhysX
|
aed9c3035955d4ad90e5741f7d1dcfb5c178d44f
|
[
"BSD-3-Clause"
] | null | null | null |
//
// 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 NVIDIA CORPORATION 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 ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "CmUtils.h"
#include "GuBounds.h"
#include "NpActor.h"
#include "NpArticulationLink.h"
#include "NpFactory.h"
#include "NpPtrTableStorageManager.h"
#include "NpRigidDynamic.h"
#include "NpScene.h"
#include "NpShapeManager.h"
#include "PsAlloca.h"
#include "ScBodySim.h"
#include "ScbRigidObject.h"
#include "SqPruningStructure.h"
using namespace physx;
using namespace Sq;
using namespace Gu;
using namespace Cm;
static PX_FORCE_INLINE bool isSceneQuery(const NpShape &shape) {
return shape.getFlagsFast() & PxShapeFlag::eSCENE_QUERY_SHAPE;
}
NpShapeManager::NpShapeManager() : mSqCompoundId(INVALID_PRUNERHANDLE), mPruningStructure(NULL) {}
// PX_SERIALIZATION
NpShapeManager::NpShapeManager(const PxEMPTY) : mShapes(PxEmpty), mSceneQueryData(PxEmpty) {}
NpShapeManager::~NpShapeManager() {
PX_ASSERT(!mPruningStructure);
PtrTableStorageManager &sm = NpFactory::getInstance().getPtrTableStorageManager();
mShapes.clear(sm);
mSceneQueryData.clear(sm);
}
void NpShapeManager::preExportDataReset() {
// Clearing SceneQueryPruner handles to avoid stale references after deserialization and for deterministic
// serialization output. Multi shape cases handled in exportExtraData
if (getNbShapes() == 1) {
setPrunerData(0, Sq::PrunerData(SQ_INVALID_PRUNER_DATA));
}
}
void NpShapeManager::exportExtraData(PxSerializationContext &stream) {
mShapes.exportExtraData(stream);
// Clearing SceneQueryPruner handles to avoid stale references after deserialization and for deterministic
// serialization output. For single shape, it's handled on exportData.
PxU32 numShapes = getNbShapes();
if (numShapes > 1) {
stream.alignData(PX_SERIAL_ALIGN);
for (PxU32 i = 0; i < numShapes; i++) {
void *data = reinterpret_cast<void *>(Sq::PrunerData(SQ_INVALID_PRUNER_DATA));
stream.writeData(&data, sizeof(void *));
}
}
}
void NpShapeManager::importExtraData(PxDeserializationContext &context) {
mShapes.importExtraData(context);
mSceneQueryData.importExtraData(context);
}
//~PX_SERIALIZATION
void NpShapeManager::attachShape(NpShape &shape, PxRigidActor &actor) {
PX_ASSERT(!mPruningStructure);
PtrTableStorageManager &sm = NpFactory::getInstance().getPtrTableStorageManager();
const PxU32 index = getNbShapes();
mShapes.add(&shape, sm);
mSceneQueryData.add(reinterpret_cast<void *>(size_t(SQ_INVALID_PRUNER_DATA)), sm);
NpScene *scene = NpActor::getAPIScene(actor);
if (scene && isSceneQuery(shape))
setupSceneQuery(scene->getSceneQueryManagerFast(), actor, index);
Scb::RigidObject &ro = static_cast<Scb::RigidObject &>(NpActor::getScbFromPxActor(actor));
ro.onShapeAttach(shape.getScbShape());
PX_ASSERT(!shape.isExclusive() || shape.getActor() == NULL);
shape.onActorAttach(actor);
}
bool NpShapeManager::detachShape(NpShape &s, PxRigidActor &actor, bool wakeOnLostTouch) {
PX_ASSERT(!mPruningStructure);
const PxU32 index = mShapes.find(&s);
if (index == 0xffffffff)
return false;
NpScene *scene = NpActor::getAPIScene(actor);
if (scene && isSceneQuery(s)) {
scene->getSceneQueryManagerFast().removePrunerShape(mSqCompoundId, getPrunerData(index));
// if this is the last shape of a compound shape, we have to remove the compound id
// and in case of a dynamic actor, remove it from the active list
if (isSqCompound() && (mShapes.getCount() == 1)) {
mSqCompoundId = INVALID_PRUNERHANDLE;
const PxType actorType = actor.getConcreteType();
const bool isDynamic =
actorType == PxConcreteType::eRIGID_DYNAMIC || actorType == PxConcreteType::eARTICULATION_LINK;
if (isDynamic) {
// for PxRigidDynamic and PxArticulationLink we need to remove the compound rigid flag and remove them from
// active list
if (actor.is<PxRigidDynamic>())
const_cast<NpRigidDynamic &>(static_cast<const NpRigidDynamic &>(actor))
.getScbBodyFast()
.getScBody()
.getSim()
->disableCompound();
else {
if (actor.is<PxArticulationLink>())
const_cast<NpArticulationLink &>(static_cast<const NpArticulationLink &>(actor))
.getScbBodyFast()
.getScBody()
.getSim()
->disableCompound();
}
}
}
}
Scb::RigidObject &ro = static_cast<Scb::RigidObject &>(NpActor::getScbFromPxActor(actor));
ro.onShapeDetach(s.getScbShape(), wakeOnLostTouch, (s.getRefCount() == 1));
PtrTableStorageManager &sm = NpFactory::getInstance().getPtrTableStorageManager();
mShapes.replaceWithLast(index, sm);
mSceneQueryData.replaceWithLast(index, sm);
s.onActorDetach();
return true;
}
void NpShapeManager::detachAll(NpScene *scene, const PxRigidActor &actor) {
// assumes all SQ data has been released, which is currently the responsbility of the owning actor
const PxU32 nbShapes = getNbShapes();
NpShape *const *shapes = getShapes();
if (scene)
teardownAllSceneQuery(scene->getSceneQueryManagerFast(), actor);
// actor cleanup in Scb/Sc will remove any outstanding references corresponding to sim objects, so we don't need to do
// that here.
for (PxU32 i = 0; i < nbShapes; i++)
shapes[i]->onActorDetach();
PtrTableStorageManager &sm = NpFactory::getInstance().getPtrTableStorageManager();
mShapes.clear(sm);
mSceneQueryData.clear(sm);
}
PxU32 NpShapeManager::getShapes(PxShape **buffer, PxU32 bufferSize, PxU32 startIndex) const {
return getArrayOfPointers(buffer, bufferSize, startIndex, getShapes(), getNbShapes());
}
PxBounds3 NpShapeManager::getWorldBounds(const PxRigidActor &actor) const {
PxBounds3 bounds(PxBounds3::empty());
const PxU32 nbShapes = getNbShapes();
const PxTransform actorPose = actor.getGlobalPose();
NpShape *const *PX_RESTRICT shapes = getShapes();
for (PxU32 i = 0; i < nbShapes; i++)
bounds.include(
Gu::computeBounds(shapes[i]->getScbShape().getGeometry(), actorPose * shapes[i]->getLocalPoseFast()));
return bounds;
}
void NpShapeManager::clearShapesOnRelease(Scb::Scene &s, PxRigidActor &r) {
PX_ASSERT(static_cast<Scb::RigidObject &>(NpActor::getScbFromPxActor(r)).isSimDisabledInternally());
const PxU32 nbShapes = getNbShapes();
NpShape *const *PX_RESTRICT shapes = getShapes();
for (PxU32 i = 0; i < nbShapes; i++) {
Scb::Shape &scbShape = shapes[i]->getScbShape();
scbShape.checkUpdateOnRemove<false>(&s);
#if PX_SUPPORT_PVD
s.getScenePvdClient().releasePvdInstance(&scbShape, r);
#else
PX_UNUSED(r);
#endif
}
}
void NpShapeManager::releaseExclusiveUserReferences() {
// when the factory is torn down, release any shape owner refs that are still outstanding
const PxU32 nbShapes = getNbShapes();
NpShape *const *PX_RESTRICT shapes = getShapes();
for (PxU32 i = 0; i < nbShapes; i++) {
if (shapes[i]->isExclusiveFast() && shapes[i]->getRefCount() > 1)
shapes[i]->release();
}
}
void NpShapeManager::setupSceneQuery(SceneQueryManager &sqManager, const PxRigidActor &actor, const NpShape &shape) {
PX_ASSERT(shape.getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE);
const PxU32 index = mShapes.find(&shape);
PX_ASSERT(index != 0xffffffff);
setupSceneQuery(sqManager, actor, index);
}
void NpShapeManager::teardownSceneQuery(SceneQueryManager &sqManager, const NpShape &shape) {
const PxU32 index = mShapes.find(&shape);
PX_ASSERT(index != 0xffffffff);
teardownSceneQuery(sqManager, index);
}
void NpShapeManager::setupAllSceneQuery(NpScene *scene, const PxRigidActor &actor, bool hasPrunerStructure,
const PxBounds3 *bounds, const Gu::BVHStructure *bvhStructure) {
PX_ASSERT(scene); // shouldn't get here unless we're in a scene
SceneQueryManager &sqManager = scene->getSceneQueryManagerFast();
const PxU32 nbShapes = getNbShapes();
NpShape *const *shapes = getShapes();
// if BVH structure was provided, we add shapes into compound pruner
if (bvhStructure) {
addBVHStructureShapes(sqManager, actor, bvhStructure);
} else {
const PxType actorType = actor.getConcreteType();
const bool isDynamic =
actorType == PxConcreteType::eRIGID_DYNAMIC || actorType == PxConcreteType::eARTICULATION_LINK;
for (PxU32 i = 0; i < nbShapes; i++) {
if (isSceneQuery(*shapes[i]))
addPrunerShape(sqManager, i, *shapes[i], actor, isDynamic, bounds ? bounds + i : NULL, hasPrunerStructure);
}
}
}
void NpShapeManager::teardownAllSceneQuery(SceneQueryManager &sqManager, const PxRigidActor &actor) {
NpShape *const *shapes = getShapes();
const PxU32 nbShapes = getNbShapes();
if (isSqCompound()) {
const PxType actorType = actor.getConcreteType();
const bool isDynamic =
actorType == PxConcreteType::eRIGID_DYNAMIC || actorType == PxConcreteType::eARTICULATION_LINK;
sqManager.removeCompoundActor(mSqCompoundId, isDynamic);
for (PxU32 i = 0; i < nbShapes; i++) {
setPrunerData(i, SQ_INVALID_PRUNER_DATA);
}
mSqCompoundId = INVALID_PRUNERHANDLE;
return;
}
for (PxU32 i = 0; i < nbShapes; i++) {
if (isSceneQuery(*shapes[i]))
sqManager.removePrunerShape(INVALID_PRUNERHANDLE, getPrunerData(i));
setPrunerData(i, SQ_INVALID_PRUNER_DATA);
}
}
void NpShapeManager::markAllSceneQueryForUpdate(SceneQueryManager &sqManager, const PxRigidActor &actor) {
if (isSqCompound()) {
const PxType actorType = actor.getConcreteType();
const bool isDynamic =
actorType == PxConcreteType::eRIGID_DYNAMIC || actorType == PxConcreteType::eARTICULATION_LINK;
sqManager.updateCompoundActor(mSqCompoundId, actor.getGlobalPose(), isDynamic);
return;
}
const PxU32 nbShapes = getNbShapes();
for (PxU32 i = 0; i < nbShapes; i++) {
const PrunerData data = getPrunerData(i);
if (data != SQ_INVALID_PRUNER_DATA)
sqManager.markForUpdate(INVALID_PRUNERHANDLE, data);
}
}
Sq::PrunerData NpShapeManager::findSceneQueryData(const NpShape &shape) const {
const PxU32 index = mShapes.find(&shape);
PX_ASSERT(index != 0xffffffff);
PX_ASSERT(!isSqCompound()); // used in cases we know it is not a compound
return getPrunerData(index);
}
Sq::PrunerData NpShapeManager::findSceneQueryData(const NpShape &shape, Sq::PrunerCompoundId &compoundId) const {
const PxU32 index = mShapes.find(&shape);
PX_ASSERT(index != 0xffffffff);
compoundId = mSqCompoundId;
return getPrunerData(index);
}
//
// internal methods
//
void NpShapeManager::addBVHStructureShapes(SceneQueryManager &sqManager, const PxRigidActor &actor,
const Gu::BVHStructure *bvhStructure) {
PX_ASSERT(bvhStructure);
const Scb::Actor &scbActor = NpActor::getScbFromPxActor(actor);
const PxU32 nbShapes = getNbShapes();
PX_ALLOCA(scbShapes, const Scb::Shape *, nbShapes);
PX_ALLOCA(prunerData, Sq::PrunerData, nbShapes);
PxU32 numSqShapes = 0;
for (PxU32 i = 0; i < nbShapes; i++) {
const NpShape &shape = *getShapes()[i];
if (isSceneQuery(shape))
scbShapes[numSqShapes++] = &shape.getScbShape();
}
PX_ASSERT(numSqShapes == bvhStructure->getNbBounds());
mSqCompoundId = static_cast<const Sc::RigidCore &>(NpActor::getScbFromPxActor(actor).getActorCore()).getRigidID();
sqManager.addCompoundShape(*bvhStructure, mSqCompoundId, actor.getGlobalPose(), prunerData, scbShapes, scbActor);
numSqShapes = 0;
for (PxU32 i = 0; i < nbShapes; i++) {
const NpShape &shape = *getShapes()[i];
if (isSceneQuery(shape))
setPrunerData(i, prunerData[numSqShapes++]);
}
}
void NpShapeManager::addPrunerShape(SceneQueryManager &sqManager, PxU32 index, const NpShape &shape,
const PxRigidActor &actor, bool dynamic, const PxBounds3 *bound,
bool hasPrunerStructure) {
const Scb::Shape &scbShape = shape.getScbShape();
const Scb::Actor &scbActor = NpActor::getScbFromPxActor(actor);
setPrunerData(index, sqManager.addPrunerShape(scbShape, scbActor, dynamic, mSqCompoundId, bound, hasPrunerStructure));
}
void NpShapeManager::setupSceneQuery(SceneQueryManager &sqManager, const PxRigidActor &actor, PxU32 index) {
const PxType actorType = actor.getConcreteType();
const bool isDynamic = actorType == PxConcreteType::eRIGID_DYNAMIC || actorType == PxConcreteType::eARTICULATION_LINK;
addPrunerShape(sqManager, index, *(getShapes()[index]), actor, isDynamic, NULL, false);
}
void NpShapeManager::teardownSceneQuery(SceneQueryManager &sqManager, PxU32 index) {
sqManager.removePrunerShape(mSqCompoundId, getPrunerData(index));
setPrunerData(index, SQ_INVALID_PRUNER_DATA);
}
#if PX_ENABLE_DEBUG_VISUALIZATION
#include "GuConvexEdgeFlags.h"
#include "GuHeightFieldUtil.h"
#include "GuMidphaseInterface.h"
#include "geometry/PxGeometryQuery.h"
#include "geometry/PxMeshQuery.h"
static const PxU32 gCollisionShapeColor = PxU32(PxDebugColor::eARGB_MAGENTA);
static void visualizeSphere(const PxSphereGeometry &geometry, RenderOutput &out, const PxTransform &absPose) {
out << gCollisionShapeColor; // PT: no need to output this for each segment!
out << absPose << DebugCircle(100, geometry.radius);
PxMat44 rotPose(absPose);
Ps::swap(rotPose.column1, rotPose.column2);
rotPose.column1 = -rotPose.column1;
out << rotPose << DebugCircle(100, geometry.radius);
Ps::swap(rotPose.column0, rotPose.column2);
rotPose.column0 = -rotPose.column0;
out << rotPose << DebugCircle(100, geometry.radius);
}
static void visualizePlane(const PxPlaneGeometry & /*geometry*/, RenderOutput &out, const PxTransform &absPose) {
PxMat44 rotPose(absPose);
Ps::swap(rotPose.column1, rotPose.column2);
rotPose.column1 = -rotPose.column1;
Ps::swap(rotPose.column0, rotPose.column2);
rotPose.column0 = -rotPose.column0;
out << rotPose << gCollisionShapeColor; // PT: no need to output this for each segment!
for (PxReal radius = 2.0f; radius < 20.0f; radius += 2.0f)
out << DebugCircle(100, radius * radius);
}
static void visualizeCapsule(const PxCapsuleGeometry &geometry, RenderOutput &out, const PxTransform &absPose) {
out << gCollisionShapeColor;
out.outputCapsule(geometry.radius, geometry.halfHeight, absPose);
}
static void visualizeBox(const PxBoxGeometry &geometry, RenderOutput &out, const PxTransform &absPose) {
out << gCollisionShapeColor;
out << absPose << DebugBox(geometry.halfExtents);
}
static void visualizeConvexMesh(const PxConvexMeshGeometry &geometry, RenderOutput &out, const PxTransform &absPose) {
const ConvexMesh *convexMesh = static_cast<const ConvexMesh *>(geometry.convexMesh);
const ConvexHullData &hullData = convexMesh->getHull();
const PxVec3 *vertices = hullData.getHullVertices();
const PxU8 *indexBuffer = hullData.getVertexData8();
const PxU32 nbPolygons = convexMesh->getNbPolygonsFast();
const PxMat44 m44(PxMat33(absPose.q) * geometry.scale.toMat33(), absPose.p);
out << m44 << gCollisionShapeColor; // PT: no need to output this for each segment!
for (PxU32 i = 0; i < nbPolygons; i++) {
const PxU32 pnbVertices = hullData.mPolygons[i].mNbVerts;
PxVec3 begin = m44.transform(vertices[indexBuffer[0]]); // PT: transform it only once before the loop starts
for (PxU32 j = 1; j < pnbVertices; j++) {
const PxVec3 end = m44.transform(vertices[indexBuffer[j]]);
out.outputSegment(begin, end);
begin = end;
}
out.outputSegment(begin, m44.transform(vertices[indexBuffer[0]]));
indexBuffer += pnbVertices;
}
}
static void getTriangle(const Gu::TriangleMesh &, PxU32 i, PxVec3 *wp, const PxVec3 *vertices, const void *indices,
bool has16BitIndices) {
PxU32 ref0, ref1, ref2;
if (!has16BitIndices) {
const PxU32 *dtriangles = reinterpret_cast<const PxU32 *>(indices);
ref0 = dtriangles[i * 3 + 0];
ref1 = dtriangles[i * 3 + 1];
ref2 = dtriangles[i * 3 + 2];
} else {
const PxU16 *wtriangles = reinterpret_cast<const PxU16 *>(indices);
ref0 = wtriangles[i * 3 + 0];
ref1 = wtriangles[i * 3 + 1];
ref2 = wtriangles[i * 3 + 2];
}
wp[0] = vertices[ref0];
wp[1] = vertices[ref1];
wp[2] = vertices[ref2];
}
static void getTriangle(const Gu::TriangleMesh &mesh, PxU32 i, PxVec3 *wp, const PxVec3 *vertices, const void *indices,
const Matrix34 &absPose, bool has16BitIndices) {
PxVec3 localVerts[3];
getTriangle(mesh, i, localVerts, vertices, indices, has16BitIndices);
wp[0] = absPose.transform(localVerts[0]);
wp[1] = absPose.transform(localVerts[1]);
wp[2] = absPose.transform(localVerts[2]);
}
static void visualizeActiveEdges(RenderOutput &out, const Gu::TriangleMesh &mesh, PxU32 nbTriangles,
const PxU32 *results, const Matrix34 &absPose) {
const PxU8 *extraTrigData = mesh.getExtraTrigData();
PX_ASSERT(extraTrigData);
const PxVec3 *vertices = mesh.getVerticesFast();
const void *indices = mesh.getTrianglesFast();
out << PxU32(PxDebugColor::eARGB_YELLOW); // PT: no need to output this for each segment!
const bool has16Bit = mesh.has16BitIndices();
for (PxU32 i = 0; i < nbTriangles; i++) {
const PxU32 index = results ? results[i] : i;
PxVec3 wp[3];
getTriangle(mesh, index, wp, vertices, indices, absPose, has16Bit);
const PxU32 flags = extraTrigData[index];
if (flags & Gu::ETD_CONVEX_EDGE_01)
out.outputSegment(wp[0], wp[1]);
if (flags & Gu::ETD_CONVEX_EDGE_12)
out.outputSegment(wp[1], wp[2]);
if (flags & Gu::ETD_CONVEX_EDGE_20)
out.outputSegment(wp[0], wp[2]);
}
}
static void visualizeFaceNormals(PxReal fscale, RenderOutput &out, const TriangleMesh &mesh, PxU32 nbTriangles,
const PxVec3 *vertices, const void *indices, bool has16Bit, const PxU32 *results,
const Matrix34 &absPose, const PxMat44 &midt) {
if (fscale == 0.0f)
return;
out << midt << PxU32(PxDebugColor::eARGB_DARKRED); // PT: no need to output this for each segment!
for (PxU32 i = 0; i < nbTriangles; i++) {
const PxU32 index = results ? results[i] : i;
PxVec3 wp[3];
getTriangle(mesh, index, wp, vertices, indices, absPose, has16Bit);
const PxVec3 center = (wp[0] + wp[1] + wp[2]) / 3.0f;
PxVec3 normal = (wp[0] - wp[1]).cross(wp[0] - wp[2]);
PX_ASSERT(!normal.isZero());
normal = normal.getNormalized();
out << DebugArrow(center, normal * fscale);
}
}
static PX_FORCE_INLINE void outputTriangle(PxDebugLine *segments, const PxVec3 &v0, const PxVec3 &v1, const PxVec3 &v2,
PxU32 color) {
// PT: TODO: use SIMD
segments[0] = PxDebugLine(v0, v1, color);
segments[1] = PxDebugLine(v1, v2, color);
segments[2] = PxDebugLine(v2, v0, color);
}
static void visualizeTriangleMesh(const PxTriangleMeshGeometry &geometry, RenderOutput &out, const PxTransform &pose,
const PxBounds3 &cullbox, const PxReal fscale, bool visualizeShapes,
bool visualizeEdges, bool useCullBox) {
const TriangleMesh *triangleMesh = static_cast<const TriangleMesh *>(geometry.triangleMesh);
const PxMat44 midt(PxIdentity);
const Matrix34 absPose(PxMat33(pose.q) * geometry.scale.toMat33(), pose.p);
PxU32 nbTriangles = triangleMesh->getNbTrianglesFast();
const PxU32 nbVertices = triangleMesh->getNbVerticesFast();
const PxVec3 *vertices = triangleMesh->getVerticesFast();
const void *indices = triangleMesh->getTrianglesFast();
const bool has16Bit = triangleMesh->has16BitIndices();
// PT: TODO: don't render the same edge multiple times
PxU32 *results = NULL;
if (useCullBox) {
const Gu::Box worldBox((cullbox.maximum + cullbox.minimum) * 0.5f, (cullbox.maximum - cullbox.minimum) * 0.5f,
PxMat33(PxIdentity));
// PT: TODO: use the callback version here to avoid allocating this huge array
results = reinterpret_cast<PxU32 *>(PX_ALLOC_TEMP(sizeof(PxU32) * nbTriangles, "tmp triangle indices"));
LimitedResults limitedResults(results, nbTriangles, 0);
Midphase::intersectBoxVsMesh(worldBox, *triangleMesh, pose, geometry.scale, &limitedResults);
nbTriangles = limitedResults.mNbResults;
if (visualizeShapes) {
const PxU32 scolor = gCollisionShapeColor;
out << midt << scolor; // PT: no need to output this for each segment!
PxDebugLine *segments = out.reserveSegments(nbTriangles * 3);
for (PxU32 i = 0; i < nbTriangles; i++) {
PxVec3 wp[3];
getTriangle(*triangleMesh, results[i], wp, vertices, indices, absPose, has16Bit);
outputTriangle(segments, wp[0], wp[1], wp[2], scolor);
segments += 3;
}
}
} else {
if (visualizeShapes) {
const PxU32 scolor = gCollisionShapeColor;
out << midt << scolor; // PT: no need to output this for each segment!
// PT: TODO: use SIMD
PxVec3 *transformed = reinterpret_cast<PxVec3 *>(PX_ALLOC(sizeof(PxVec3) * nbVertices, "PxVec3"));
for (PxU32 i = 0; i < nbVertices; i++)
transformed[i] = absPose.transform(vertices[i]);
PxDebugLine *segments = out.reserveSegments(nbTriangles * 3);
for (PxU32 i = 0; i < nbTriangles; i++) {
PxVec3 wp[3];
getTriangle(*triangleMesh, i, wp, transformed, indices, has16Bit);
outputTriangle(segments, wp[0], wp[1], wp[2], scolor);
segments += 3;
}
PX_FREE(transformed);
}
}
visualizeFaceNormals(fscale, out, *triangleMesh, nbTriangles, vertices, indices, has16Bit, results, absPose, midt);
if (visualizeEdges && triangleMesh->getExtraTrigData())
visualizeActiveEdges(out, *triangleMesh, nbTriangles, results, absPose);
if (results)
PX_FREE(results);
}
static void visualizeHeightField(const PxHeightFieldGeometry &hfGeometry, RenderOutput &out, const PxTransform &absPose,
const PxBounds3 &cullbox, bool useCullBox) {
const HeightField *heightfield = static_cast<const HeightField *>(hfGeometry.heightField);
// PT: TODO: the debug viz for HFs is minimal at the moment...
const PxU32 scolor = gCollisionShapeColor;
const PxMat44 midt = PxMat44(PxIdentity);
HeightFieldUtil hfUtil(hfGeometry);
const PxU32 nbRows = heightfield->getNbRowsFast();
const PxU32 nbColumns = heightfield->getNbColumnsFast();
const PxU32 nbVerts = nbRows * nbColumns;
const PxU32 nbTriangles = 2 * nbVerts;
out << midt << scolor; // PT: no need to output the same matrix/color for each triangle
if (useCullBox) {
const PxTransform pose0((cullbox.maximum + cullbox.minimum) * 0.5f);
const PxBoxGeometry boxGeometry((cullbox.maximum - cullbox.minimum) * 0.5f);
PxU32 *results = reinterpret_cast<PxU32 *>(PX_ALLOC(sizeof(PxU32) * nbTriangles, "tmp triangle indices"));
bool overflow = false;
PxU32 nbTouchedTris =
PxMeshQuery::findOverlapHeightField(boxGeometry, pose0, hfGeometry, absPose, results, nbTriangles, 0, overflow);
PxDebugLine *segments = out.reserveSegments(nbTouchedTris * 3);
for (PxU32 i = 0; i < nbTouchedTris; i++) {
const PxU32 index = results[i];
PxTriangle currentTriangle;
PxMeshQuery::getTriangle(hfGeometry, absPose, index, currentTriangle);
// The check has been done in the findOverlapHeightField
// if(heightfield->isValidTriangle(index) && heightfield->getTriangleMaterial(index) !=
// PxHeightFieldMaterial::eHOLE)
{
outputTriangle(segments, currentTriangle.verts[0], currentTriangle.verts[1], currentTriangle.verts[2], scolor);
segments += 3;
}
}
PX_FREE(results);
} else {
// PT: transform vertices only once
PxVec3 *tmpVerts = reinterpret_cast<PxVec3 *>(PX_ALLOC(sizeof(PxVec3) * nbVerts, "PxVec3"));
// PT: TODO: optimize the following line
for (PxU32 i = 0; i < nbVerts; i++)
tmpVerts[i] = absPose.transform(hfUtil.hf2shapep(heightfield->getVertex(i)));
for (PxU32 i = 0; i < nbTriangles; i++) {
if (heightfield->isValidTriangle(i) && heightfield->getTriangleMaterial(i) != PxHeightFieldMaterial::eHOLE) {
PxU32 vi0, vi1, vi2;
heightfield->getTriangleVertexIndices(i, vi0, vi1, vi2);
PxDebugLine *segments = out.reserveSegments(3);
outputTriangle(segments, tmpVerts[vi0], tmpVerts[vi1], tmpVerts[vi2], scolor);
}
}
PX_FREE(tmpVerts);
}
}
static void visualize(const PxGeometry &geometry, RenderOutput &out, const PxTransform &absPose,
const PxBounds3 &cullbox, const PxReal fscale, bool visualizeShapes, bool visualizeEdges,
bool useCullBox) {
// triangle meshes can render active edges or face normals, but for other types we can just early out if there are no
// collision shapes
if (!visualizeShapes && geometry.getType() != PxGeometryType::eTRIANGLEMESH)
return;
switch (geometry.getType()) {
case PxGeometryType::eSPHERE:
visualizeSphere(static_cast<const PxSphereGeometry &>(geometry), out, absPose);
break;
case PxGeometryType::eBOX:
visualizeBox(static_cast<const PxBoxGeometry &>(geometry), out, absPose);
break;
case PxGeometryType::ePLANE:
visualizePlane(static_cast<const PxPlaneGeometry &>(geometry), out, absPose);
break;
case PxGeometryType::eCAPSULE:
visualizeCapsule(static_cast<const PxCapsuleGeometry &>(geometry), out, absPose);
break;
case PxGeometryType::eCONVEXMESH:
visualizeConvexMesh(static_cast<const PxConvexMeshGeometry &>(geometry), out, absPose);
break;
case PxGeometryType::eTRIANGLEMESH:
visualizeTriangleMesh(static_cast<const PxTriangleMeshGeometry &>(geometry), out, absPose, cullbox, fscale,
visualizeShapes, visualizeEdges, useCullBox);
break;
case PxGeometryType::eHEIGHTFIELD:
visualizeHeightField(static_cast<const PxHeightFieldGeometry &>(geometry), out, absPose, cullbox, useCullBox);
break;
case PxGeometryType::eINVALID:
break;
case PxGeometryType::eGEOMETRY_COUNT:
break;
}
}
void NpShapeManager::visualize(RenderOutput &out, NpScene *scene, const PxRigidActor &actor) {
const PxReal scale = scene->getVisualizationParameter(PxVisualizationParameter::eSCALE);
if (!scale)
return;
const PxU32 nbShapes = getNbShapes();
NpShape *const *PX_RESTRICT shapes = getShapes();
const bool visualizeCompounds =
(nbShapes > 1) && scene->getVisualizationParameter(PxVisualizationParameter::eCOLLISION_COMPOUNDS) != 0.0f;
// PT: moved all these out of the loop, no need to grab them once per shape
const PxBounds3 &cullbox = scene->getScene().getVisualizationCullingBox();
const bool visualizeAABBs = scene->getVisualizationParameter(PxVisualizationParameter::eCOLLISION_AABBS) != 0.0f;
const bool visualizeShapes = scene->getVisualizationParameter(PxVisualizationParameter::eCOLLISION_SHAPES) != 0.0f;
const bool visualizeEdges = scene->getVisualizationParameter(PxVisualizationParameter::eCOLLISION_EDGES) != 0.0f;
const float fNormals = scene->getVisualizationParameter(PxVisualizationParameter::eCOLLISION_FNORMALS);
const bool visualizeFNormals = fNormals != 0.0f;
const bool visualizeCollision = visualizeShapes || visualizeFNormals || visualizeEdges;
const bool useCullBox = !cullbox.isEmpty();
const bool needsShapeBounds0 = visualizeCompounds || (visualizeCollision && useCullBox);
const PxReal collisionAxes = scale * scene->getVisualizationParameter(PxVisualizationParameter::eCOLLISION_AXES);
const PxReal fscale = scale * fNormals;
const PxTransform actorPose = actor.getGlobalPose();
PxBounds3 compoundBounds(PxBounds3::empty());
for (PxU32 i = 0; i < nbShapes; i++) {
const Scb::Shape &scbShape = shapes[i]->getScbShape();
const PxTransform absPose = actorPose * scbShape.getShape2Actor();
const PxGeometry &geom = scbShape.getGeometry();
const bool shapeDebugVizEnabled = scbShape.getFlags() & PxShapeFlag::eVISUALIZATION;
const bool needsShapeBounds = needsShapeBounds0 || (visualizeAABBs && shapeDebugVizEnabled);
const PxBounds3 currentShapeBounds = needsShapeBounds ? Gu::computeBounds(geom, absPose) : PxBounds3::empty();
if (shapeDebugVizEnabled) {
if (visualizeAABBs)
out << PxU32(PxDebugColor::eARGB_YELLOW) << PxMat44(PxIdentity) << DebugBox(currentShapeBounds);
if (collisionAxes != 0.0f)
out << PxMat44(absPose) << DebugBasis(PxVec3(collisionAxes), 0xcf0000, 0x00cf00, 0x0000cf);
if (visualizeCollision) {
if (!useCullBox || cullbox.intersects(currentShapeBounds))
::visualize(geom, out, absPose, cullbox, fscale, visualizeShapes, visualizeEdges, useCullBox);
}
}
if (visualizeCompounds)
compoundBounds.include(currentShapeBounds);
}
if (visualizeCompounds && !compoundBounds.isEmpty())
out << gCollisionShapeColor << PxMat44(PxIdentity) << DebugBox(compoundBounds);
}
#endif // PX_ENABLE_DEBUG_VISUALIZATION
| 40.00651
| 120
| 0.710073
|
yangfengzzz
|
3bc1b262680b05ee3564c5355d4bc61291d1b6e0
| 5,742
|
cpp
|
C++
|
c3dToolKit/core/c3dMath.cpp
|
wantnon2/3DToolKit-2-for-cocos2dx
|
518aa856f06788929e50897b43969e5cfa50c3cf
|
[
"MIT"
] | 11
|
2015-02-12T04:34:43.000Z
|
2021-10-10T06:24:55.000Z
|
c3dToolKit/core/c3dMath.cpp
|
wantnon2/3DToolKit-2-for-cocos2dx
|
518aa856f06788929e50897b43969e5cfa50c3cf
|
[
"MIT"
] | null | null | null |
c3dToolKit/core/c3dMath.cpp
|
wantnon2/3DToolKit-2-for-cocos2dx
|
518aa856f06788929e50897b43969e5cfa50c3cf
|
[
"MIT"
] | 8
|
2015-06-30T11:51:30.000Z
|
2021-10-10T06:24:56.000Z
|
//
// c3dMath.cpp
// HelloCpp
//
// Created by yang chao (wantnon) on 14-1-4.
//
//
#include "c3dMath.h"
Cc3dMatrix4 unitMat(){
Cc3dMatrix4 mat(1,0,0,0,//col 1
0,1,0,0,
0,0,1,0,
0,0,0,1);
return mat;
}
Cc3dMatrix4 zeroMat(){
Cc3dMatrix4 mat(0,0,0,0,//col 1
0,0,0,0,
0,0,0,0,
0,0,0,0);
return mat;
}
bool isEqual(const Cc3dMatrix4&mat1,const Cc3dMatrix4&mat2,float eps){
for(int i=0;i<16;i++){
float d=fabsf(mat1.getAt(i)-mat2.getAt(i));
if(d>eps)return false;
}
return true;
}
bool isEqual(const Cc3dVector4&v1,const Cc3dVector4&v2,float eps){
for(int i=0;i<4;i++){
float d=fabsf(v1.getAt(i)-v2.getAt(i));
if(d>eps)return false;
}
return true;
}
bool isUnitMat(const Cc3dMatrix4&mat){
return isEqual(mat, unitMat());
}
Cc3dVector4 normalize(const Cc3dVector4&v){
assert(v.w()==0);
float r2=v.x()*v.x()+v.y()*v.y()+v.z()*v.z();
if(r2==0){
return Cc3dVector4(0,0,0,0);
}
float r=sqrtf(r2);
Cc3dVector4 rs(v.x()/r,v.y()/r,v.z()/r,0);
return rs;
}
float dot(const Cc3dVector4&v1,const Cc3dVector4&v2){
return v1.x()*v2.x()+v1.y()*v2.y()+v1.z()*v2.z();
}
Cc3dVector4 cross(const Cc3dVector4&v1,const Cc3dVector4&v2)
{
assert(v1.w()==0);
assert(v2.w()==0);
Cc3dVector4 rs(v1.y()*v2.z()-v1.z()*v2.y(),
v1.z()*v2.x()-v1.x()*v2.z(),
v1.x()*v2.y()-v1.y()*v2.x(),
0);//cross product result must be a vector, so the fourth component set to zero
return rs;
}
Cc3dMatrix4 transpose(const Cc3dMatrix4&mat){
const float* m=mat.getArray();
float rs[16]={
m[0],m[4],m[8],m[12],//col 1
m[1],m[5],m[9],m[13],//col 2
m[2],m[6],m[10],m[14],//col 3
m[3],m[7],m[11],m[15]//col 4
};
return Cc3dMatrix4(rs);
}
Cc3dMatrix4 inverse(const Cc3dMatrix4&mat){
//this code is copy from:http://stackoverflow.com/questions/1148309/inverting-a-4x4-matrix
float m[16];
for(int i=0;i<16;i++)m[i]=mat.getAt(i);
float invOut[16];
float inv[16], det;
int i;
inv[0] = m[5] * m[10] * m[15] -
m[5] * m[11] * m[14] -
m[9] * m[6] * m[15] +
m[9] * m[7] * m[14] +
m[13] * m[6] * m[11] -
m[13] * m[7] * m[10];
inv[4] = -m[4] * m[10] * m[15] +
m[4] * m[11] * m[14] +
m[8] * m[6] * m[15] -
m[8] * m[7] * m[14] -
m[12] * m[6] * m[11] +
m[12] * m[7] * m[10];
inv[8] = m[4] * m[9] * m[15] -
m[4] * m[11] * m[13] -
m[8] * m[5] * m[15] +
m[8] * m[7] * m[13] +
m[12] * m[5] * m[11] -
m[12] * m[7] * m[9];
inv[12] = -m[4] * m[9] * m[14] +
m[4] * m[10] * m[13] +
m[8] * m[5] * m[14] -
m[8] * m[6] * m[13] -
m[12] * m[5] * m[10] +
m[12] * m[6] * m[9];
inv[1] = -m[1] * m[10] * m[15] +
m[1] * m[11] * m[14] +
m[9] * m[2] * m[15] -
m[9] * m[3] * m[14] -
m[13] * m[2] * m[11] +
m[13] * m[3] * m[10];
inv[5] = m[0] * m[10] * m[15] -
m[0] * m[11] * m[14] -
m[8] * m[2] * m[15] +
m[8] * m[3] * m[14] +
m[12] * m[2] * m[11] -
m[12] * m[3] * m[10];
inv[9] = -m[0] * m[9] * m[15] +
m[0] * m[11] * m[13] +
m[8] * m[1] * m[15] -
m[8] * m[3] * m[13] -
m[12] * m[1] * m[11] +
m[12] * m[3] * m[9];
inv[13] = m[0] * m[9] * m[14] -
m[0] * m[10] * m[13] -
m[8] * m[1] * m[14] +
m[8] * m[2] * m[13] +
m[12] * m[1] * m[10] -
m[12] * m[2] * m[9];
inv[2] = m[1] * m[6] * m[15] -
m[1] * m[7] * m[14] -
m[5] * m[2] * m[15] +
m[5] * m[3] * m[14] +
m[13] * m[2] * m[7] -
m[13] * m[3] * m[6];
inv[6] = -m[0] * m[6] * m[15] +
m[0] * m[7] * m[14] +
m[4] * m[2] * m[15] -
m[4] * m[3] * m[14] -
m[12] * m[2] * m[7] +
m[12] * m[3] * m[6];
inv[10] = m[0] * m[5] * m[15] -
m[0] * m[7] * m[13] -
m[4] * m[1] * m[15] +
m[4] * m[3] * m[13] +
m[12] * m[1] * m[7] -
m[12] * m[3] * m[5];
inv[14] = -m[0] * m[5] * m[14] +
m[0] * m[6] * m[13] +
m[4] * m[1] * m[14] -
m[4] * m[2] * m[13] -
m[12] * m[1] * m[6] +
m[12] * m[2] * m[5];
inv[3] = -m[1] * m[6] * m[11] +
m[1] * m[7] * m[10] +
m[5] * m[2] * m[11] -
m[5] * m[3] * m[10] -
m[9] * m[2] * m[7] +
m[9] * m[3] * m[6];
inv[7] = m[0] * m[6] * m[11] -
m[0] * m[7] * m[10] -
m[4] * m[2] * m[11] +
m[4] * m[3] * m[10] +
m[8] * m[2] * m[7] -
m[8] * m[3] * m[6];
inv[11] = -m[0] * m[5] * m[11] +
m[0] * m[7] * m[9] +
m[4] * m[1] * m[11] -
m[4] * m[3] * m[9] -
m[8] * m[1] * m[7] +
m[8] * m[3] * m[5];
inv[15] = m[0] * m[5] * m[10] -
m[0] * m[6] * m[9] -
m[4] * m[1] * m[10] +
m[4] * m[2] * m[9] +
m[8] * m[1] * m[6] -
m[8] * m[2] * m[5];
det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
if (det == 0)
//return false;
assert(false);
det = 1.0 / det;
for (i = 0; i < 16; i++)
invOut[i] = inv[i] * det;
// return true;
return Cc3dMatrix4(invOut);
}
Cc3dVector4 toV4(const Cc3dVector2&v2,float z,float w){
return Cc3dVector4(v2.x(), v2.y(), z, w);
}
Cc3dVector2 toV2(const Cc3dVector4&v4){
return Cc3dVector2(v4.x(), v4.y());
}
float getLength2(const Cc3dVector4&v){//square of length
assert(v.w()==0);
return v.x()*v.x()+v.y()*v.y()+v.z()*v.z();
}
float getLength(const Cc3dVector4&v){
assert(v.w()==0);
return sqrtf(v.x()*v.x()+v.y()*v.y()+v.z()*v.z());
}
| 25.40708
| 98
| 0.40613
|
wantnon2
|
3bc75cd7054bae66c21293a99fba3e02c13ebe72
| 7,819
|
cpp
|
C++
|
src/pke/unittest/UnitTestEvalSum.cpp
|
mattdano/palisade
|
6e49bc3a850672a142eea209e6d71505e689cb81
|
[
"BSD-2-Clause"
] | null | null | null |
src/pke/unittest/UnitTestEvalSum.cpp
|
mattdano/palisade
|
6e49bc3a850672a142eea209e6d71505e689cb81
|
[
"BSD-2-Clause"
] | null | null | null |
src/pke/unittest/UnitTestEvalSum.cpp
|
mattdano/palisade
|
6e49bc3a850672a142eea209e6d71505e689cb81
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* @author TPOC: contact@palisade-crypto.org
*
* @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT)
* 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 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.
*/
#include "include/gtest/gtest.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include "../lib/cryptocontext.h"
#include "encoding/encodings.h"
#include "utils/debug.h"
using namespace std;
using namespace lbcrypto;
class UTEvalSum : public ::testing::Test {
protected:
void SetUp() {}
void TearDown() {
CryptoContextFactory<Poly>::ReleaseAllContexts();
CryptoContextFactory<DCRTPoly>::ReleaseAllContexts();
}
public:
};
int64_t ArbBGVEvalSumPackedArray(std::vector<int64_t> &clearVector, PlaintextModulus p);
int64_t ArbBGVEvalSumPackedArrayPrime(std::vector<int64_t> &clearVector, PlaintextModulus p);
int64_t ArbBFVEvalSumPackedArray(std::vector<int64_t> &clearVector, PlaintextModulus p);
void EvalSumSetup(std::vector<int64_t>& input, int64_t& expectedSum, PlaintextModulus plaintextMod) {
usint limit = 15;
random_device rnd_device;
mt19937 mersenne_engine(rnd_device());
uniform_int_distribution<usint> dist(0, limit);
auto gen = std::bind(dist, mersenne_engine);
generate(input.begin(), input.end()-2, gen);
expectedSum = std::accumulate(input.begin(), input.end(), 0);
expectedSum %= plaintextMod;
int64_t half = int64_t(plaintextMod)/2;
if( expectedSum > half )
expectedSum -= plaintextMod;
}
TEST_F(UTEvalSum, Test_BGV_EvalSum) {
usint size = 10;
std::vector<int64_t> input(size,0);
int64_t expectedSum;
EvalSumSetup(input,expectedSum, 89);
int64_t result = ArbBGVEvalSumPackedArray(input, 89);
EXPECT_EQ(expectedSum, result);
}
TEST_F(UTEvalSum, Test_BGV_EvalSum_Prime_Cyclotomics) {
usint size = 10;
std::vector<int64_t> input(size,0);
int64_t expectedSum;
EvalSumSetup(input,expectedSum, 23);
int64_t result = ArbBGVEvalSumPackedArrayPrime(input, 23);
EXPECT_EQ(expectedSum, result);
}
TEST_F(UTEvalSum, Test_BFV_EvalSum) {
usint size = 10;
std::vector<int64_t> input(size,0);
int64_t expectedSum;
EvalSumSetup(input,expectedSum, 89);
int64_t result = ArbBFVEvalSumPackedArray(input, 89);
EXPECT_EQ(expectedSum, result);
}
int64_t ArbBGVEvalSumPackedArray(std::vector<int64_t> &clearVector, PlaintextModulus p) {
usint m = 22;
BigInteger modulusP(p);
BigInteger modulusQ("955263939794561");
BigInteger squareRootOfRoot("941018665059848");
BigInteger bigmodulus("80899135611688102162227204937217");
BigInteger bigroot("77936753846653065954043047918387");
auto cycloPoly = GetCyclotomicPolynomial<BigVector>(m, modulusQ);
ChineseRemainderTransformArb<BigVector>::SetCylotomicPolynomial(cycloPoly, modulusQ);
float stdDev = 4;
usint batchSize = 8;
shared_ptr<ILParams> params(new ILParams(m, modulusQ, squareRootOfRoot, bigmodulus, bigroot));
EncodingParams encodingParams(new EncodingParamsImpl(p, batchSize, PackedEncoding::GetAutomorphismGenerator(m)));
PackedEncoding::SetParams(m, encodingParams);
CryptoContext<Poly> cc = CryptoContextFactory<Poly>::genCryptoContextBGV(params, encodingParams, 8, stdDev);
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
// Initialize the public key containers.
LPKeyPair<Poly> kp = cc->KeyGen();
Ciphertext<Poly> ciphertext;
Plaintext intArray = cc->MakePackedPlaintext(clearVector);
cc->EvalSumKeyGen(kp.secretKey);
ciphertext = cc->Encrypt(kp.publicKey, intArray);
auto ciphertextSum = cc->EvalSum(ciphertext, batchSize);
Plaintext intArrayNew;
cc->Decrypt(kp.secretKey, ciphertextSum, &intArrayNew);
return intArrayNew->GetPackedValue()[0];
}
int64_t ArbBGVEvalSumPackedArrayPrime(std::vector<int64_t> &clearVector, PlaintextModulus p) {
usint m = 11;
BigInteger modulusP(p);
BigInteger modulusQ("1125899906842679");
BigInteger squareRootOfRoot("7742739281594");
BigInteger bigmodulus("81129638414606681695789005144449");
BigInteger bigroot("74771531227552428119450922526156");
auto cycloPoly = GetCyclotomicPolynomial<BigVector>(m, modulusQ);
ChineseRemainderTransformArb<BigVector>::SetCylotomicPolynomial(cycloPoly, modulusQ);
float stdDev = 4;
usint batchSize = 8;
shared_ptr<ILParams> params(new ILParams(m, modulusQ, squareRootOfRoot, bigmodulus, bigroot));
EncodingParams encodingParams(new EncodingParamsImpl(p, batchSize, PackedEncoding::GetAutomorphismGenerator(m)));
PackedEncoding::SetParams(m, encodingParams);
CryptoContext<Poly> cc = CryptoContextFactory<Poly>::genCryptoContextBGV(params, encodingParams, 8, stdDev);
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
// Initialize the public key containers.
LPKeyPair<Poly> kp = cc->KeyGen();
Ciphertext<Poly> ciphertext;
Plaintext intArray = cc->MakePackedPlaintext(clearVector);
cc->EvalSumKeyGen(kp.secretKey);
ciphertext = cc->Encrypt(kp.publicKey, intArray);
auto ciphertextSum = cc->EvalSum(ciphertext, batchSize);
Plaintext intArrayNew;
cc->Decrypt(kp.secretKey, ciphertextSum, &intArrayNew);
return intArrayNew->GetPackedValue()[0];
}
int64_t ArbBFVEvalSumPackedArray(std::vector<int64_t> &clearVector, PlaintextModulus p) {
usint m = 22;
BigInteger modulusP(p);
BigInteger modulusQ("955263939794561");
BigInteger squareRootOfRoot("941018665059848");
BigInteger bigmodulus("80899135611688102162227204937217");
BigInteger bigroot("77936753846653065954043047918387");
auto cycloPoly = GetCyclotomicPolynomial<BigVector>(m, modulusQ);
ChineseRemainderTransformArb<BigVector>::SetCylotomicPolynomial(cycloPoly, modulusQ);
float stdDev = 4;
usint batchSize = 8;
shared_ptr<ILParams> params(new ILParams(m, modulusQ, squareRootOfRoot, bigmodulus, bigroot));
EncodingParams encodingParams(new EncodingParamsImpl(p, batchSize, PackedEncoding::GetAutomorphismGenerator(m)));
PackedEncoding::SetParams(m, encodingParams);
BigInteger delta(modulusQ.DividedBy(modulusP));
CryptoContext<Poly> cc = CryptoContextFactory<Poly>::genCryptoContextBFV(params, encodingParams, 8, stdDev, delta.ToString());
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
// Initialize the public key containers.
LPKeyPair<Poly> kp = cc->KeyGen();
Ciphertext<Poly> ciphertext;
std::vector<int64_t> vectorOfInts = std::move(clearVector);
Plaintext intArray = cc->MakePackedPlaintext(vectorOfInts);
cc->EvalSumKeyGen(kp.secretKey);
ciphertext = cc->Encrypt(kp.publicKey, intArray);
auto ciphertextSum = cc->EvalSum(ciphertext, batchSize);
Plaintext intArrayNew;
cc->Decrypt(kp.secretKey, ciphertextSum, &intArrayNew);
return intArrayNew->GetPackedValue()[0];
}
| 29.175373
| 127
| 0.775163
|
mattdano
|
3bc7d4336e9349b11efdfcd1659df26daf4d5236
| 1,250
|
cpp
|
C++
|
codeforce/528/B.cpp
|
heiseish/Competitive-Programming
|
e4dd4db83c38e8837914562bc84bc8c102e68e34
|
[
"MIT"
] | 5
|
2019-03-17T01:33:19.000Z
|
2021-06-25T09:50:45.000Z
|
codeforce/528/B.cpp
|
heiseish/Competitive-Programming
|
e4dd4db83c38e8837914562bc84bc8c102e68e34
|
[
"MIT"
] | null | null | null |
codeforce/528/B.cpp
|
heiseish/Competitive-Programming
|
e4dd4db83c38e8837914562bc84bc8c102e68e34
|
[
"MIT"
] | null | null | null |
/**
Is a reason necessary? I don't know why you would kill someone but as for saving someone…a logical mind isn\'t needed, right?
*/
#include <bits/stdc++.h>
#define forn(i, l, r) for(int i=l;i<=r;i++)
#define all(v) v.begin(),v.end()
#define pb push_back
#define nd second
#define st first
#define debug(x) cout<<#x<<" -> "<<x<< endl
#define rsa(x, y) memset(x, y, sizeof x);
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<bool> vb;
typedef vector<string> vs;
typedef vector<double> vd;
typedef vector<long long> vll;
typedef vector<vector<int> > vvi;
typedef vector<vll> vvll;
typedef vector<pair<int, int> > vpi;
typedef vector<vpi> vvpi;
typedef pair<int, int> pi;
typedef pair<ll, ll> pll;
typedef vector<pll> vpll;
const int INF = 1 << 30;
/**
Start coding from here
*/
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
int n, k;
cin >> n >> k;
vi ans;
forn(i, 1, n) {
if (n%i==0) ans.pb(i);
}
ll res = 1L * INF;
for (auto &v : ans){
ll f = 1L * k * v + n/v;
ll s = 1L * k * n / v + v;
if (f%k != 0 && (f/k) * (f%k) == n) res = min<ll>(res, f);
if (s%k != 0 && (s/k) * (s%k) == n) res = min<ll>(res, s);
}
cout << res << '\n';
return 0;
}
| 24.038462
| 133
| 0.6072
|
heiseish
|
3bcb38cb3c0d92f67dda0ea62a76f9effffdd81a
| 629
|
cpp
|
C++
|
solved-uva/195-2.cpp
|
Maruf-Tuhin/Online_Judge
|
cf9b2a522e8b1a9623d3996a632caad7fd67f751
|
[
"MIT"
] | 1
|
2019-03-31T05:47:30.000Z
|
2019-03-31T05:47:30.000Z
|
solved-uva/195-2.cpp
|
the-redback/competitive-programming
|
cf9b2a522e8b1a9623d3996a632caad7fd67f751
|
[
"MIT"
] | null | null | null |
solved-uva/195-2.cpp
|
the-redback/competitive-programming
|
cf9b2a522e8b1a9623d3996a632caad7fd67f751
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <vector>
#include <algorithm>
#include <ctype.h>
using namespace std;
#define mem(x,y) memset(x,y,sizeof(x));
char a[100];
bool comp(char b,char c)
{
if(tolower(b)==tolower(c))
return b<c; //porer ta Capital hole swap kore age jaba
else
return tolower(b)<tolower(c); //eki thakbe
}
main()
{
int l,T;
scanf("%d",&T);
getchar();
while(T--)
{
gets(a);
l=strlen(a);
sort(a,a+l,comp);
do
{
puts(a);
}while(next_permutation(a,a+l,comp));
}
return 0;
}
| 17.971429
| 65
| 0.538951
|
Maruf-Tuhin
|
3bd64421c2c9bd266fb0282fb8d7eb672a8fec24
| 6,436
|
cpp
|
C++
|
DonerComponents/source/common/component/CComponentFactoryManager.cpp
|
Donerkebap13/DonerComponents
|
2441ffcb52510783d3f4bef714461429687e7d4d
|
[
"MIT"
] | 28
|
2018-09-16T15:48:47.000Z
|
2022-01-11T01:11:16.000Z
|
DonerComponents/source/common/component/CComponentFactoryManager.cpp
|
Donerkebap13/DonerECS
|
2441ffcb52510783d3f4bef714461429687e7d4d
|
[
"MIT"
] | 6
|
2017-12-12T21:41:40.000Z
|
2018-09-16T14:15:43.000Z
|
DonerComponents/source/common/component/CComponentFactoryManager.cpp
|
Donerkebap13/DonerECS
|
2441ffcb52510783d3f4bef714461429687e7d4d
|
[
"MIT"
] | null | null | null |
////////////////////////////////////////////////////////////
//
// MIT License
//
// DonerComponents
// Copyright(c) 2017 Donerkebap13
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
////////////////////////////////////////////////////////////
#include <donercomponents/component/CComponent.h>
#include <donercomponents/component/CComponentFactoryManager.h>
#include <donercomponents/handle/CHandle.h>
#include <cassert>
namespace DonerComponents
{
CComponent* CComponentFactoryManager::CreateComponent(CStrID componentNameId)
{
IComponentFactory* factory = GetFactoryByName(componentNameId);
if (factory)
{
return factory->CreateComponent();
}
else
{
DC_ERROR_MSG(EErrorCode::ComponentFactoryNotRegistered, "There's no factory registered to create component %u", componentNameId);
return nullptr;
}
}
CComponent* CComponentFactoryManager::CloneComponent(CComponent* component, int componentIdx)
{
IComponentFactory* factory = GetFactoryByIndex(componentIdx);
if (factory)
{
return factory->CloneComponent(component);
}
else
{
DC_ERROR_MSG(EErrorCode::InvalidComponentFactoryIndex, "There's no factory registered with index %d", componentIdx);
return nullptr;
}
}
void CComponentFactoryManager::CloneComponents(std::vector<CComponent*>& src, std::vector<CComponent*>& dst)
{
assert(src.size() == dst.size());
for (std::size_t i = 0; i < src.size(); ++i)
{
dst[i] = CloneComponent(src[i], i);
}
}
CComponent* CComponentFactoryManager::AddComponent(CStrID componentNameId, std::vector<CComponent*>& components)
{
int factoryIdx = GetFactoryIndexByName(componentNameId);
if (factoryIdx >= 0)
{
IComponentFactory* factory = GetFactoryByIndex(factoryIdx);
if (factory && components[factoryIdx] == nullptr)
{
components[factoryIdx] = factory->CreateComponent();
return components[factoryIdx];
}
}
DC_ERROR_MSG(EErrorCode::ComponentFactoryNotRegistered, "There's no factory registered to create component %u", componentNameId);
return nullptr;
}
CComponent* CComponentFactoryManager::GetComponent(std::size_t componentTypeIdx, int index, int version)
{
if (componentTypeIdx < m_factories.size())
{
IComponentFactory* factory = m_factories[componentTypeIdx].m_address;
if (factory)
{
return factory->GetByIdxAndVersion(index, version);
}
}
DC_ERROR_MSG(EErrorCode::InvalidComponentFactoryIndex, "There's no factory registered with index %d", index);
return nullptr;
}
CHandle CComponentFactoryManager::SetHandleInfoFromComponent(CComponent* component)
{
CHandle handle;
for (std::size_t i = 0; i < m_factories.size(); ++i)
{
if (m_factories[i].m_address->SetHandleInfoFromComponent(component, handle))
{
handle.m_componentIdx = i;
}
}
return handle;
}
int CComponentFactoryManager::GetPositionForElement(CComponent* component)
{
for (std::size_t i = 0; i < m_factories.size(); ++i)
{
int pos = m_factories[i].m_address->GetComponentPosition(component);
if (pos >= 0)
{
return pos;
}
}
DC_ERROR_MSG(EErrorCode::ComponentNotRegisteredInFactory, "Trying to get position for component created outside a factory");
return -1;
}
bool CComponentFactoryManager::DestroyComponent(CComponent** component)
{
for (std::size_t i = 0; i < m_factories.size(); ++i)
{
if (m_factories[i].m_address->GetComponentPosition(*component) != -1)
{
(*component)->Destroy();
if (m_factories[i].m_address->DestroyComponent(*component))
{
*component = nullptr;
return true;
}
}
}
DC_ERROR_MSG(EErrorCode::ComponentNotRegisteredInFactory, "Trying to destroy component created outside a factory");
return false;
}
IComponentFactory* CComponentFactoryManager::GetFactoryByName(CStrID nameId)
{
for (SFactoryData& data : m_factories)
{
if (data.m_nameId == nameId)
{
return data.m_address;
}
}
DC_ERROR_MSG(EErrorCode::ComponentFactoryNotRegistered, "There's no factory registered with id %u", nameId);
return nullptr;
}
IComponentFactory* CComponentFactoryManager::GetFactoryByIndex(std::size_t idx)
{
if (idx < m_factories.size())
{
return m_factories[idx].m_address;
}
DC_ERROR_MSG(EErrorCode::InvalidComponentFactoryIndex, "There's no factory registered with index %u", idx);
return nullptr;
}
int CComponentFactoryManager::GetFactoryIndexByName(CStrID nameId)
{
for (std::size_t i = 0; i < m_factories.size(); ++i)
{
if (m_factories[i].m_nameId == nameId)
{
return i;
}
}
DC_ERROR_MSG(EErrorCode::ComponentFactoryNotRegistered, "There's no factory registered with id %u", nameId);
return -1;
}
void CComponentFactoryManager::Update(float dt)
{
for (SFactoryData& data : m_factories)
{
data.m_address->Update(dt);
}
}
void CComponentFactoryManager::ScheduleDestroyComponent(CComponent* component)
{
for (std::size_t i = 0; i < m_factories.size(); ++i)
{
if (m_factories[i].m_address->GetComponentPosition(component) != -1)
{
m_factories[i].m_address->ScheduleDestroyComponent(component);
return;
}
}
DC_ERROR_MSG(EErrorCode::ComponentNotRegisteredInFactory, "Trying to destroy component created outside a factory");
}
void CComponentFactoryManager::ExecuteScheduledDestroys()
{
for (SFactoryData& data : m_factories)
{
data.m_address->ExecuteScheduledDestroys();
}
}
}
| 30.215962
| 132
| 0.716128
|
Donerkebap13
|
3bd80db1f5d99bd78eeb5be9f2eb033cfe962a62
| 1,775
|
hpp
|
C++
|
doc/quickbook/oglplus/quickref/enums/texture_target_class.hpp
|
Extrunder/oglplus
|
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
|
[
"BSL-1.0"
] | null | null | null |
doc/quickbook/oglplus/quickref/enums/texture_target_class.hpp
|
Extrunder/oglplus
|
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
|
[
"BSL-1.0"
] | null | null | null |
doc/quickbook/oglplus/quickref/enums/texture_target_class.hpp
|
Extrunder/oglplus
|
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
|
[
"BSL-1.0"
] | null | null | null |
// File doc/quickbook/oglplus/quickref/enums/texture_target_class.hpp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/texture_target.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2015 Matus Chochlik.
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
//[oglplus_enums_texture_target_class
#if !__OGLPLUS_NO_ENUM_VALUE_CLASSES
namespace enums {
template <typename Base, template<__TextureTarget> class Transform>
class __EnumToClass<Base, __TextureTarget, Transform> /*<
Specialization of __EnumToClass for the __TextureTarget enumeration.
>*/
: public Base
{
public:
EnumToClass(void);
EnumToClass(Base&& base);
Transform<TextureTarget::_1D>
_1D;
Transform<TextureTarget::_2D>
_2D;
Transform<TextureTarget::_3D>
_3D;
Transform<TextureTarget::_1DArray>
_1DArray;
Transform<TextureTarget::_2DArray>
_2DArray;
Transform<TextureTarget::Rectangle>
Rectangle;
Transform<TextureTarget::Buffer>
Buffer;
Transform<TextureTarget::CubeMap>
CubeMap;
Transform<TextureTarget::CubeMapArray>
CubeMapArray;
Transform<TextureTarget::_2DMultisample>
_2DMultisample;
Transform<TextureTarget::_2DMultisampleArray>
_2DMultisampleArray;
Transform<TextureTarget::CubeMapPositiveX>
CubeMapPositiveX;
Transform<TextureTarget::CubeMapNegativeX>
CubeMapNegativeX;
Transform<TextureTarget::CubeMapPositiveY>
CubeMapPositiveY;
Transform<TextureTarget::CubeMapNegativeY>
CubeMapNegativeY;
Transform<TextureTarget::CubeMapPositiveZ>
CubeMapPositiveZ;
Transform<TextureTarget::CubeMapNegativeZ>
CubeMapNegativeZ;
};
} // namespace enums
#endif
//]
| 26.893939
| 70
| 0.790986
|
Extrunder
|
3bdb85d2c9bce9786ab8aed301a4efb591cefe85
| 16,086
|
cc
|
C++
|
src/connectivity/network/mdns/service/mdns_service_impl.cc
|
myself659/fuchsia
|
18eb5ad3d995fba458b32d8600b2af97f89a5726
|
[
"BSD-3-Clause"
] | null | null | null |
src/connectivity/network/mdns/service/mdns_service_impl.cc
|
myself659/fuchsia
|
18eb5ad3d995fba458b32d8600b2af97f89a5726
|
[
"BSD-3-Clause"
] | 4
|
2020-09-06T07:59:32.000Z
|
2022-02-12T16:06:47.000Z
|
src/connectivity/network/mdns/service/mdns_service_impl.cc
|
myself659/fuchsia
|
18eb5ad3d995fba458b32d8600b2af97f89a5726
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2017 The Fuchsia 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 "src/connectivity/network/mdns/service/mdns_service_impl.h"
#include <fuchsia/netstack/cpp/fidl.h>
#include <lib/async/cpp/task.h>
#include <lib/async/default.h>
#include <lib/sys/cpp/component_context.h>
#include <unistd.h>
#include "lib/fidl/cpp/type_converter.h"
#include "lib/fsl/types/type_converters.h"
#include "src/connectivity/network/mdns/service/mdns_fidl_util.h"
#include "src/connectivity/network/mdns/service/mdns_names.h"
#include "src/lib/fxl/logging.h"
namespace mdns {
namespace {
static const std::string kUnsetHostName = "fuchsia-unset-device-name";
static constexpr zx::duration kReadyPollingInterval = zx::sec(1);
std::string GetHostName() {
char host_name_buffer[HOST_NAME_MAX + 1];
int result = gethostname(host_name_buffer, sizeof(host_name_buffer));
std::string host_name;
if (result < 0) {
FXL_LOG(ERROR) << "gethostname failed, " << strerror(errno);
host_name = kUnsetHostName;
} else {
host_name = host_name_buffer;
}
return host_name;
}
} // namespace
MdnsServiceImpl::MdnsServiceImpl(sys::ComponentContext* component_context)
: component_context_(component_context),
resolver_bindings_(this, "Resolver"),
subscriber_bindings_(this, "Subscriber"),
publisher_bindings_(this, "Publisher") {
component_context_->outgoing()
->AddPublicService<fuchsia::net::mdns::Resolver>(fit::bind_member(
&resolver_bindings_,
&BindingSet<fuchsia::net::mdns::Resolver>::OnBindRequest));
component_context_->outgoing()
->AddPublicService<fuchsia::net::mdns::Subscriber>(fit::bind_member(
&subscriber_bindings_,
&BindingSet<fuchsia::net::mdns::Subscriber>::OnBindRequest));
component_context_->outgoing()
->AddPublicService<fuchsia::net::mdns::Publisher>(fit::bind_member(
&publisher_bindings_,
&BindingSet<fuchsia::net::mdns::Publisher>::OnBindRequest));
Start();
}
MdnsServiceImpl::~MdnsServiceImpl() {}
void MdnsServiceImpl::Start() {
std::string host_name = GetHostName();
if (host_name == kUnsetHostName) {
// Host name not set. Try again soon.
async::PostDelayedTask(
async_get_default_dispatcher(), [this]() { Start(); },
kReadyPollingInterval);
return;
}
config_.ReadConfigFiles(host_name);
if (!config_.valid()) {
FXL_LOG(FATAL) << "Invalid config file(s), terminating: "
<< config_.error();
return;
}
mdns_.Start(component_context_->svc()->Connect<fuchsia::netstack::Netstack>(),
host_name, config_.addresses(), config_.perform_host_name_probe(),
fit::bind_member(this, &MdnsServiceImpl::OnReady));
}
void MdnsServiceImpl::OnReady() {
ready_ = true;
// Publish as indicated in config files.
for (auto& publication : config_.publications()) {
PublishServiceInstance(
publication.service_, publication.instance_,
publication.publication_->Clone(), true,
[service = publication.service_](
fuchsia::net::mdns::Publisher_PublishServiceInstance_Result
result) {
if (result.is_err()) {
FXL_LOG(ERROR) << "Failed to publish as " << service << ", result "
<< static_cast<uint32_t>(result.err());
}
});
}
resolver_bindings_.OnReady();
subscriber_bindings_.OnReady();
publisher_bindings_.OnReady();
}
bool MdnsServiceImpl::PublishServiceInstance(
std::string service_name, std::string instance_name,
std::unique_ptr<Mdns::Publication> publication, bool perform_probe,
PublishServiceInstanceCallback callback) {
auto publisher = std::make_unique<SimplePublisher>(std::move(publication),
callback.share());
if (!mdns_.PublishServiceInstance(service_name, instance_name, perform_probe,
publisher.get())) {
return false;
}
std::string instance_full_name =
MdnsNames::LocalInstanceFullName(instance_name, service_name);
// |Mdns| told us our instance is unique locally, so the full name should
// not appear in our collection.
FXL_DCHECK(publishers_by_instance_full_name_.find(instance_full_name) ==
publishers_by_instance_full_name_.end());
publishers_by_instance_full_name_.emplace(instance_full_name,
std::move(publisher));
return true;
}
void MdnsServiceImpl::ResolveHostName(std::string host, int64_t timeout_ns,
ResolveHostNameCallback callback) {
if (!MdnsNames::IsValidHostName(host)) {
FXL_LOG(ERROR) << "ResolveHostName called with invalid host name " << host;
callback(nullptr, nullptr);
return;
}
mdns_.ResolveHostName(
host, fxl::TimePoint::Now() + fxl::TimeDelta::FromNanoseconds(timeout_ns),
[callback = std::move(callback)](
const std::string& host, const inet::IpAddress& v4_address,
const inet::IpAddress& v6_address) {
callback(v4_address ? std::make_unique<fuchsia::net::Ipv4Address>(
MdnsFidlUtil::CreateIpv4Address(v4_address))
: nullptr,
v6_address ? std::make_unique<fuchsia::net::Ipv6Address>(
MdnsFidlUtil::CreateIpv6Address(v6_address))
: nullptr);
});
}
void MdnsServiceImpl::SubscribeToService(
std::string service,
fidl::InterfaceHandle<fuchsia::net::mdns::ServiceSubscriber>
subscriber_handle) {
if (!MdnsNames::IsValidServiceName(service)) {
FXL_LOG(ERROR) << "ResolveHostName called with invalid service name "
<< service;
return;
}
size_t id = next_subscriber_id_++;
auto subscriber = std::make_unique<Subscriber>(
std::move(subscriber_handle),
[this, id]() { subscribers_by_id_.erase(id); });
mdns_.SubscribeToService(service, subscriber.get());
subscribers_by_id_.emplace(id, std::move(subscriber));
}
void MdnsServiceImpl::PublishServiceInstance(
std::string service, std::string instance, bool perform_probe,
fidl::InterfaceHandle<fuchsia::net::mdns::PublicationResponder>
responder_handle,
PublishServiceInstanceCallback callback) {
FXL_DCHECK(responder_handle);
if (!MdnsNames::IsValidServiceName(service)) {
FXL_LOG(ERROR) << "PublishServiceInstance called with invalid service name "
<< service;
fuchsia::net::mdns::Publisher_PublishServiceInstance_Result result;
result.set_err(fuchsia::net::mdns::Error::INVALID_SERVICE_NAME);
callback(std::move(result));
return;
}
if (!MdnsNames::IsValidInstanceName(instance)) {
FXL_LOG(ERROR)
<< "PublishServiceInstance called with invalid instance name "
<< instance;
fuchsia::net::mdns::Publisher_PublishServiceInstance_Result result;
result.set_err(fuchsia::net::mdns::Error::INVALID_INSTANCE_NAME);
callback(std::move(result));
return;
}
auto responder_ptr = responder_handle.Bind();
FXL_DCHECK(responder_ptr);
std::string instance_full_name =
MdnsNames::LocalInstanceFullName(instance, service);
auto publisher = std::make_unique<ResponderPublisher>(
std::move(responder_ptr), std::move(callback),
[this, instance_full_name]() {
publishers_by_instance_full_name_.erase(instance_full_name);
});
if (!mdns_.PublishServiceInstance(service, instance, perform_probe,
publisher.get())) {
fuchsia::net::mdns::Publisher_PublishServiceInstance_Result result;
result.set_err(fuchsia::net::mdns::Error::ALREADY_PUBLISHED_LOCALLY);
callback(std::move(result));
return;
}
// |Mdns| told us our instance is unique locally, so the full name should
// not appear in our collection.
FXL_DCHECK(publishers_by_instance_full_name_.find(instance_full_name) ==
publishers_by_instance_full_name_.end());
publishers_by_instance_full_name_.emplace(instance_full_name,
std::move(publisher));
}
////////////////////////////////////////////////////////////////////////////////
// MdnsServiceImpl::Subscriber implementation
MdnsServiceImpl::Subscriber::Subscriber(
fidl::InterfaceHandle<fuchsia::net::mdns::ServiceSubscriber> handle,
fit::closure deleter) {
client_.Bind(std::move(handle));
client_.set_error_handler(
[this, deleter = std::move(deleter)](zx_status_t status) {
client_.set_error_handler(nullptr);
client_.Unbind();
deleter();
});
}
MdnsServiceImpl::Subscriber::~Subscriber() {}
void MdnsServiceImpl::Subscriber::InstanceDiscovered(
const std::string& service, const std::string& instance,
const inet::SocketAddress& v4_address,
const inet::SocketAddress& v6_address, const std::vector<std::string>& text,
uint16_t srv_priority, uint16_t srv_weight) {
Entry entry{.type = EntryType::kInstanceDiscovered,
.service_instance = fuchsia::net::mdns::ServiceInstance{
.service = service,
.instance = instance,
.text = fidl::VectorPtr<std::string>(text),
.srv_priority = srv_priority,
.srv_weight = srv_weight}};
if (v4_address) {
entry.service_instance.endpoints.push_back(
MdnsFidlUtil::CreateEndpointV4(v4_address));
}
if (v6_address) {
entry.service_instance.endpoints.push_back(
MdnsFidlUtil::CreateEndpointV6(v6_address));
}
entries_.push(std::move(entry));
MaybeSendNextEntry();
}
void MdnsServiceImpl::Subscriber::InstanceChanged(
const std::string& service, const std::string& instance,
const inet::SocketAddress& v4_address,
const inet::SocketAddress& v6_address, const std::vector<std::string>& text,
uint16_t srv_priority, uint16_t srv_weight) {
Entry entry{.type = EntryType::kInstanceChanged,
.service_instance = fuchsia::net::mdns::ServiceInstance{
.service = service,
.instance = instance,
.text = fidl::VectorPtr<std::string>(text),
.srv_priority = srv_priority,
.srv_weight = srv_weight}};
if (v4_address) {
entry.service_instance.endpoints.push_back(
MdnsFidlUtil::CreateEndpointV4(v4_address));
}
if (v6_address) {
entry.service_instance.endpoints.push_back(
MdnsFidlUtil::CreateEndpointV6(v6_address));
}
entries_.push(std::move(entry));
MaybeSendNextEntry();
}
void MdnsServiceImpl::Subscriber::InstanceLost(const std::string& service,
const std::string& instance) {
entries_.push({.type = EntryType::kInstanceLost,
.service_instance = fuchsia::net::mdns::ServiceInstance{
.service = service, .instance = instance}});
MaybeSendNextEntry();
}
void MdnsServiceImpl::Subscriber::MaybeSendNextEntry() {
FXL_DCHECK(pipeline_depth_ <= kMaxPipelineDepth);
if (pipeline_depth_ == kMaxPipelineDepth || entries_.empty()) {
return;
}
Entry& entry = entries_.front();
auto on_reply =
fit::bind_member(this, &MdnsServiceImpl::Subscriber::ReplyReceived);
switch (entry.type) {
case EntryType::kInstanceDiscovered:
client_->OnInstanceDiscovered(std::move(entry.service_instance),
std::move(on_reply));
break;
case EntryType::kInstanceChanged:
client_->OnInstanceChanged(std::move(entry.service_instance),
std::move(on_reply));
break;
case EntryType::kInstanceLost:
client_->OnInstanceLost(entry.service_instance.service,
entry.service_instance.instance,
std::move(on_reply));
break;
}
++pipeline_depth_;
entries_.pop();
}
void MdnsServiceImpl::Subscriber::ReplyReceived() {
FXL_DCHECK(pipeline_depth_ != 0);
--pipeline_depth_;
MaybeSendNextEntry();
}
////////////////////////////////////////////////////////////////////////////////
// MdnsServiceImpl::SimplePublisher implementation
MdnsServiceImpl::SimplePublisher::SimplePublisher(
std::unique_ptr<Mdns::Publication> publication,
PublishServiceInstanceCallback callback)
: publication_(std::move(publication)), callback_(std::move(callback)) {}
void MdnsServiceImpl::SimplePublisher::ReportSuccess(bool success) {
fuchsia::net::mdns::Publisher_PublishServiceInstance_Result result;
if (success) {
result.set_response(
fuchsia::net::mdns::Publisher_PublishServiceInstance_Response());
} else {
result.set_err(fuchsia::net::mdns::Error::ALREADY_PUBLISHED_ON_SUBNET);
}
callback_(std::move(result));
}
void MdnsServiceImpl::SimplePublisher::GetPublication(
bool query, const std::string& subtype,
fit::function<void(std::unique_ptr<Mdns::Publication>)> callback) {
FXL_DCHECK(subtype.empty() || MdnsNames::IsValidSubtypeName(subtype));
callback(publication_->Clone());
}
////////////////////////////////////////////////////////////////////////////////
// MdnsServiceImpl::ResponderPublisher implementation
MdnsServiceImpl::ResponderPublisher::ResponderPublisher(
fuchsia::net::mdns::PublicationResponderPtr responder,
PublishServiceInstanceCallback callback, fit::closure deleter)
: responder_(std::move(responder)), callback_(std::move(callback)) {
FXL_DCHECK(responder_);
responder_.set_error_handler(
[this, deleter = std::move(deleter)](zx_status_t status) {
responder_.set_error_handler(nullptr);
deleter();
});
responder_.events().SetSubtypes = [this](std::vector<std::string> subtypes) {
for (auto& subtype : subtypes) {
if (!MdnsNames::IsValidSubtypeName(subtype)) {
FXL_LOG(ERROR) << "Invalid subtype " << subtype
<< " passed in SetSubtypes event, closing connection.";
responder_ = nullptr;
Unpublish();
return;
}
}
SetSubtypes(std::move(subtypes));
};
responder_.events().Reannounce = [this]() { Reannounce(); };
}
void MdnsServiceImpl::ResponderPublisher::ReportSuccess(bool success) {
fuchsia::net::mdns::Publisher_PublishServiceInstance_Result result;
if (success) {
result.set_response(
fuchsia::net::mdns::Publisher_PublishServiceInstance_Response());
} else {
result.set_err(fuchsia::net::mdns::Error::ALREADY_PUBLISHED_ON_SUBNET);
}
callback_(std::move(result));
}
void MdnsServiceImpl::ResponderPublisher::GetPublication(
bool query, const std::string& subtype,
fit::function<void(std::unique_ptr<Mdns::Publication>)> callback) {
FXL_DCHECK(subtype.empty() || MdnsNames::IsValidSubtypeName(subtype));
FXL_DCHECK(responder_);
responder_->OnPublication(
query, subtype,
[this, callback = std::move(callback)](
fuchsia::net::mdns::PublicationPtr publication_ptr) {
if (publication_ptr) {
for (auto& text : publication_ptr->text) {
if (!MdnsNames::IsValidTextString(text)) {
FXL_LOG(ERROR) << "Invalid text string returned by "
"Responder.GetPublication, closing connection.";
responder_ = nullptr;
Unpublish();
return;
}
}
if (publication_ptr->ptr_ttl < ZX_SEC(1) ||
publication_ptr->srv_ttl < ZX_SEC(1) ||
publication_ptr->txt_ttl < ZX_SEC(1)) {
FXL_LOG(ERROR) << "TTL less than one second returned by "
"Responder.GetPublication, closing connection.";
responder_ = nullptr;
Unpublish();
return;
}
}
callback(MdnsFidlUtil::Convert(publication_ptr));
});
}
} // namespace mdns
| 35.431718
| 80
| 0.654793
|
myself659
|
3bdbcd10fd1ed8b0a58f9d20b4757d028ed8572f
| 7,136
|
hh
|
C++
|
include/tchecker/utils/cache.hh
|
arnabSur/tchecker
|
24ba7703068a41c6e9c613b4ef80ad6c788e65bc
|
[
"MIT"
] | 7
|
2019-08-12T12:22:07.000Z
|
2021-11-18T01:48:27.000Z
|
include/tchecker/utils/cache.hh
|
arnabSur/tchecker
|
24ba7703068a41c6e9c613b4ef80ad6c788e65bc
|
[
"MIT"
] | 40
|
2019-07-03T04:31:19.000Z
|
2022-03-31T03:40:43.000Z
|
include/tchecker/utils/cache.hh
|
arnabSur/tchecker
|
24ba7703068a41c6e9c613b4ef80ad6c788e65bc
|
[
"MIT"
] | 8
|
2019-07-04T06:40:49.000Z
|
2021-12-03T15:51:50.000Z
|
/*
* This file is a part of the TChecker project.
*
* See files AUTHORS and LICENSE for copyright details.
*
*/
#ifndef TCHECKER_CACHE_HH
#define TCHECKER_CACHE_HH
/*!
\file cache.hh
\brief Cache of shared objects
*/
#include <vector>
#include "tchecker/utils/shared_objects.hh"
#include "tchecker/utils/spinlock.hh"
namespace tchecker {
namespace details {
/*!
\class thread_safe_collection_t
\brief Collection of shared objects with thread-safe access
\param T : type of object, should be tchecker::make_shared_t<>
\param EQUAL : equality predicate on T values, should be default constructible
*/
template <class T, class EQUAL> class thread_safe_collection_t {
public:
/*!
\brief Constructor
*/
thread_safe_collection_t() = default;
/*!
\brief Copy-construction (deleted)
*/
thread_safe_collection_t(tchecker::details::thread_safe_collection_t<T, EQUAL> const &) = delete;
/*!
\brief Move-construction (deleted)
*/
thread_safe_collection_t(tchecker::details::thread_safe_collection_t<T, EQUAL> &&) = delete;
/*!
\brief Destructor
*/
~thread_safe_collection_t() = default;
/*!
\brief Assignment operator (deleted)
*/
tchecker::details::thread_safe_collection_t<T, EQUAL> &
operator=(tchecker::details::thread_safe_collection_t<T, EQUAL> const &) = delete;
/*!
\brief Move-assignment operator (deleted)
*/
tchecker::details::thread_safe_collection_t<T, EQUAL> &
operator=(tchecker::details::thread_safe_collection_t<T, EQUAL> &&) = delete;
/*!
\brief Object caching
\param t : object
\return The object equal to t in this collection, which is t itself if no objec equal to t is already in the collection
\post If no object equal to t was in the collection, t has been inserted into the collection
\note Compelxity is linear in the size of the collection
*/
tchecker::intrusive_shared_ptr_t<T> find_else_insert(tchecker::intrusive_shared_ptr_t<T> const & t)
{
_lock.lock();
for (tchecker::intrusive_shared_ptr_t<T> const & u : _values)
if (_equal(*t, *u)) {
tchecker::intrusive_shared_ptr_t<T> uu(u); // ensures at least 2 references to the object
_lock.unlock();
return uu;
}
_values.push_back(t);
_lock.unlock();
return t;
}
/*!
\brief Membership predicate
\param t : object
\return true if the collection contains an object equal to t, false otherwise
\note Complexity is linear in the size of the collection
*/
bool find(tchecker::intrusive_shared_ptr_t<T> const & t)
{
_lock.lock();
for (tchecker::intrusive_shared_ptr_t<T> const & u : _values)
if (_equal(*t, *u)) {
_lock.unlock();
return true;
}
_lock.unlock();
return false;
}
/*!
\brief Clear
\post The collection is empty
*/
void clear()
{
_lock.lock();
_values.clear();
_lock.unlock();
}
/*!
\brief Garbage collection
\post All objects with reference counter 1 (i.e. objects that are only referenced by this collection) have been
removed from this collection
*/
void collect()
{
_lock.lock();
for (std::size_t i = 0; i < _values.size();) {
if (_values[i]->refcount() == 1) {
_values[i] = _values.back();
_values.pop_back();
}
else
++i;
}
_lock.unlock();
}
/*!
\brief Accessor
\return Number of objects in the collection
*/
std::size_t size() const
{
_lock.lock();
std::size_t size = _values.size();
_lock.unlock();
return size;
}
private:
std::vector<tchecker::intrusive_shared_ptr_t<T>> _values; /*!< Collection */
mutable tchecker::spinlock_t _lock; /*!< Lock for thread-safe access */
EQUAL _equal; /*!< Equality predicate on T values */
};
} // end of namespace details
/*!
\class cache_t
\brief Cache of shared objects
\param T : type of objects, should be tchecker::make_shared_t<>
\param HASH : type of hash function on T, should be default constructible
\param EQUAL : type of equality predicate on T, should be default constructible
*/
template <class T, class HASH, class EQUAL> class cache_t {
public:
/*!
\brief Constructor
\param table_size : size of the hash table
\note The size of the hash table is fixed. The hash table maps hash codes to collection of objects.
*/
cache_t(std::size_t table_size = 65536) : _table_size(table_size)
{
_table = new tchecker::details::thread_safe_collection_t<T, EQUAL>[_table_size];
}
/*!
\brief Copy-construction (deleted)
*/
cache_t(tchecker::cache_t<T, HASH, EQUAL> const &) = delete;
/*!
\brief Move-construction (deleted)
*/
cache_t(tchecker::cache_t<T, HASH, EQUAL> &&) = delete;
/*!
\brief Destructor
*/
~cache_t()
{
clear();
delete[] _table;
}
/*!
\brief Assignment operator (deleted)
*/
tchecker::cache_t<T, HASH, EQUAL> & operator=(tchecker::cache_t<T, HASH, EQUAL> const &) = delete;
/*!
\brief Move-assignment operator (deleted)
*/
tchecker::cache_t<T, HASH, EQUAL> & operator=(tchecker::cache_t<T, HASH, EQUAL> &&) = delete;
/*!
\brief Object caching
\param t : object
\return object equivalent to t (w.r.t. HASH and EQUAL) in this cache, t itself if no equivalent object was in the cache
before \post t has been inserted in the cache if no equivalent object (w.r.t. HASH and EQUAL) was in the cache before
*/
tchecker::intrusive_shared_ptr_t<T> find_else_insert(tchecker::intrusive_shared_ptr_t<T> const & t)
{
std::size_t i = _hash(*t) % _table_size;
return _table[i].find_else_insert(t);
}
/*!
\brief Membership predicate
\param t : object
\return true if this cache constains an object equivalent to t (w.r.t. HASH and EQUAL), false otherwise
*/
bool find(tchecker::intrusive_shared_ptr_t<T> const & t)
{
std::size_t i = _hash(*t) % _table_size;
return _table[i].find(t);
}
/*!
\brief Clear
\post The cache is empty
*/
void clear()
{
for (std::size_t i = 0; i < _table_size; ++i)
_table[i].clear();
}
/*!
\brief Garbage collection
\post All objects with reference counter 1 (i.e. objects with no reference outisde of the cache) have been removed from the
cache
*/
void collect()
{
for (std::size_t i = 0; i < _table_size; ++i)
_table[i].collect();
}
/*!
\brief Accessor
\return Number of objects in the cache
\note Complexity linear in the size of the hash table
*/
std::size_t size() const
{
std::size_t size = 0;
for (std::size_t i = 0; i < _table_size; ++i)
size += _table[i].size();
return size;
}
private:
std::size_t _table_size; /*!< Number of collections in the map */
tchecker::details::thread_safe_collection_t<T, EQUAL> * _table; /*!< Map : hash code -> objects collection */
HASH _hash; /*!< Hash function on T values */
};
} // end of namespace tchecker
#endif // TCHECKER_CACHE_HH
| 26.626866
| 126
| 0.64546
|
arnabSur
|
3be158e5924d5b71f8ccd504d0b5a56b48a66e3f
| 1,348
|
cpp
|
C++
|
vnext/Microsoft.ReactNative/ReactHost/JSExceptionCallbackFactory.cpp
|
enm10k/react-native-windows
|
feb180024d814472295f049351ef72aaa1e1682b
|
[
"MIT"
] | 1
|
2020-02-17T11:33:03.000Z
|
2020-02-17T11:33:03.000Z
|
vnext/Microsoft.ReactNative/ReactHost/JSExceptionCallbackFactory.cpp
|
enm10k/react-native-windows
|
feb180024d814472295f049351ef72aaa1e1682b
|
[
"MIT"
] | null | null | null |
vnext/Microsoft.ReactNative/ReactHost/JSExceptionCallbackFactory.cpp
|
enm10k/react-native-windows
|
feb180024d814472295f049351ef72aaa1e1682b
|
[
"MIT"
] | null | null | null |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "pch.h"
#include "JSExceptionCallbackFactory.h"
namespace Mso::React {
std::function<void(facebook::react::JSExceptionInfo &&)> CreateExceptionCallback(
OnJSExceptionCallback &&jsExceptionCallback) noexcept {
return [exceptionCallback = std::move(jsExceptionCallback)](
facebook::react::JSExceptionInfo && jsExceptionInfo) noexcept {
Mso::React::JSExceptionInfo exceptionInfo;
exceptionInfo.Callstack = std::move(jsExceptionInfo.callstack);
exceptionInfo.ExceptionId = jsExceptionInfo.exceptionId;
exceptionInfo.ExceptionMessage = std::move(jsExceptionInfo.exceptionMessage);
static_assert(
static_cast<int32_t>(facebook::react::JSExceptionType::Fatal) ==
static_cast<int32_t>(Mso::React::JSExceptionType::Fatal),
"Exception type enums don't match");
static_assert(
static_cast<int32_t>(facebook::react::JSExceptionType::Soft) ==
static_cast<int32_t>(Mso::React::JSExceptionType::Soft),
"Exception type enums don't match");
exceptionInfo.ExceptionType = static_cast<Mso::React::JSExceptionType>(jsExceptionInfo.exceptionType);
exceptionCallback(std::move(exceptionInfo));
};
}
} // namespace Mso::React
| 40.848485
| 107
| 0.718843
|
enm10k
|
3be17e4c88a5f7e3e96d83ff1304fd7722e85c3a
| 1,746
|
cpp
|
C++
|
systems/plants/collision/test/BodyTest.cpp
|
andybarry/drake
|
61428cff8cb523314cd87105821148519460a0b9
|
[
"BSD-3-Clause"
] | 1
|
2020-01-12T14:32:29.000Z
|
2020-01-12T14:32:29.000Z
|
systems/plants/collision/test/BodyTest.cpp
|
cmmccann/drake
|
0a124c044357d5a29ec7e536acb747cfa5682eba
|
[
"BSD-3-Clause"
] | null | null | null |
systems/plants/collision/test/BodyTest.cpp
|
cmmccann/drake
|
0a124c044357d5a29ec7e536acb747cfa5682eba
|
[
"BSD-3-Clause"
] | 1
|
2021-07-07T18:52:51.000Z
|
2021-07-07T18:52:51.000Z
|
#define BOOST_TEST_MODULE Body test
#include <boost/test/unit_test.hpp>
#include <iostream>
#include "DrakeCollision.h"
#include "BulletModel.h"
using namespace DrakeCollision;
using namespace std;
BOOST_AUTO_TEST_CASE(constructor_test)
{
Body body1;
BOOST_CHECK_EQUAL(body1.getBodyIdx(), -1);
BOOST_CHECK_EQUAL(body1.getParentIdx(), -1);
BOOST_CHECK_EQUAL(body1.getGroup(), DEFAULT_GROUP);
BOOST_CHECK_EQUAL(body1.getMask(), ALL_MASK);
}
BOOST_AUTO_TEST_CASE(setGroup_test)
{
Body body1;
bitmask group; group.set(7);
body1.setGroup(group);
BOOST_CHECK_EQUAL(body1.getGroup(), group);
}
BOOST_AUTO_TEST_CASE(addToGroup_test)
{
Body body1;
bitmask group; group.set(7);
body1.addToGroup(group);
BOOST_CHECK( (body1.getGroup() & group) != 0 );
}
BOOST_AUTO_TEST_CASE(ignoreGroup_test)
{
Body body1;
bitmask group; group.set(7);
body1.ignoreGroup(group);
BOOST_CHECK( (body1.getMask() & group) == 0 );
}
BOOST_AUTO_TEST_CASE(collidesWith_test)
{
Body body1;
Body body2;
body1.setBodyIdx(0);
body2.setBodyIdx(1);
BOOST_REQUIRE_MESSAGE( body1.collidesWith(body2),
"Default constructed objects should collide");
body1.ignoreGroup(body2.getGroup());
BOOST_CHECK_MESSAGE( !body1.collidesWith(body2),
"Bodies should not collide with bodies in ignored groups");
BOOST_CHECK_EQUAL( body2.collidesWith(body1), body1.collidesWith(body2) );
}
BOOST_AUTO_TEST_CASE(collideWithGroup_test)
{
Body body1;
Body body2;
body1.setBodyIdx(0);
body2.setBodyIdx(1);
body1.ignoreGroup(body2.getGroup());
body1.collideWithGroup(body2.getGroup());
BOOST_CHECK_MESSAGE( body1.collidesWith(body2),
"Body 1 should collide with body2");
}
| 24.942857
| 81
| 0.726231
|
andybarry
|
3be468a93dab86da2b32f995984ed9554910cfa2
| 675
|
hpp
|
C++
|
forward_iterator/bst_node.hpp
|
SimplyCpp/exemplos
|
139cd3c7af6885d0f4be45b0049e0f714bce3468
|
[
"MIT"
] | 6
|
2015-05-19T06:30:06.000Z
|
2018-07-24T08:15:45.000Z
|
forward_iterator/bst_node.hpp
|
SimplyCpp/exemplos
|
139cd3c7af6885d0f4be45b0049e0f714bce3468
|
[
"MIT"
] | 1
|
2015-05-19T06:42:38.000Z
|
2015-05-19T14:45:49.000Z
|
forward_iterator/bst_node.hpp
|
SimplyCpp/exemplos
|
139cd3c7af6885d0f4be45b0049e0f714bce3468
|
[
"MIT"
] | 3
|
2015-10-09T05:54:58.000Z
|
2018-07-25T13:52:32.000Z
|
//Sample provided by Fabio Galuppo
//February 2017
//http://www.simplycpp.com
#ifndef BST_NODE_HPP
#define BST_NODE_HPP
template<typename T>
struct bst_node
{
explicit bst_node(const T& value) :
value(value),
left(nullptr),
right(nullptr) {}
T value;
bst_node<T>* left;
bst_node<T>* right;
bool operator==(const T& val) const
{
return value == val;
}
bool operator!=(const T& val) const
{
return value != val;
}
bool operator==(const bst_node<T>& that) const
{
return value == that.value && left == that.left && right == that.left;
}
bool operator!=(const bst_node<T>& that) const
{
return !(*this == that);
}
};
#endif /* BST_NODE_HPP */
| 16.875
| 72
| 0.659259
|
SimplyCpp
|
3be7cf21fab8457c4391e171518be65dbf5e926f
| 479
|
cpp
|
C++
|
codeforces/431A.cpp
|
sgrade/cpptest
|
84ade6ec03ea394d4a4489c7559d12b4799c0b62
|
[
"MIT"
] | null | null | null |
codeforces/431A.cpp
|
sgrade/cpptest
|
84ade6ec03ea394d4a4489c7559d12b4799c0b62
|
[
"MIT"
] | null | null | null |
codeforces/431A.cpp
|
sgrade/cpptest
|
84ade6ec03ea394d4a4489c7559d12b4799c0b62
|
[
"MIT"
] | null | null | null |
// A. Black Square
#include <iostream>
#include <string>
using namespace std;
int main(){
int a1, a2, a3, a4;
scanf("%d %d %d %d\n", &a1, &a2, &a3, &a4);
int arr[4] = {a1, a2, a3, a4};
string s;
getline (cin, s);
int cal = 0;
for (unsigned i=0; i < s.size(); ++i){
// In ASCII numbers start from 48
// Additional "-1" because arr indexes start from 0
int aIndex = (int)s[i] - 48 - 1;
cal += arr [ aIndex ];
}
printf("%d\n", cal);
return 0;
}
| 14.96875
| 53
| 0.549061
|
sgrade
|
3be899fd83f975eebeac2a6fcb9457266f2efed9
| 44,393
|
cpp
|
C++
|
automated-tests/src/dali-toolkit-internal/utc-Dali-Text-MultiLanguage.cpp
|
pwisbey/dali-toolkit
|
aeb2a95e6cb48788c99d0338dd9788c402ebde07
|
[
"Apache-2.0"
] | null | null | null |
automated-tests/src/dali-toolkit-internal/utc-Dali-Text-MultiLanguage.cpp
|
pwisbey/dali-toolkit
|
aeb2a95e6cb48788c99d0338dd9788c402ebde07
|
[
"Apache-2.0"
] | null | null | null |
automated-tests/src/dali-toolkit-internal/utc-Dali-Text-MultiLanguage.cpp
|
pwisbey/dali-toolkit
|
aeb2a95e6cb48788c99d0338dd9788c402ebde07
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2015 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <dali/devel-api/text-abstraction/font-client.h>
#include <dali-toolkit/internal/text/character-set-conversion.h>
#include <dali-toolkit/internal/text/logical-model-impl.h>
#include <dali-toolkit/internal/text/multi-language-helper-functions.h>
#include <dali-toolkit/internal/text/multi-language-support.h>
#include <dali-toolkit/internal/text/segmentation.h>
#include <dali-toolkit/internal/text/text-run-container.h>
#include <dali-toolkit-test-suite-utils.h>
#include <dali-toolkit/dali-toolkit.h>
using namespace Dali;
using namespace Toolkit;
using namespace Text;
// Tests the following functions with different scripts.
//
// void MergeFontDescriptions( const Vector<FontDescriptionRun>& fontDescriptions,
// const TextAbstraction::FontDescription& defaultFontDescription,
// TextAbstraction::PointSize26Dot6 defaultPointSize,
// CharacterIndex characterIndex,
// TextAbstraction::FontDescription& fontDescription,
// TextAbstraction::PointSize26Dot6& fontPointSize,
// bool& isDefaultFont );
//
// Script GetScript( Length index,
// Vector<ScriptRun>::ConstIterator& scriptRunIt,
// const Vector<ScriptRun>::ConstIterator& scriptRunEndIt );
//
// Constructor, destructor and MultilanguageSupport::Get()
//
// void MultilanguageSupport::SetScripts( const Vector<Character>& text,
// CharacterIndex startIndex,
// Length numberOfCharacters,
// Vector<ScriptRun>& scripts );
//
// void MultilanguageSupport::ValidateFonts( const Vector<Character>& text,
// const Vector<ScriptRun>& scripts,
// const Vector<FontDescriptionRun>& fontDescriptions,
// const TextAbstraction::FontDescription& defaultFontDescription,
// TextAbstraction::PointSize26Dot6 defaultFontPointSize,
// CharacterIndex startIndex,
// Length numberOfCharacters,
// Vector<FontRun>& fonts );
//////////////////////////////////////////////////////////
namespace
{
const std::string DEFAULT_FONT_DIR( "/resources/fonts" );
const unsigned int EMOJI_FONT_SIZE = 3968u;
const unsigned int NON_DEFAULT_FONT_SIZE = 40u;
struct MergeFontDescriptionsData
{
std::string description; ///< Description of the experiment.
Vector<FontDescriptionRun> fontDescriptionRuns; ///< The font description runs.
TextAbstraction::FontDescription defaultFontDescription; ///< The default font description.
TextAbstraction::PointSize26Dot6 defaultPointSize; ///< The default point size.
unsigned int startIndex; ///< The start index.
unsigned int numberOfCharacters; ///< The number of characters.
Vector<FontId> expectedFontIds; ///< The expected font ids.
Vector<bool> expectedIsDefault; ///< The expected font ids.
};
struct ScriptsData
{
std::string description; ///< Description of the experiment.
std::string text; ///< Input text.
unsigned int index; ///< The index of the first character to update the script.
unsigned int numberOfCharacters; ///< The numbers of characters to update the script.
Vector<ScriptRun> scriptRuns; ///< Expected script runs.
};
struct ValidateFontsData
{
std::string description; ///< Description of the experiment.
std::string text; ///< Input text.
std::string defaultFont; ///< The default font.
unsigned int defaultFontSize; ///< The default font size.
unsigned int index; ///< The index of the first character to update the script.
unsigned int numberOfCharacters; ///< The numbers of characters to update the script.
Vector<FontDescriptionRun> fontDescriptionRuns; ///< The font description runs.
Vector<FontRun> fontRuns; ///< The expected font runs.
};
//////////////////////////////////////////////////////////
void PrintFontDescription( FontId id )
{
TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
TextAbstraction::FontDescription description;
fontClient.GetDescription( id, description );
const TextAbstraction::PointSize26Dot6 pointSize = fontClient.GetPointSize( id );
std::cout << std::endl << " font description for font id : " << id << std::endl;
std::cout << " font family : [" << description.family << "]" << std::endl;
std::cout << " font width : [" << TextAbstraction::FontWidth::Name[description.width] << "]" << std::endl;
std::cout << " font weight : [" << TextAbstraction::FontWeight::Name[description.weight] << "]" << std::endl;
std::cout << " font slant : [" << TextAbstraction::FontSlant::Name[description.slant] << "]" << std::endl;
std::cout << " font size : " << pointSize << std::endl;
}
bool MergeFontDescriptionsTest( const MergeFontDescriptionsData& data )
{
TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
Vector<FontId> fontIds;
fontIds.Resize( data.startIndex + data.numberOfCharacters, 0u );
Vector<bool> isDefaultFont;
isDefaultFont.Resize( data.startIndex + data.numberOfCharacters, true );
for( unsigned int index = data.startIndex; index < data.startIndex + data.numberOfCharacters; ++index )
{
TextAbstraction::FontDescription fontDescription;
TextAbstraction::PointSize26Dot6 fontPointSize = TextAbstraction::FontClient::DEFAULT_POINT_SIZE;
MergeFontDescriptions( data.fontDescriptionRuns,
data.defaultFontDescription,
data.defaultPointSize,
index,
fontDescription,
fontPointSize,
isDefaultFont[index] );
if( !isDefaultFont[index] )
{
fontIds[index] = fontClient.GetFontId( fontDescription, fontPointSize );
}
}
if( fontIds.Count() != data.expectedFontIds.Count() )
{
std::cout << data.description << " Different number of font ids : " << fontIds.Count() << ", expected : " << data.expectedFontIds.Count() << std::endl;
return false;
}
for( unsigned int index = 0u; index < fontIds.Count(); ++index )
{
if( fontIds[index] != data.expectedFontIds[index] )
{
std::cout << data.description << " Different font id at index : " << index << ", font id : " << fontIds[index] << ", expected : " << data.expectedFontIds[index] << std::endl;
std::cout << " font ids : ";
for( unsigned int i=0;i<fontIds.Count();++i)
{
std::cout << fontIds[i] << " ";
}
std::cout << std::endl;
std::cout << " expected font ids : ";
for( unsigned int i=0;i<data.expectedFontIds.Count();++i)
{
std::cout << data.expectedFontIds[i] << " ";
}
std::cout << std::endl;
return false;
}
if( isDefaultFont[index] != data.expectedIsDefault[index] )
{
std::cout << data.description << " Different 'is font default' at index : " << index << ", is font default : " << isDefaultFont[index] << ", expected : " << data.expectedIsDefault[index] << std::endl;
return false;
}
}
return true;
}
bool ScriptsTest( const ScriptsData& data )
{
MultilanguageSupport multilanguageSupport = MultilanguageSupport::Get();
// 1) Convert to utf32
Vector<Character> utf32;
utf32.Resize( data.text.size() );
const uint32_t numberOfCharacters = Utf8ToUtf32( reinterpret_cast<const uint8_t* const>( data.text.c_str() ),
data.text.size(),
&utf32[0u] );
utf32.Resize( numberOfCharacters );
// 2) Set the script info.
Vector<ScriptRun> scripts;
multilanguageSupport.SetScripts( utf32,
0u,
numberOfCharacters,
scripts );
if( ( 0u != data.index ) ||
( numberOfCharacters != data.numberOfCharacters ) )
{
// 3) Clear the scripts.
ClearCharacterRuns( data.index,
data.index + data.numberOfCharacters - 1u,
scripts );
multilanguageSupport.SetScripts( utf32,
data.index,
data.numberOfCharacters,
scripts );
}
// 4) Compare the results.
tet_printf( "Testing %s\n", data.description.c_str() );
if( scripts.Count() != data.scriptRuns.Count() )
{
tet_printf("ScriptsTest FAIL: different number of scripts. %d, should be %d\n", scripts.Count(), data.scriptRuns.Count() );
for( Vector<ScriptRun>::ConstIterator it = scripts.Begin(); it != scripts.End(); ++it)
{
const ScriptRun& run = *it;
std::cout << " index : " << run.characterRun.characterIndex << ", num chars : " << run.characterRun.numberOfCharacters << ", script : [" << TextAbstraction::ScriptName[run.script] << "]" << std::endl;
}
return false;
}
for( unsigned int index = 0u; index < scripts.Count(); ++index )
{
const ScriptRun& scriptRun1 = scripts[index];
const ScriptRun& scriptRun2 = data.scriptRuns[index];
if( scriptRun1.characterRun.characterIndex != scriptRun2.characterRun.characterIndex )
{
tet_printf("ScriptsTest FAIL: different character index. %d, should be %d\n", scriptRun1.characterRun.characterIndex, scriptRun2.characterRun.characterIndex );
return false;
}
if( scriptRun1.characterRun.numberOfCharacters != scriptRun2.characterRun.numberOfCharacters )
{
tet_printf("ScriptsTest FAIL: different number of characters. %d, should be %d\n", scriptRun1.characterRun.numberOfCharacters, scriptRun2.characterRun.numberOfCharacters );
return false;
}
if( scriptRun1.script != scriptRun2.script )
{
tet_printf("ScriptsTest FAIL: different script. %s, should be %s\n", TextAbstraction::ScriptName[scriptRun1.script], TextAbstraction::ScriptName[scriptRun2.script] );
return false;
}
}
return true;
}
bool ValidateFontTest( const ValidateFontsData& data )
{
MultilanguageSupport multilanguageSupport = MultilanguageSupport::Get();
TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
// 1) Convert to utf32
Vector<Character> utf32;
utf32.Resize( data.text.size() );
const uint32_t numberOfCharacters = Utf8ToUtf32( reinterpret_cast<const uint8_t* const>( data.text.c_str() ),
data.text.size(),
&utf32[0u] );
utf32.Resize( numberOfCharacters );
// 2) Set the script info.
Vector<ScriptRun> scripts;
multilanguageSupport.SetScripts( utf32,
0u,
numberOfCharacters,
scripts );
char* pathNamePtr = get_current_dir_name();
const std::string pathName( pathNamePtr );
free( pathNamePtr );
// Get the default font id.
const FontId defaultFontId = fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + data.defaultFont,
data.defaultFontSize );
TextAbstraction::FontDescription defaultFontDescription;
fontClient.GetDescription( defaultFontId, defaultFontDescription );
const TextAbstraction::PointSize26Dot6 defaultPointSize = fontClient.GetPointSize( defaultFontId );
Vector<FontRun> fontRuns;
// 3) Validate the fonts.
multilanguageSupport.ValidateFonts( utf32,
scripts,
data.fontDescriptionRuns,
defaultFontDescription,
defaultPointSize,
0u,
numberOfCharacters,
fontRuns );
if( ( 0u != data.index ) ||
( numberOfCharacters != data.numberOfCharacters ) )
{
// 4) Clear the fonts.
ClearCharacterRuns( data.index,
data.index + data.numberOfCharacters - 1u,
fontRuns );
multilanguageSupport.ValidateFonts( utf32,
scripts,
data.fontDescriptionRuns,
defaultFontDescription,
defaultPointSize,
data.index,
data.numberOfCharacters,
fontRuns );
}
// 5) Compare the results.
if( data.fontRuns.Count() != fontRuns.Count() )
{
std::cout << " Different number of font runs : " << fontRuns.Count() << ", expected : " << data.fontRuns.Count() << std::endl;
return false;
}
for( unsigned int index = 0; index < data.fontRuns.Count(); ++index )
{
const FontRun& run = fontRuns[index];
const FontRun& expectedRun = data.fontRuns[index];
if( run.characterRun.characterIndex != expectedRun.characterRun.characterIndex )
{
std::cout << " character run : " << index << ", index : " << run.characterRun.characterIndex << ", expected : " << expectedRun.characterRun.characterIndex << std::endl;
return false;
}
if( run.characterRun.numberOfCharacters != expectedRun.characterRun.numberOfCharacters )
{
std::cout << " character run : " << index << ", num chars : " << run.characterRun.numberOfCharacters << ", expected : " << expectedRun.characterRun.numberOfCharacters << std::endl;
return false;
}
if( run.fontId != expectedRun.fontId )
{
std::cout << " character run : " << index << ", font : " << run.fontId << ", expected : " << expectedRun.fontId << std::endl;
return false;
}
}
return true;
}
} // namespace
int UtcDaliTextGetScript(void)
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliTextGetScript");
Script script = TextAbstraction::LATIN;
// Text with no scripts.
Vector<ScriptRun> scriptRuns;
Vector<ScriptRun>::ConstIterator scriptRunIt = scriptRuns.Begin();
script = GetScript( 0u,
scriptRunIt,
scriptRuns.End() );
DALI_TEST_CHECK( TextAbstraction::UNKNOWN == script );
const unsigned int numberOfCharacters = 7u;
// Add scripts.
ScriptRun scriptRun01 =
{
{
0u,
2u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun02 =
{
{
2u,
2u,
},
TextAbstraction::HEBREW
};
ScriptRun scriptRun03 =
{
{
4u,
2u,
},
TextAbstraction::ARABIC
};
scriptRuns.PushBack( scriptRun01 );
scriptRuns.PushBack( scriptRun02 );
scriptRuns.PushBack( scriptRun03 );
// Expected results
TextAbstraction::Script expectedScripts[]=
{
TextAbstraction::LATIN,
TextAbstraction::LATIN,
TextAbstraction::HEBREW,
TextAbstraction::HEBREW,
TextAbstraction::ARABIC,
TextAbstraction::ARABIC,
TextAbstraction::UNKNOWN
};
scriptRunIt = scriptRuns.Begin();
for( unsigned int index = 0u; index < numberOfCharacters; ++index )
{
script = GetScript( index,
scriptRunIt,
scriptRuns.End() );
DALI_TEST_CHECK( expectedScripts[index] == script );
}
DALI_TEST_CHECK( scriptRunIt == scriptRuns.End() );
tet_result(TET_PASS);
END_TEST;
}
int UtcDaliTextMergeFontDescriptions(void)
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliTextMergeFontDescriptions");
// Load some fonts.
char* pathNamePtr = get_current_dir_name();
const std::string pathName( pathNamePtr );
free( pathNamePtr );
TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/dejavu/DejaVuSans.ttf" );
fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/dejavu/DejaVuSerif.ttf" );
fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/dejavu/DejaVuSerif.ttf", NON_DEFAULT_FONT_SIZE );
fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/dejavu/DejaVuSerif-Bold.ttf" );
fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/dejavu/DejaVuSerif-Italic.ttf" );
// To test the font width as GetFontId() with the font file path can't cache the width property.
TextAbstraction::FontDescription widthDescription;
widthDescription.path = "";
widthDescription.family = "DejaVu Serif";
widthDescription.weight = TextAbstraction::FontWeight::NORMAL;
widthDescription.width = TextAbstraction::FontWidth::EXPANDED;
widthDescription.slant = TextAbstraction::FontSlant::NORMAL;
fontClient.GetFontId( widthDescription );
// Test.
TextAbstraction::FontDescription defaultFontDescription01;
Vector<FontDescriptionRun> fontDescriptionRuns01;
Vector<FontId> expectedFontIds01;
Vector<bool> expectedIsFontDefault01;
TextAbstraction::FontDescription defaultFontDescription02;
Vector<FontDescriptionRun> fontDescriptionRuns02;
Vector<FontId> expectedFontIds02;
expectedFontIds02.PushBack( 0u );
expectedFontIds02.PushBack( 0u );
Vector<bool> expectedIsFontDefault02;
expectedIsFontDefault02.PushBack( true );
expectedIsFontDefault02.PushBack( true );
TextAbstraction::FontDescription defaultFontDescription03;
defaultFontDescription03.family = "DejaVu Serif";
Vector<FontDescriptionRun> fontDescriptionRuns03;
FontDescriptionRun fontDescription0301 =
{
{
0u,
2u
},
const_cast<char*>( "DejaVu Sans" ),
11u,
TextAbstraction::FontWeight::NONE,
TextAbstraction::FontWidth::NONE,
TextAbstraction::FontSlant::NONE,
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
true,
false,
false,
false,
false
};
FontDescriptionRun fontDescription0302 =
{
{
2u,
2u
},
NULL,
0u,
TextAbstraction::FontWeight::NONE,
TextAbstraction::FontWidth::NONE,
TextAbstraction::FontSlant::ITALIC,
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
false,
false,
false,
true,
false
};
FontDescriptionRun fontDescription0303 =
{
{
4u,
2u
},
NULL,
0u,
TextAbstraction::FontWeight::BOLD,
TextAbstraction::FontWidth::NONE,
TextAbstraction::FontSlant::NONE,
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
false,
true,
false,
false,
false
};
FontDescriptionRun fontDescription0304 =
{
{
6u,
2u
},
NULL,
0u,
TextAbstraction::FontWeight::NONE,
TextAbstraction::FontWidth::NONE,
TextAbstraction::FontSlant::NONE,
NON_DEFAULT_FONT_SIZE,
false,
false,
false,
false,
true
};
FontDescriptionRun fontDescription0305 =
{
{
8u,
2u
},
NULL,
0u,
TextAbstraction::FontWeight::NONE,
TextAbstraction::FontWidth::EXPANDED,
TextAbstraction::FontSlant::NONE,
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
false,
false,
true,
false,
false
};
fontDescriptionRuns03.PushBack( fontDescription0301 );
fontDescriptionRuns03.PushBack( fontDescription0302 );
fontDescriptionRuns03.PushBack( fontDescription0303 );
fontDescriptionRuns03.PushBack( fontDescription0304 );
fontDescriptionRuns03.PushBack( fontDescription0305 );
Vector<FontId> expectedFontIds03;
expectedFontIds03.PushBack( 1u );
expectedFontIds03.PushBack( 1u );
expectedFontIds03.PushBack( 5u );
expectedFontIds03.PushBack( 5u );
expectedFontIds03.PushBack( 4u );
expectedFontIds03.PushBack( 4u );
expectedFontIds03.PushBack( 3u );
expectedFontIds03.PushBack( 3u );
expectedFontIds03.PushBack( 6u );
expectedFontIds03.PushBack( 6u );
Vector<bool> expectedIsFontDefault03;
expectedIsFontDefault03.PushBack( false );
expectedIsFontDefault03.PushBack( false );
expectedIsFontDefault03.PushBack( false );
expectedIsFontDefault03.PushBack( false );
expectedIsFontDefault03.PushBack( false );
expectedIsFontDefault03.PushBack( false );
expectedIsFontDefault03.PushBack( false );
expectedIsFontDefault03.PushBack( false );
expectedIsFontDefault03.PushBack( false );
expectedIsFontDefault03.PushBack( false );
const MergeFontDescriptionsData data[] =
{
{
"void text.",
fontDescriptionRuns01,
defaultFontDescription01,
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
0u,
0u,
expectedFontIds01,
expectedIsFontDefault01
},
{
"No description runs.",
fontDescriptionRuns02,
defaultFontDescription02,
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
0u,
2u,
expectedFontIds02,
expectedIsFontDefault02
},
{
"Some description runs.",
fontDescriptionRuns03,
defaultFontDescription03,
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
0u,
10u,
expectedFontIds03,
expectedIsFontDefault03
}
};
const unsigned int numberOfTests = 3u;
for( unsigned int index = 0u; index < numberOfTests; ++index )
{
if( !MergeFontDescriptionsTest( data[index] ) )
{
tet_result(TET_FAIL);
}
}
tet_result(TET_PASS);
END_TEST;
}
int UtcDaliTextMultiLanguageConstructor(void)
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliTextMultiLanguageConstructor");
MultilanguageSupport multilanguageSupport;
DALI_TEST_CHECK( !multilanguageSupport );
MultilanguageSupport multilanguageSupport1 = MultilanguageSupport::Get();
DALI_TEST_CHECK( multilanguageSupport1 );
// To increase coverage.
MultilanguageSupport multilanguageSupport2 = MultilanguageSupport::Get();
DALI_TEST_CHECK( multilanguageSupport2 );
DALI_TEST_CHECK( multilanguageSupport1 == multilanguageSupport2 );
tet_result(TET_PASS);
END_TEST;
}
int UtcDaliTextMultiLanguageSetScripts(void)
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliTextMultiLanguageSetScripts" );
// Void text.
Vector<ScriptRun> scriptRuns00;
// Hello world.
Vector<ScriptRun> scriptRuns01;
ScriptRun scriptRun0100 =
{
{
0u,
11u,
},
TextAbstraction::LATIN
};
scriptRuns01.PushBack( scriptRun0100 );
// Mix of LTR '\n'and RTL
Vector<ScriptRun> scriptRuns02;
ScriptRun scriptRun0200 =
{
{
0u,
12u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun0201 =
{
{
12u,
13u,
},
TextAbstraction::ARABIC
};
scriptRuns02.PushBack( scriptRun0200 );
scriptRuns02.PushBack( scriptRun0201 );
// Mix of RTL '\n'and LTR
Vector<ScriptRun> scriptRuns03;
ScriptRun scriptRun0300 =
{
{
0u,
14u,
},
TextAbstraction::ARABIC
};
ScriptRun scriptRun0301 =
{
{
14u,
11u,
},
TextAbstraction::LATIN
};
scriptRuns03.PushBack( scriptRun0300 );
scriptRuns03.PushBack( scriptRun0301 );
// White spaces. At the beginning of the text.
Vector<ScriptRun> scriptRuns04;
ScriptRun scriptRun0400 =
{
{
0u,
15u,
},
TextAbstraction::LATIN
};
scriptRuns04.PushBack( scriptRun0400 );
// White spaces. At the end of the text.
Vector<ScriptRun> scriptRuns05;
ScriptRun scriptRun0500 =
{
{
0u,
15u,
},
TextAbstraction::LATIN
};
scriptRuns05.PushBack( scriptRun0500 );
// White spaces. At the middle of the text.
Vector<ScriptRun> scriptRuns06;
ScriptRun scriptRun0600 =
{
{
0u,
15u,
},
TextAbstraction::LATIN
};
scriptRuns06.PushBack( scriptRun0600 );
// White spaces between different scripts.
Vector<ScriptRun> scriptRuns07;
ScriptRun scriptRun0700 =
{
{
0u,
8u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun0701 =
{
{
8u,
5u,
},
TextAbstraction::HANGUL
};
scriptRuns07.PushBack( scriptRun0700 );
scriptRuns07.PushBack( scriptRun0701 );
// White spaces between different scripts and differetn directions. Starting LTR.
Vector<ScriptRun> scriptRuns08;
ScriptRun scriptRun0800 =
{
{
0u,
18u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun0801 =
{
{
18u,
14u,
},
TextAbstraction::ARABIC
};
ScriptRun scriptRun0802 =
{
{
32u,
18u,
},
TextAbstraction::HANGUL
};
scriptRuns08.PushBack( scriptRun0800 );
scriptRuns08.PushBack( scriptRun0801 );
scriptRuns08.PushBack( scriptRun0802 );
// White spaces between different scripts and differetn directions. Starting RTL.
Vector<ScriptRun> scriptRuns09;
ScriptRun scriptRun0900 =
{
{
0u,
21u,
},
TextAbstraction::ARABIC
};
ScriptRun scriptRun0901 =
{
{
21u,
16u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun0902 =
{
{
37u,
10u,
},
TextAbstraction::HANGUL
};
ScriptRun scriptRun0903 =
{
{
47u,
20u,
},
TextAbstraction::ARABIC
};
scriptRuns09.PushBack( scriptRun0900 );
scriptRuns09.PushBack( scriptRun0901 );
scriptRuns09.PushBack( scriptRun0902 );
scriptRuns09.PushBack( scriptRun0903 );
// Paragraphs with different directions.
Vector<ScriptRun> scriptRuns10;
ScriptRun scriptRun1000 =
{
{
0u,
20u,
},
TextAbstraction::ARABIC
};
ScriptRun scriptRun1001 =
{
{
20u,
12u,
},
TextAbstraction::HEBREW
};
ScriptRun scriptRun1002 =
{
{
32u,
17u,
},
TextAbstraction::ARABIC
};
ScriptRun scriptRun1003 =
{
{
49u,
18u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun1004 =
{
{
67u,
14u,
},
TextAbstraction::HANGUL
};
ScriptRun scriptRun1005 =
{
{
81u,
19u,
},
TextAbstraction::ARABIC
};
ScriptRun scriptRun1006 =
{
{
100u,
13u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun1007 =
{
{
113u,
16u,
},
TextAbstraction::HEBREW
};
ScriptRun scriptRun1008 =
{
{
129u,
20u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun1009 =
{
{
149u,
14u,
},
TextAbstraction::ARABIC
};
ScriptRun scriptRun1010 =
{
{
163u,
18u,
},
TextAbstraction::HANGUL
};
ScriptRun scriptRun1011 =
{
{
181u,
17u,
},
TextAbstraction::HANGUL
};
scriptRuns10.PushBack( scriptRun1000 );
scriptRuns10.PushBack( scriptRun1001 );
scriptRuns10.PushBack( scriptRun1002 );
scriptRuns10.PushBack( scriptRun1003 );
scriptRuns10.PushBack( scriptRun1004 );
scriptRuns10.PushBack( scriptRun1005 );
scriptRuns10.PushBack( scriptRun1006 );
scriptRuns10.PushBack( scriptRun1007 );
scriptRuns10.PushBack( scriptRun1008 );
scriptRuns10.PushBack( scriptRun1009 );
scriptRuns10.PushBack( scriptRun1010 );
scriptRuns10.PushBack( scriptRun1011 );
// Paragraphs with no scripts mixed with paragraphs with scripts.
Vector<ScriptRun> scriptRuns11;
ScriptRun scriptRun1100 =
{
{
0u,
3u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun1101 =
{
{
3u,
3u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun1102 =
{
{
6u,
19u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun1103 =
{
{
25u,
3u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun1104 =
{
{
28u,
3u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun1105 =
{
{
31u,
15u,
},
TextAbstraction::HEBREW
};
ScriptRun scriptRun1106 =
{
{
46u,
2u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun1107 =
{
{
48u,
2u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun1108 =
{
{
50u,
2u,
},
TextAbstraction::LATIN
};
scriptRuns11.PushBack( scriptRun1100 );
scriptRuns11.PushBack( scriptRun1101 );
scriptRuns11.PushBack( scriptRun1102 );
scriptRuns11.PushBack( scriptRun1103 );
scriptRuns11.PushBack( scriptRun1104 );
scriptRuns11.PushBack( scriptRun1105 );
scriptRuns11.PushBack( scriptRun1106 );
scriptRuns11.PushBack( scriptRun1107 );
scriptRuns11.PushBack( scriptRun1108 );
// Paragraphs with no scripts.
Vector<ScriptRun> scriptRuns12;
ScriptRun scriptRun1200 =
{
{
0u,
3u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun1201 =
{
{
3u,
3u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun1202 =
{
{
6u,
3u,
},
TextAbstraction::LATIN
};
ScriptRun scriptRun1203 =
{
{
9u,
2u,
},
TextAbstraction::LATIN
};
scriptRuns12.PushBack( scriptRun1200 );
scriptRuns12.PushBack( scriptRun1201 );
scriptRuns12.PushBack( scriptRun1202 );
scriptRuns12.PushBack( scriptRun1203 );
Vector<ScriptRun> scriptRuns13;
ScriptRun scriptRun1301 =
{
{
0u,
4u,
},
TextAbstraction::LATIN // An unknown script is transformed to LATIN
};
scriptRuns13.PushBack( scriptRun1301 );
const ScriptsData data[] =
{
{
"void text",
"",
0u,
0u,
scriptRuns00,
},
{
"Easy latin script",
"Hello world",
0u,
11u,
scriptRuns01,
},
{
"Mix of LTR '\\n'and RTL",
"Hello world\nمرحبا بالعالم",
0u,
25u,
scriptRuns02,
},
{
"Update mix of LTR '\\n'and RTL. Update LTR",
"Hello world\nمرحبا بالعالم",
0u,
12u,
scriptRuns02,
},
{
"Update mix of LTR '\\n'and RTL. Update RTL",
"Hello world\nمرحبا بالعالم",
12u,
13u,
scriptRuns02,
},
{
"Mix of RTL '\\n'and LTR",
"مرحبا بالعالم\nHello world",
0u,
25u,
scriptRuns03,
},
{
"Update mix of RTL '\\n'and LTR. Update RTL",
"مرحبا بالعالم\nHello world",
0u,
14u,
scriptRuns03,
},
{
"Update mix of RTL '\\n'and LTR. Update LTR",
"مرحبا بالعالم\nHello world",
14u,
11u,
scriptRuns03,
},
{
"White spaces. At the beginning of the text.",
" Hello world",
0u,
15u,
scriptRuns04,
},
{
"White spaces. At the end of the text.",
"Hello world ",
0u,
15u,
scriptRuns05,
},
{
"White spaces. At the middle of the text.",
"Hello world",
0u,
15u,
scriptRuns06,
},
{
"White spaces between different scripts.",
" Hel 세계 ",
0u,
13u,
scriptRuns07,
},
{
"White spaces between different scripts and differetn directions. Starting LTR.",
" Hello world مرحبا بالعالم 안녕하세요 세계 ",
0u,
50u,
scriptRuns08,
},
{
"White spaces between different scripts and differetn directions. Starting RTL.",
" مرحبا بالعالم Hello world 안녕하세요 세계 مرحبا بالعالم ",
0u,
67u,
scriptRuns09
},
{
"Paragraphs with different directions.",
" مرحبا بالعالم שלום עולם مرحبا بالعالم \n "
" Hello world 안녕하세요 세계 \n "
" مرحبا بالعالم Hello world שלום עולם \n "
" Hello world مرحبا بالعالم 안녕하세요 세계 \n "
" 안녕하세요 세계 ",
0u,
198u,
scriptRuns10
},
{
"Update paragraphs with different directions. Update initial paragraphs.",
" مرحبا بالعالم שלום עולם مرحبا بالعالم \n "
" Hello world 안녕하세요 세계 \n "
" مرحبا بالعالم Hello world שלום עולם \n "
" Hello world مرحبا بالعالم 안녕하세요 세계 \n "
" 안녕하세요 세계 ",
0u,
81u,
scriptRuns10
},
{
"Update paragraphs with different directions. Update middle paragraphs.",
" مرحبا بالعالم שלום עולם مرحبا بالعالم \n "
" Hello world 안녕하세요 세계 \n "
" مرحبا بالعالم Hello world שלום עולם \n "
" Hello world مرحبا بالعالم 안녕하세요 세계 \n "
" 안녕하세요 세계 ",
49u,
80u,
scriptRuns10
},
{
"Update paragraphs with different directions. Update final paragraphs.",
" مرحبا بالعالم שלום עולם مرحبا بالعالم \n "
" Hello world 안녕하세요 세계 \n "
" مرحبا بالعالم Hello world שלום עולם \n "
" Hello world مرحبا بالعالم 안녕하세요 세계 \n "
" 안녕하세요 세계 ",
129u,
69u,
scriptRuns10
},
{
"Paragraphs with no scripts mixed with paragraphs with scripts.",
" \n \n Hello world \n \n \n שלום עולם \n \n \n ",
0u,
52u,
scriptRuns11
},
{
"Paragraphs with no scripts.",
" \n \n \n ",
0u,
11u,
scriptRuns12
},
{
"Update paragraphs with no scripts. Update initial paragraphs.",
" \n \n \n ",
0u,
3u,
scriptRuns12
},
{
"Update paragraphs with no scripts. Update middle paragraphs.",
" \n \n \n ",
3u,
6u,
scriptRuns12
},
{
"Update paragraphs with no scripts. Update final paragraphs.",
" \n \n \n ",
9u,
2u,
scriptRuns12
},
{
"Unknown scripts.",
"ᚩᚯᚱᚸ", // Runic script not currentlu supported.
0u,
4u,
scriptRuns13
}
};
const unsigned int numberOfTests = 24u;
for( unsigned int index = 0u; index < numberOfTests; ++index )
{
if( !ScriptsTest( data[index] ) )
{
tet_result(TET_FAIL);
}
}
tet_result(TET_PASS);
END_TEST;
}
int UtcDaliTextMultiLanguageValidateFonts01(void)
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliTextMultiLanguageValidateFonts");
TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
char* pathNamePtr = get_current_dir_name();
const std::string pathName( pathNamePtr );
free( pathNamePtr );
const PointSize26Dot6 pointSize01 = static_cast<PointSize26Dot6>( 21.f * 64.f );
const PointSize26Dot6 pointSize02 = static_cast<PointSize26Dot6>( 35.f * 64.f );
// Load some fonts.
fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/tizen/TizenSansArabicRegular.ttf" );
fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/tizen/TizenSansHebrewRegular.ttf" );
fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/tizen/TizenColorEmoji.ttf", EMOJI_FONT_SIZE );
fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/tizen/TizenSansRegular.ttf", pointSize01 );
fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/tizen/TizenSansRegular.ttf", pointSize02 );
fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/tizen/TizenSansHebrewRegular.ttf", pointSize01 );
fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/tizen/TizenSansHebrewRegular.ttf", pointSize02 );
// Font id 1 --> TizenSansArabicRegular.ttf
// Font id 2 --> TizenSansHebrewRegular.ttf
// Font id 3 --> TizenColorEmoji.ttf
// Font id 4 --> TizenSansRegular.ttf, size 8
// Font id 5 --> TizenSansRegular.ttf, size 16
// Font id 6 --> TizenSansHebrewRegular.ttf, size 8
// Font id 7 --> TizenSansHebrewRegular.ttf, size 16
// Font id 8 --> (default)
Vector<FontRun> fontRuns01;
Vector<FontDescriptionRun> fontDescriptions01;
FontRun fontRun0201 =
{
{
0u,
11u
},
8u
};
Vector<FontRun> fontRuns02;
fontRuns02.PushBack( fontRun0201 );
FontDescriptionRun fontDescription0201 =
{
{
0u,
11u
},
const_cast<char*>( "TizenSans" ),
9u,
TextAbstraction::FontWeight::NORMAL,
TextAbstraction::FontWidth::NORMAL,
TextAbstraction::FontSlant::NORMAL,
0u,
true,
false,
false,
false,
false
};
Vector<FontDescriptionRun> fontDescriptions02;
fontDescriptions02.PushBack( fontDescription0201 );
FontRun fontRun0301 =
{
{
0u,
12u
},
8u
};
FontRun fontRun0302 =
{
{
12u,
12u
},
8u
};
FontRun fontRun0303 =
{
{
24u,
4u
},
8u
};
Vector<FontRun> fontRuns03;
fontRuns03.PushBack( fontRun0301 );
fontRuns03.PushBack( fontRun0302 );
fontRuns03.PushBack( fontRun0303 );
Vector<FontDescriptionRun> fontDescriptions03;
FontRun fontRun0701 =
{
{
0u,
4u
},
2u
};
FontRun fontRun0702 =
{
{
4u,
1u
},
8u
};
FontRun fontRun0703 =
{
{
5u,
4u
},
2u
};
Vector<FontRun> fontRuns07;
fontRuns07.PushBack( fontRun0701 );
fontRuns07.PushBack( fontRun0702 );
fontRuns07.PushBack( fontRun0703 );
FontDescriptionRun fontDescription0701 =
{
{
0u,
4u
},
const_cast<char*>( "TizenSansHebrew" ),
15u,
TextAbstraction::FontWeight::NORMAL,
TextAbstraction::FontWidth::NORMAL,
TextAbstraction::FontSlant::NORMAL,
0u,
true,
false,
false,
false,
false
};
FontDescriptionRun fontDescription0702 =
{
{
5u,
4u
},
const_cast<char*>( "TizenSansHebrew" ),
15u,
TextAbstraction::FontWeight::NORMAL,
TextAbstraction::FontWidth::NORMAL,
TextAbstraction::FontSlant::NORMAL,
0u,
true,
false,
false,
false,
false
};
Vector<FontDescriptionRun> fontDescriptions07;
fontDescriptions07.PushBack( fontDescription0701 );
fontDescriptions07.PushBack( fontDescription0702 );
FontRun fontRun0801 =
{
{
0u,
9u
},
2u
};
Vector<FontRun> fontRuns08;
fontRuns08.PushBack( fontRun0801 );
Vector<FontDescriptionRun> fontDescriptions08;
FontRun fontRun0901 =
{
{
0u,
4u
},
3u
};
Vector<FontRun> fontRuns09;
fontRuns09.PushBack( fontRun0901 );
Vector<FontDescriptionRun> fontDescriptions09;
FontDescriptionRun fontDescription0901 =
{
{
0u,
4u
},
const_cast<char*>( "TizenColorEmoji" ),
15u,
TextAbstraction::FontWeight::NORMAL,
TextAbstraction::FontWidth::NORMAL,
TextAbstraction::FontSlant::NORMAL,
EMOJI_FONT_SIZE,
true,
false,
false,
false,
true
};
fontDescriptions09.PushBack( fontDescription0901 );
FontRun fontRun1001 =
{
{
0u,
13u
},
4u
};
FontRun fontRun1002 =
{
{
13u,
9u
},
6u
};
FontRun fontRun1003 =
{
{
22u,
15u
},
5u
};
FontRun fontRun1004 =
{
{
37u,
9u
},
7u
};
Vector<FontRun> fontRuns10;
fontRuns10.PushBack( fontRun1001 );
fontRuns10.PushBack( fontRun1002 );
fontRuns10.PushBack( fontRun1003 );
fontRuns10.PushBack( fontRun1004 );
FontDescriptionRun fontDescription1001 =
{
{
0u,
13u
},
const_cast<char*>( "TizenSans" ),
9u,
TextAbstraction::FontWeight::NORMAL,
TextAbstraction::FontWidth::NORMAL,
TextAbstraction::FontSlant::NORMAL,
pointSize01,
true,
false,
false,
false,
true
};
FontDescriptionRun fontDescription1002 =
{
{
13u,
9u
},
const_cast<char*>( "TizenSansHebrew" ),
15u,
TextAbstraction::FontWeight::NORMAL,
TextAbstraction::FontWidth::NORMAL,
TextAbstraction::FontSlant::NORMAL,
pointSize01,
true,
false,
false,
false,
true
};
FontDescriptionRun fontDescription1003 =
{
{
22u,
15u
},
const_cast<char*>( "TizenSans" ),
9u,
TextAbstraction::FontWeight::NORMAL,
TextAbstraction::FontWidth::NORMAL,
TextAbstraction::FontSlant::NORMAL,
pointSize02,
true,
false,
false,
false,
true
};
FontDescriptionRun fontDescription1004 =
{
{
37u,
9u
},
const_cast<char*>( "TizenSansHebrew" ),
15u,
TextAbstraction::FontWeight::NORMAL,
TextAbstraction::FontWidth::NORMAL,
TextAbstraction::FontSlant::NORMAL,
pointSize02,
true,
false,
false,
false,
true
};
Vector<FontDescriptionRun> fontDescriptions10;
fontDescriptions10.PushBack( fontDescription1001 );
fontDescriptions10.PushBack( fontDescription1002 );
fontDescriptions10.PushBack( fontDescription1003 );
fontDescriptions10.PushBack( fontDescription1004 );
const ValidateFontsData data[] =
{
{
"void text.",
"",
"/tizen/TizenSansRegular.ttf",
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
0u,
0u,
fontDescriptions01,
fontRuns01
},
{
"Easy latin script.",
"Hello world",
"/tizen/TizenSansRegular.ttf",
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
0u,
11u,
fontDescriptions02,
fontRuns02
},
{
"Different paragraphs.",
"Hello world\nhello world\ndemo",
"/tizen/TizenSansRegular.ttf",
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
0u,
28u,
fontDescriptions03,
fontRuns03
},
{
"Different paragraphs. Update the initial paragraph.",
"Hello world\nhello world\ndemo",
"/tizen/TizenSansRegular.ttf",
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
0u,
12u,
fontDescriptions03,
fontRuns03
},
{
"Different paragraphs. Update the middle paragraph.",
"Hello world\nhello world\ndemo",
"/tizen/TizenSansRegular.ttf",
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
12u,
12u,
fontDescriptions03,
fontRuns03
},
{
"Different paragraphs. Update the final paragraph.",
"Hello world\nhello world\ndemo",
"/tizen/TizenSansRegular.ttf",
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
24u,
4u,
fontDescriptions03,
fontRuns03
},
{
"Hebrew text. Default font: latin",
"שלום עולם",
"/tizen/TizenSansRegular.ttf",
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
0u,
9u,
fontDescriptions07,
fontRuns07
},
{
"Hebrew text. Default font: hebrew",
"שלום עולם",
"/tizen/TizenSansHebrewRegular.ttf",
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
0u,
9u,
fontDescriptions08,
fontRuns08
},
{
"Emojis",
"\xF0\x9F\x98\x81\xF0\x9F\x98\x82\xF0\x9F\x98\x83\xF0\x9F\x98\x84",
"/tizen/TizenColorEmoji.ttf",
EMOJI_FONT_SIZE,
0u,
4u,
fontDescriptions09,
fontRuns09
},
{
"Mix text. Default font: latin. Different font sizes",
"Hello world, שלום עולם, hello world, שלום עולם",
"/tizen/TizenSansRegular.ttf",
TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
0u,
46u,
fontDescriptions10,
fontRuns10
},
};
const unsigned int numberOfTests = 10u;
for( unsigned int index = 0u; index < numberOfTests; ++index )
{
if( !ValidateFontTest( data[index] ) )
{
tet_result(TET_FAIL);
}
}
tet_result(TET_PASS);
END_TEST;
}
| 25.367429
| 207
| 0.613115
|
pwisbey
|
3be965725110bbc1c942e6967f7edf2d42026459
| 38,792
|
cpp
|
C++
|
test/liz_lookaside_double_stack_test.cpp
|
bjoernknafla/liz
|
b9400b0cb51379aa133953894580006892c2dc2a
|
[
"BSD-3-Clause"
] | 35
|
2015-05-13T03:06:37.000Z
|
2022-02-18T20:33:03.000Z
|
test/liz_lookaside_double_stack_test.cpp
|
bjoernknafla/liz
|
b9400b0cb51379aa133953894580006892c2dc2a
|
[
"BSD-3-Clause"
] | null | null | null |
test/liz_lookaside_double_stack_test.cpp
|
bjoernknafla/liz
|
b9400b0cb51379aa133953894580006892c2dc2a
|
[
"BSD-3-Clause"
] | 3
|
2016-12-20T19:03:26.000Z
|
2018-03-27T08:52:43.000Z
|
/*
* Copyright (c) 2011, Bjoern Knafla
* http://www.bjoernknafla.com/
* 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 Bjoern Knafla 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.
*/
/**
* @file
*
*
*/
#include <liz/liz_lookaside_double_stack.h>
#include <cassert>
#include <climits>
#include <unittestpp.h>
SUITE(liz_lookaside_double_stack_test)
{
TEST(make_empty_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(2, 0, 0);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(2, liz_lookaside_double_stack_capacity(&stack));
CHECK_EQUAL(true, liz_lookaside_double_stack_is_valid(&stack));
}
TEST(make_zero_capacity_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(0, 0, 0);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_capacity(&stack));
CHECK_EQUAL(true, liz_lookaside_double_stack_is_valid(&stack));
}
TEST(count_all_empty_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 0);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_all(&stack));
}
TEST(count_all_zero_capacity_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(0, 0, 0);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_all(&stack));
}
TEST(count_all_low_entries_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 0);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_all(&stack));
}
TEST(count_all_high_entries_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 3);
CHECK_EQUAL(3, liz_lookaside_double_stack_count_all(&stack));
}
TEST(count_all_low_and_high_entries_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 1);
CHECK_EQUAL(3, liz_lookaside_double_stack_count_all(&stack));
}
TEST(count_all_full_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 3, 1);
CHECK_EQUAL(4, liz_lookaside_double_stack_count_all(&stack));
}
TEST(count_low_empty_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 0);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
}
TEST(count_low_zero_capacity_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(0, 0, 0);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
}
TEST(count_low_low_entries_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 0);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_low(&stack));
}
TEST(count_low_high_entries_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 3);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
}
TEST(count_low_low_and_high_entries_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 1);
CHECK_EQUAL(2, liz_lookaside_double_stack_count_low(&stack));
}
TEST(count_low_full_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 3, 1);
CHECK_EQUAL(3, liz_lookaside_double_stack_count_low(&stack));
}
TEST(count_high_empty_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 0);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
}
TEST(count_high_zero_capacity_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(0, 0, 0);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
}
TEST(count_high_low_entries_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 0);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
}
TEST(count_high_high_entries_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 3);
CHECK_EQUAL(3, liz_lookaside_double_stack_count_high(&stack));
}
TEST(count_high_low_and_high_entries_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 1);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_high(&stack));
}
TEST(count_high_full_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 3, 1);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_high(&stack));
}
TEST(count_empty_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 0);
CHECK_EQUAL(0, liz_lookaside_double_stack_count(&stack, liz_lookaside_double_stack_side_low));
CHECK_EQUAL(0, liz_lookaside_double_stack_count(&stack, liz_lookaside_double_stack_side_high));
}
TEST(count_zero_capacity_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(0, 0, 0);
CHECK_EQUAL(0, liz_lookaside_double_stack_count(&stack, liz_lookaside_double_stack_side_low));
CHECK_EQUAL(0, liz_lookaside_double_stack_count(&stack, liz_lookaside_double_stack_side_high));
}
TEST(count_low_entries_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 0);
CHECK_EQUAL(1, liz_lookaside_double_stack_count(&stack, liz_lookaside_double_stack_side_low));
CHECK_EQUAL(0, liz_lookaside_double_stack_count(&stack, liz_lookaside_double_stack_side_high));
}
TEST(count_high_entries_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 3);
CHECK_EQUAL(0, liz_lookaside_double_stack_count(&stack, liz_lookaside_double_stack_side_low));
CHECK_EQUAL(3, liz_lookaside_double_stack_count(&stack, liz_lookaside_double_stack_side_high));
}
TEST(count_low_and_high_entries_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 1);
CHECK_EQUAL(2, liz_lookaside_double_stack_count(&stack, liz_lookaside_double_stack_side_low));
CHECK_EQUAL(1, liz_lookaside_double_stack_count(&stack, liz_lookaside_double_stack_side_high));
}
TEST(count_full_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 3, 1);
CHECK_EQUAL(3, liz_lookaside_double_stack_count(&stack, liz_lookaside_double_stack_side_low));
CHECK_EQUAL(1, liz_lookaside_double_stack_count(&stack, liz_lookaside_double_stack_side_high));
}
/*
TEST(empty_stack_is_empty)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 0);
CHECK_EQUAL(true, liz_lookaside_double_stack_is_empty(&stack));
}
TEST(zero_capacity_stack_is_not_empty)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(0, 0, 0);
CHECK_EQUAL(false, liz_lookaside_double_stack_is_empty(&stack));
}
TEST(low_non_empty_stack_is_not_empty)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 0);
CHECK_EQUAL(false, liz_lookaside_double_stack_is_empty(&stack));
}
TEST(high_non_empty_stack_is_not_empty)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 2);
CHECK_EQUAL(false, liz_lookaside_double_stack_is_empty(&stack));
}
TEST(low_and_high_non_empty_stack_is_not_empty)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 1);
CHECK_EQUAL(false, liz_lookaside_double_stack_is_empty(&stack));
}
TEST(full_stack_is_not_empty)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 2);
CHECK_EQUAL(false, liz_lookaside_double_stack_is_empty(&stack));
}
*/
TEST(empty_stack_is_not_full)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 0);
CHECK_EQUAL(false, liz_lookaside_double_stack_is_full(&stack));
}
TEST(zero_capacityu_stack_is_full)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(0, 0, 0);
CHECK_EQUAL(true, liz_lookaside_double_stack_is_full(&stack));
}
TEST(low_non_full_stack_is_not_full)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 3, 0);
CHECK_EQUAL(false, liz_lookaside_double_stack_is_full(&stack));
}
TEST(high_non_full_stack_is_not_full)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 2);
CHECK_EQUAL(false, liz_lookaside_double_stack_is_full(&stack));
}
TEST(low_and_high_non_full_stack_is_not_full)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 1);
CHECK_EQUAL(false, liz_lookaside_double_stack_is_full(&stack));
}
TEST(low_full_stack_is_full)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 4);
CHECK_EQUAL(true, liz_lookaside_double_stack_is_full(&stack));
}
TEST(high_full_stack_is_full)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 4);
CHECK_EQUAL(true, liz_lookaside_double_stack_is_full(&stack));
}
TEST(low_and_high_full_stack_is_full)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 2);
CHECK_EQUAL(true, liz_lookaside_double_stack_is_full(&stack));
}
TEST(clear_empty_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 0);
liz_lookaside_double_stack_clear(&stack);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_all(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(clear_zero_capacity_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(0, 0, 0);
liz_lookaside_double_stack_clear(&stack);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_all(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_capacity(&stack));
}
TEST(clear_non_empty_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 1);
liz_lookaside_double_stack_clear(&stack);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_all(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(clear_full_stack)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 2);
liz_lookaside_double_stack_clear(&stack);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_all(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(empty_stack_push_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 0);
liz_lookaside_double_stack_push_low(&stack);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(non_empty_low_stack_push_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 3, 0);
liz_lookaside_double_stack_push_low(&stack);
CHECK_EQUAL(4, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(non_empty_high_stack_push_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 3);
liz_lookaside_double_stack_push_low(&stack);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(3, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(non_empty_stack_push_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 1);
liz_lookaside_double_stack_push_low(&stack);
CHECK_EQUAL(2, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(1, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(empty_stack_push_high)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 0);
liz_lookaside_double_stack_push_high(&stack);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(1, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(non_empty_low_stack_push_high)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 3, 0);
liz_lookaside_double_stack_push_high(&stack);
CHECK_EQUAL(3, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(1, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(non_empty_high_stack_push_high)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 3);
liz_lookaside_double_stack_push_high(&stack);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(non_empty_stack_push_high)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 1);
liz_lookaside_double_stack_push_high(&stack);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(2, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(empty_stack_push_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 0);
liz_lookaside_double_stack_push(&stack, liz_lookaside_double_stack_side_low);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(non_empty_low_stack_push_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 3, 0);
liz_lookaside_double_stack_push(&stack, liz_lookaside_double_stack_side_low);
CHECK_EQUAL(4, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(non_empty_high_stack_push_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 3);
liz_lookaside_double_stack_push(&stack, liz_lookaside_double_stack_side_low);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(3, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(non_empty_stack_push_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 1);
liz_lookaside_double_stack_push(&stack, liz_lookaside_double_stack_side_low);
CHECK_EQUAL(2, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(1, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(empty_stack_push_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 0);
liz_lookaside_double_stack_push(&stack, liz_lookaside_double_stack_side_high);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(1, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(non_empty_low_stack_push_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 3, 0);
liz_lookaside_double_stack_push(&stack, liz_lookaside_double_stack_side_high);
CHECK_EQUAL(3, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(1, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(non_empty_high_stack_push_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 3);
liz_lookaside_double_stack_push(&stack, liz_lookaside_double_stack_side_high);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(non_empty_stack_push_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 1);
liz_lookaside_double_stack_push(&stack, liz_lookaside_double_stack_side_high);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(2, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(one_low_element_stack_pop_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 0);
liz_lookaside_double_stack_pop_low(&stack);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(full_low_element_stack_pop_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 4, 0);
liz_lookaside_double_stack_pop_low(&stack);
CHECK_EQUAL(3, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(one_low_element_a_few_high_elements_pop_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 2);
liz_lookaside_double_stack_pop_low(&stack);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(2, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(full_stack_pop_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 3, 1);
liz_lookaside_double_stack_pop_low(&stack);
CHECK_EQUAL(2, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(1, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(one_high_element_stack_pop_high)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 1);
liz_lookaside_double_stack_pop_high(&stack);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(full_high_element_stack_pop_high)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 4);
liz_lookaside_double_stack_pop_high(&stack);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(3, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(few_low_element_one_high_elements_pop_high)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 1);
liz_lookaside_double_stack_pop_high(&stack);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(full_stack_pop_high)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 2);
liz_lookaside_double_stack_pop_high(&stack);
CHECK_EQUAL(2, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(1, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(one_low_element_stack_pop_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 0);
liz_lookaside_double_stack_pop(&stack, liz_lookaside_double_stack_side_low);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(full_low_element_stack_pop_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 4, 0);
liz_lookaside_double_stack_pop(&stack, liz_lookaside_double_stack_side_low);
CHECK_EQUAL(3, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(one_low_element_a_few_high_elements_pop_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 2);
liz_lookaside_double_stack_pop(&stack, liz_lookaside_double_stack_side_low);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(2, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(full_stack_pop_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 3, 1);
liz_lookaside_double_stack_pop(&stack, liz_lookaside_double_stack_side_low);
CHECK_EQUAL(2, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(1, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(one_high_element_stack_pop_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 1);
liz_lookaside_double_stack_pop(&stack, liz_lookaside_double_stack_side_high);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(full_high_element_stack_pop_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 4);
liz_lookaside_double_stack_pop(&stack, liz_lookaside_double_stack_side_high);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(3, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(few_low_element_one_high_elements_pop_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 1);
liz_lookaside_double_stack_pop(&stack, liz_lookaside_double_stack_side_high);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(full_stack_pop_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 2);
liz_lookaside_double_stack_pop(&stack, liz_lookaside_double_stack_side_high);
CHECK_EQUAL(2, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(1, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(set_count_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 2);
liz_lookaside_double_stack_set_count_low(&stack,
1);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(2, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(set_count_hight)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 2);
liz_lookaside_double_stack_set_count_high(&stack,
0);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(0, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(set_count_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 2);
liz_lookaside_double_stack_set_count(&stack,
0,
liz_lookaside_double_stack_side_low);
CHECK_EQUAL(0, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(2, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
TEST(set_count_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 2);
liz_lookaside_double_stack_set_count(&stack,
1,
liz_lookaside_double_stack_side_high);
CHECK_EQUAL(1, liz_lookaside_double_stack_count_low(&stack));
CHECK_EQUAL(1, liz_lookaside_double_stack_count_high(&stack));
CHECK_EQUAL(4, liz_lookaside_double_stack_capacity(&stack));
}
/* It's undefined behavior to call top_index on an empty stack.
TEST(zero_capacity_stack_top_index_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(0, 0, 0);
liz_int_t index = liz_lookaside_double_stack_top_index_low(&stack);
CHECK_EQUAL(LIZ_LOOKASIDE_DOUBLE_STACK_INDEX_INVALID, index);
}
TEST(empty_stack_top_index_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 0);
liz_int_t index = liz_lookaside_double_stack_top_index_low(&stack);
CHECK_EQUAL(LIZ_LOOKASIDE_DOUBLE_STACK_INDEX_INVALID, index);
}
TEST(empty_low_part_stack_top_index_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 1);
liz_int_t index = liz_lookaside_double_stack_top_index_low(&stack);
CHECK_EQUAL(LIZ_LOOKASIDE_DOUBLE_STACK_INDEX_INVALID, index);
}
*/
TEST(few_low_elements_stack_top_index_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 0);
liz_int_t index = liz_lookaside_double_stack_top_index_low(&stack);
CHECK_EQUAL(1, index);
}
TEST(full_low_element_stack_top_index_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 4, 0);
liz_int_t index = liz_lookaside_double_stack_top_index_low(&stack);
CHECK_EQUAL(3, index);
}
TEST(stack_top_index_low)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 3);
liz_int_t index = liz_lookaside_double_stack_top_index_low(&stack);
CHECK_EQUAL(0, index);
}
/* It's undefined behavior to call top_index on an empty stack.
TEST(zero_capacity_stack_top_index_high)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(0, 0, 0);
liz_int_t index = liz_lookaside_double_stack_top_index_high(&stack);
CHECK_EQUAL(LIZ_LOOKASIDE_DOUBLE_STACK_INDEX_INVALID, index);
}
TEST(empty_stack_top_index_high)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 4);
liz_int_t index = liz_lookaside_double_stack_top_index_high(&stack);
CHECK_EQUAL(LIZ_LOOKASIDE_DOUBLE_STACK_INDEX_INVALID, index);
}
TEST(empty_high_part_stack_top_index_high)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 0);
liz_int_t index = liz_lookaside_double_stack_top_index_high(&stack);
CHECK_EQUAL(LIZ_LOOKASIDE_DOUBLE_STACK_INDEX_INVALID, index);
}
*/
TEST(few_high_elements_stack_top_index_high)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 3);
liz_int_t index = liz_lookaside_double_stack_top_index_high(&stack);
CHECK_EQUAL(1, index);
}
TEST(full_high_element_stack_top_index_high)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 4);
liz_int_t index = liz_lookaside_double_stack_top_index_high(&stack);
CHECK_EQUAL(0, index);
}
TEST(stack_top_index_high)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 3);
liz_int_t index = liz_lookaside_double_stack_top_index_high(&stack);
CHECK_EQUAL(1, index);
}
/* It's undefined behavior to call top_index on an empty stack.
TEST(zero_capacity_stack_top_index_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(0, 0, 0);
liz_int_t index = liz_lookaside_double_stack_top_index(&stack,
liz_lookaside_double_stack_side_low);
CHECK_EQUAL(LIZ_LOOKASIDE_DOUBLE_STACK_INDEX_INVALID, index);
}
TEST(empty_stack_top_index_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 0);
liz_int_t index = liz_lookaside_double_stack_top_index(&stack,
liz_lookaside_double_stack_side_low);
CHECK_EQUAL(LIZ_LOOKASIDE_DOUBLE_STACK_INDEX_INVALID, index);
}
TEST(empty_low_part_stack_top_index_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 1);
liz_int_t index = liz_lookaside_double_stack_top_index(&stack,
liz_lookaside_double_stack_side_low);
CHECK_EQUAL(LIZ_LOOKASIDE_DOUBLE_STACK_INDEX_INVALID, index);
}
*/
TEST(few_low_elements_stack_top_index_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 2, 0);
liz_int_t index = liz_lookaside_double_stack_top_index(&stack,
liz_lookaside_double_stack_side_low);
CHECK_EQUAL(1, index);
}
TEST(full_low_element_stack_top_index_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 4, 0);
liz_int_t index = liz_lookaside_double_stack_top_index(&stack,
liz_lookaside_double_stack_side_low);
CHECK_EQUAL(3, index);
}
TEST(stack_top_index_low_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 3);
liz_int_t index = liz_lookaside_double_stack_top_index(&stack,
liz_lookaside_double_stack_side_low);
CHECK_EQUAL(0, index);
}
/* It's undefined behavior to call top_index on an empty stack.
TEST(zero_capacity_stack_top_index_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(0, 0, 0);
liz_int_t index = liz_lookaside_double_stack_top_index(&stack,
liz_lookaside_double_stack_side_high);
CHECK_EQUAL(LIZ_LOOKASIDE_DOUBLE_STACK_INDEX_INVALID, index);
}
TEST(empty_stack_top_index_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 0);
liz_int_t index = liz_lookaside_double_stack_top_index(&stack,
liz_lookaside_double_stack_side_high);
CHECK_EQUAL(LIZ_LOOKASIDE_DOUBLE_STACK_INDEX_INVALID, index);
}
TEST(empty_highw_part_stack_top_index_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 0);
liz_int_t index = liz_lookaside_double_stack_top_index(&stack,
liz_lookaside_double_stack_side_high);
CHECK_EQUAL(LIZ_LOOKASIDE_DOUBLE_STACK_INDEX_INVALID, index);
}
*/
TEST(few_high_elements_stack_top_index_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 3);
liz_int_t index = liz_lookaside_double_stack_top_index(&stack,
liz_lookaside_double_stack_side_high);
CHECK_EQUAL(1, index);
}
TEST(full_high_element_stack_top_index_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 0, 4);
liz_int_t index = liz_lookaside_double_stack_top_index(&stack,
liz_lookaside_double_stack_side_high);
CHECK_EQUAL(0, index);
}
TEST(stack_top_index_high_case)
{
liz_lookaside_double_stack_t stack = liz_lookaside_double_stack_make(4, 1, 3);
liz_int_t index = liz_lookaside_double_stack_top_index(&stack,
liz_lookaside_double_stack_side_high);
CHECK_EQUAL(1, index);
}
} // SUITE(liz_lookaside_double_stack_test)
| 33.155556
| 103
| 0.673824
|
bjoernknafla
|
3becd4412c57677be86fe437b7785d18eb77bf1a
| 1,200
|
hpp
|
C++
|
gpcl/detail/futex_condition_variable.hpp
|
Chingyat/gpcl
|
de4157a2bab07640539d9051fc7bb66c9c82eaf4
|
[
"BSL-1.0"
] | 2
|
2021-02-10T11:51:25.000Z
|
2021-12-20T12:35:36.000Z
|
gpcl/detail/futex_condition_variable.hpp
|
Chingyat/gpcl
|
de4157a2bab07640539d9051fc7bb66c9c82eaf4
|
[
"BSL-1.0"
] | 2
|
2021-11-28T03:09:15.000Z
|
2021-11-29T15:08:43.000Z
|
gpcl/detail/futex_condition_variable.hpp
|
Chingyat/gpcl
|
c2702b8b13fa948f6753285ba62455ddf9413578
|
[
"BSL-1.0"
] | null | null | null |
//
// futex_condition_variable.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021 Zhengyi Fu (tsingyat at outlook dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef GPCL_DETAIL_FUTEX_CONDITION_VARIABLE_HPP
#define GPCL_DETAIL_FUTEX_CONDITION_VARIABLE_HPP
#include <gpcl/detail/config.hpp>
#include <gpcl/detail/futex.hpp>
#include <gpcl/detail/futex_mutex.hpp>
namespace gpcl {
namespace detail {
class futex_condition_variable
{
public:
inline constexpr explicit futex_condition_variable() noexcept;
futex_condition_variable(const futex_condition_variable &) = delete;
futex_condition_variable(futex_condition_variable &&) = delete;
GPCL_DECL void wait(futex_mutex &mtx);
GPCL_DECL void notify_one();
GPCL_DECL void notify_all();
private:
futex_word_type fut_;
};
constexpr futex_condition_variable::futex_condition_variable() noexcept
: fut_(0)
{
}
} // namespace detail
} // namespace gpcl
#ifdef GPCL_HEADER_ONLY
# include <gpcl/detail/impl/futex_condition_variable.ipp>
#endif
#endif // GPCL_DETAIL_FUTEX_CONDITION_VARIABLE_HPP
| 23.076923
| 79
| 0.763333
|
Chingyat
|
3bf07c6ae1742d3ed0e08ab858c5d2e22f2d775c
| 2,164
|
hpp
|
C++
|
include/argot/concepts/exceptional_switch_body_case.hpp
|
mattcalabrese/argot
|
97349baaf27659c9dc4d67cf8963b2e871eaedae
|
[
"BSL-1.0"
] | 49
|
2018-05-09T23:17:45.000Z
|
2021-07-21T10:05:19.000Z
|
include/argot/concepts/exceptional_switch_body_case.hpp
|
mattcalabrese/argot
|
97349baaf27659c9dc4d67cf8963b2e871eaedae
|
[
"BSL-1.0"
] | null | null | null |
include/argot/concepts/exceptional_switch_body_case.hpp
|
mattcalabrese/argot
|
97349baaf27659c9dc4d67cf8963b2e871eaedae
|
[
"BSL-1.0"
] | 2
|
2019-08-04T03:51:36.000Z
|
2020-12-28T06:53:29.000Z
|
/*==============================================================================
Copyright (c) 2017, 2018, 2019 Matt Calabrese
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef ARGOT_CONCEPTS_EXCEPTIONAL_SWITCH_BODY_CASE_HPP_
#define ARGOT_CONCEPTS_EXCEPTIONAL_SWITCH_BODY_CASE_HPP_
#include <argot/concepts/detail/concepts_preprocessing_helpers.hpp>
#include <argot/concepts/same_type.hpp>
#include <argot/concepts/switch_body_case.hpp>
#include <argot/gen/auto_concept.hpp>
#include <argot/gen/transparent_requirement.hpp>
#ifndef ARGOT_GENERATE_PREPROCESSED_CONCEPTS
#include <argot/receiver_traits/argument_list_kinds.hpp>
#include <argot/switch_traits/argument_list_kinds_of_case_destructive.hpp>
#endif // ARGOT_GENERATE_PREPROCESSED_CONCEPTS
namespace argot {
namespace exceptional_cases_detail {
template< class T, auto Value >
struct exceptional_cases_requirements
{
template< template< class... > class Reqs >
using expand_requirements
= Reqs
< SameType
< switch_traits::argument_list_kinds_of_case_destructive_t< T, Value >
, receiver_traits::argument_list_kinds_t<>
>
>;
};
} // namespace argot(::exceptional_cases_detail)
#define ARGOT_DETAIL_PREPROCESSED_CONCEPT_HEADER_NAME() \
s/exceptional_switch_body_case.h
#ifdef ARGOT_CONCEPTS_DETAIL_SHOULD_INCLUDE_PREPROCESSED_HEADER
#include ARGOT_CONCEPTS_DETAIL_PREPROCESSED_HEADER
#else
#include <argot/concepts/detail/preprocess_header_begin.hpp>
ARGOT_CONCEPTS_DETAIL_CREATE_LINE_DIRECTIVE( __LINE__ )
template< class T, auto Value >
ARGOT_AUTO_CONCEPT( ExceptionalSwitchBodyCase )
(
SwitchBodyCase< T, Value >
, TransparentRequirement
< exceptional_cases_detail::exceptional_cases_requirements< T, Value > >
);
#include <argot/concepts/detail/preprocess_header_end.hpp>
#endif // ARGOT_CONCEPTS_DETAIL_SHOULD_INCLUDE_PREPROCESSED_HEADER
} // namespace argot
#endif // ARGOT_CONCEPTS_EXCEPTIONAL_SWITCH_BODY_CASE_HPP_
| 31.823529
| 80
| 0.743993
|
mattcalabrese
|
3bf0be8c6d410f54c33368f6b85a14294709ca0b
| 4,576
|
cpp
|
C++
|
vp/src/platform/basic/display.cpp
|
agra-uni-bremen/fdl21-stackuse-vp
|
9c8be7a3534cdd8ed8b8fbce7be740fc16807876
|
[
"MIT"
] | 26
|
2019-11-01T09:02:35.000Z
|
2022-03-10T02:21:12.000Z
|
vp/src/platform/basic/display.cpp
|
agra-uni-bremen/fdl21-stackuse-vp
|
9c8be7a3534cdd8ed8b8fbce7be740fc16807876
|
[
"MIT"
] | 2
|
2019-05-01T10:22:07.000Z
|
2020-07-27T10:08:51.000Z
|
vp/src/platform/basic/display.cpp
|
agra-uni-bremen/fdl21-stackuse-vp
|
9c8be7a3534cdd8ed8b8fbce7be740fc16807876
|
[
"MIT"
] | 12
|
2018-06-19T14:09:49.000Z
|
2022-02-08T03:34:14.000Z
|
/*
* display.cpp
*
* Created on: Sep 11, 2018
* Author: dwd
*/
#include "display.hpp"
#include <math.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
using namespace frame;
Display::Display(sc_module_name) {
tsock.register_b_transport(this, &Display::transport);
createSM();
memset(frame.raw, 0, sizeof(Framebuffer));
}
void Display::createSM() {
int shmid;
if ((shmid = shmget(SHMKEY, sizeof(Framebuffer), IPC_CREAT | 0666)) < 0) {
std::cerr << "Could not get " << sizeof(Framebuffer) << " Byte of shared Memory " << int(SHMKEY)
<< " for display" << std::endl;
perror(NULL);
exit(1);
}
frame.raw = reinterpret_cast<uint8_t *>(shmat(shmid, nullptr, 0));
if (frame.raw == (uint8_t *)-1) {
perror("shmat");
exit(1);
}
}
void Display::transport(tlm::tlm_generic_payload &trans, sc_core::sc_time &delay) {
tlm::tlm_command cmd = trans.get_command();
unsigned addr = trans.get_address();
auto *ptr = trans.get_data_ptr();
auto len = trans.get_data_length();
assert((addr + len <= sizeof(Framebuffer)) && "Access display out of bounds");
if (cmd == tlm::TLM_WRITE_COMMAND) {
if (addr == offsetof(Framebuffer, command) && len == sizeof(Framebuffer::Command)) { // apply command
switch (*reinterpret_cast<Framebuffer::Command *>(ptr)) {
case Framebuffer::Command::clearAll:
memset(frame.raw, 0, sizeof(Framebuffer));
frame.buf->activeFrame++;
break;
case Framebuffer::Command::fillFrame:
fillFrame(frame.buf->parameter.fill.frame, frame.buf->parameter.fill.color);
break;
case Framebuffer::Command::applyFrame:
frame.buf->activeFrame++;
memcpy(&frame.buf->getInactiveFrame(), &frame.buf->getActiveFrame(), sizeof(Frame));
break;
case Framebuffer::Command::drawLine:
drawLine(frame.buf->parameter.line.frame, frame.buf->parameter.line.from,
frame.buf->parameter.line.to, frame.buf->parameter.line.color);
break;
default:
cerr << "unknown framebuffer command " << *ptr << endl;
sc_assert(false);
break;
}
// reset parameter
memset(reinterpret_cast<void *>(&frame.buf->parameter), 0, sizeof(Framebuffer::Parameter));
} else if (addr >= offsetof(Framebuffer, parameter) &&
addr + len < offsetof(Framebuffer, parameter) + sizeof(Framebuffer::Parameter)) { // write the
// parameter
memcpy(&frame.raw[addr], ptr, len);
} else { // Write the actual framebuffer
memcpy(&frame.raw[addr], ptr, len);
}
} else if (cmd == tlm::TLM_READ_COMMAND && addr < sizeof(Framebuffer)) { // read whatever you like
memcpy(ptr, &frame.raw[addr], len);
} else {
sc_assert(false && "unsupported tlm command");
}
delay += sc_core::sc_time(len * 5, sc_core::SC_NS);
}
void Display::fillFrame(Framebuffer::Type type, Color color) {
assert(sizeof(Frame) % 8 == 0);
assert(8 % sizeof(Color) == 0);
uint64_t *rawFrame = reinterpret_cast<uint64_t *>(&frame.buf->getFrame(type).raw);
uint_fast32_t steps = sizeof(Frame) / 8;
uint64_t wideColor = 0;
for (uint_fast8_t i = 0; i * sizeof(Color) < 8; i++) {
reinterpret_cast<Color *>(&wideColor)[i] = color;
}
for (uint_fast32_t i = 0; i < steps; i++) {
rawFrame[i] = wideColor;
}
}
void Display::drawLine(Framebuffer::Type type, PointF from, PointF to, Color color) {
Frame &local = frame.buf->getFrame(type);
if (from.x == to.x) { // vertical line
if (from.y > to.y)
swap(from.y, to.y);
uint16_t intFromX = from.x;
uint16_t intToY = to.y;
for (uint16_t y = from.y; y <= intToY; y++) {
local.raw[y][intFromX] = color;
}
return;
}
if (from.y == to.y) { // horizontal line, the fastest
if (from.x > to.x)
swap(from.x, to.x);
uint16_t intFromY = from.y;
uint16_t intToX = to.x;
for (uint16_t x = from.x; x <= intToX; x++) {
local.raw[intFromY][x] = color;
}
return;
}
// Bresenham's line algorithm
const bool steep = (fabs(to.y - from.y) > fabs(to.x - from.x));
if (steep) {
swap(from.x, from.y);
swap(to.x, to.y);
}
if (from.x > to.x) {
swap(from.x, to.x);
swap(from.y, to.y);
}
const float dx = to.x - from.x;
const float dy = fabs(to.y - from.y);
float error = dx / 2.0f;
const int ystep = (from.y < to.y) ? 1 : -1;
int y = (int)from.y;
const int maxX = (int)to.x;
for (int x = (int)from.x; x < maxX; x++) {
if (steep) {
local.raw[x][y] = color;
} else {
local.raw[y][x] = color;
}
error -= dy;
if (error < 0) {
y += ystep;
error += dx;
}
}
}
| 28.962025
| 108
| 0.618663
|
agra-uni-bremen
|
3bf188edca33b4a13261f05859f614759d9e2f39
| 674
|
cpp
|
C++
|
Problem Solving/Implementation/bill_division.cpp
|
abivilion/Hackerank-Solutions-
|
e195fb1fce1588171cf12d99d38da32ca5c8276a
|
[
"MIT"
] | null | null | null |
Problem Solving/Implementation/bill_division.cpp
|
abivilion/Hackerank-Solutions-
|
e195fb1fce1588171cf12d99d38da32ca5c8276a
|
[
"MIT"
] | null | null | null |
Problem Solving/Implementation/bill_division.cpp
|
abivilion/Hackerank-Solutions-
|
e195fb1fce1588171cf12d99d38da32ca5c8276a
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main ()
{
//siz = no of item
// ski = index reserved
// inp = items
// sum : all appdups
//
int siz,ski,inp,sum=0,charged =0;
int store_index_ele=0;
cin>>siz>>ski;
for(int i=0;i<siz;i++)
{
if( i != ski )
{
cin>>inp;
sum += inp;
}
else {
cin>>inp;
store_index_ele =inp;
}
}
cin>>charged;
if((sum/2 - charged) == 0)
cout<<"Bon Appetit";
else
cout<<abs(sum/2 - charged);
return 0;
}
| 16.85
| 40
| 0.394659
|
abivilion
|
3bf1ff94a8040c30c9d8998c313ba5928989fcd4
| 44,650
|
cpp
|
C++
|
keynote-protos/mapping/ProtoMapping.cpp
|
eth-siplab/SVG2Keynote-lib
|
b7e6dfe5084911dac1fa6261a14254bfbbd8065b
|
[
"MIT"
] | 4
|
2021-11-24T14:27:32.000Z
|
2022-03-14T07:52:44.000Z
|
keynote-protos/mapping/ProtoMapping.cpp
|
eth-siplab/SVG2Keynote-lib
|
b7e6dfe5084911dac1fa6261a14254bfbbd8065b
|
[
"MIT"
] | null | null | null |
keynote-protos/mapping/ProtoMapping.cpp
|
eth-siplab/SVG2Keynote-lib
|
b7e6dfe5084911dac1fa6261a14254bfbbd8065b
|
[
"MIT"
] | null | null | null |
#include "ProtoMapping.h"
ProtoMapping::ProtoMapping(std::string type) {
registerCommonMessageTypes();
if (type == "keynote") {
registerKeynoteMessageTypes();
}
}
void ProtoMapping::registerKeynoteMessageTypes() {
_messageTypeToPrototypeMap[1]= new KN::DocumentArchive();
_messageTypeToPrototypeMap[2]= new KN::ShowArchive();
_messageTypeToPrototypeMap[3]= new KN::UIStateArchive();
_messageTypeToPrototypeMap[4]= new KN::SlideNodeArchive();
_messageTypeToPrototypeMap[5]= new KN::SlideArchive();
_messageTypeToPrototypeMap[6]= new KN::SlideArchive();
_messageTypeToPrototypeMap[7]= new KN::PlaceholderArchive();
_messageTypeToPrototypeMap[8]= new KN::BuildArchive();
_messageTypeToPrototypeMap[9]= new KN::SlideStyleArchive();
_messageTypeToPrototypeMap[10]= new KN::ThemeArchive();
_messageTypeToPrototypeMap[11]= new KN::PasteboardNativeStorageArchive();
_messageTypeToPrototypeMap[12]= new KN::PlaceholderArchive();
_messageTypeToPrototypeMap[14]= new TSWP::TextualAttachmentArchive();
_messageTypeToPrototypeMap[15]= new KN::NoteArchive();
_messageTypeToPrototypeMap[16]= new KN::RecordingArchive();
_messageTypeToPrototypeMap[17]= new KN::RecordingEventTrackArchive();
_messageTypeToPrototypeMap[18]= new KN::RecordingMovieTrackArchive();
_messageTypeToPrototypeMap[19]= new KN::ClassicStylesheetRecordArchive();
_messageTypeToPrototypeMap[20]= new KN::ClassicThemeRecordArchive();
_messageTypeToPrototypeMap[21]= new KN::Soundtrack();
_messageTypeToPrototypeMap[22]= new KN::SlideNumberAttachmentArchive();
_messageTypeToPrototypeMap[23]= new KN::DesktopUILayoutArchive();
_messageTypeToPrototypeMap[24]= new KN::CanvasSelectionArchive();
_messageTypeToPrototypeMap[25]= new KN::SlideCollectionSelectionArchive();
_messageTypeToPrototypeMap[100]= new KN::CommandBuildSetValueArchive();
_messageTypeToPrototypeMap[101]= new KN::CommandShowInsertSlideArchive();
_messageTypeToPrototypeMap[102]= new KN::CommandShowMoveSlideArchive();
_messageTypeToPrototypeMap[103]= new KN::CommandShowRemoveSlideArchive();
_messageTypeToPrototypeMap[104]= new KN::CommandSlideInsertDrawablesArchive();
_messageTypeToPrototypeMap[105]= new KN::CommandSlideRemoveDrawableArchive();
_messageTypeToPrototypeMap[106]= new KN::CommandSlideNodeSetPropertyArchive();
_messageTypeToPrototypeMap[107]= new KN::CommandSlideInsertBuildArchive();
_messageTypeToPrototypeMap[109]= new KN::CommandSlideRemoveBuildArchive();
_messageTypeToPrototypeMap[110]= new KN::CommandSlideInsertBuildChunkArchive();
_messageTypeToPrototypeMap[111]= new KN::CommandSlideMoveBuildChunksArchive();
_messageTypeToPrototypeMap[112]= new KN::CommandSlideRemoveBuildChunkArchive();
_messageTypeToPrototypeMap[114]= new KN::CommandTransitionSetValueArchive();
_messageTypeToPrototypeMap[118]= new KN::CommandSlideMoveDrawableZOrderArchive();
_messageTypeToPrototypeMap[119]= new KN::CommandChangeTemplateSlideArchive();
_messageTypeToPrototypeMap[123]= new KN::CommandShowSetSlideNumberVisibilityArchive();
_messageTypeToPrototypeMap[124]= new KN::CommandShowSetValueArchive();
_messageTypeToPrototypeMap[128]= new KN::CommandShowMarkOutOfSyncRecordingArchive();
_messageTypeToPrototypeMap[129]= new KN::CommandShowRemoveRecordingArchive();
_messageTypeToPrototypeMap[130]= new KN::CommandShowReplaceRecordingArchive();
_messageTypeToPrototypeMap[131]= new KN::CommandShowSetSoundtrack();
_messageTypeToPrototypeMap[132]= new KN::CommandSoundtrackSetValue();
_messageTypeToPrototypeMap[134]= new KN::CommandMoveTemplatesArchive();
_messageTypeToPrototypeMap[135]= new KN::CommandInsertTemplateArchive();
_messageTypeToPrototypeMap[136]= new KN::CommandSlideSetStyleArchive();
_messageTypeToPrototypeMap[137]= new KN::CommandSlideSetPlaceholdersForTagsArchive();
_messageTypeToPrototypeMap[138]= new KN::CommandBuildChunkSetValueArchive();
_messageTypeToPrototypeMap[140]= new KN::CommandRemoveTemplateArchive();
_messageTypeToPrototypeMap[142]= new KN::CommandTemplateSetThumbnailTextArchive();
_messageTypeToPrototypeMap[143]= new KN::CommandShowChangeThemeArchive();
_messageTypeToPrototypeMap[144]= new KN::CommandSlidePrimitiveSetTemplateArchive();
_messageTypeToPrototypeMap[145]= new KN::CommandTemplateSetBodyStylesArchive();
_messageTypeToPrototypeMap[146]= new KNSOS::CommandSlideReapplyTemplateSlideArchive();
_messageTypeToPrototypeMap[148]= new KN::ChartInfoGeometryCommandArchive();
_messageTypeToPrototypeMap[150]= new KN::CommandSlideUpdateTemplateDrawables();
_messageTypeToPrototypeMap[152]= new KN::CommandSlideSetBackgroundFillArchive();
_messageTypeToPrototypeMap[153]= new KN::BuildChunkArchive();
_messageTypeToPrototypeMap[156]= new KN::CommandSlideNodeSetViewStatePropertyArchive();
_messageTypeToPrototypeMap[157]= new KN::CommandBuildUpdateChunkCountArchive();
_messageTypeToPrototypeMap[158]= new KN::CommandBuildUpdateChunkReferentsArchive();
_messageTypeToPrototypeMap[159]= new KN::BuildAttributeTupleArchive();
_messageTypeToPrototypeMap[160]= new KN::CommandSetThemeCustomEffectTimingCurveArchive();
_messageTypeToPrototypeMap[161]= new KN::CommandShowChangeSlideSizeArchive();
_messageTypeToPrototypeMap[162]= new KN::InsertBuildDescriptionArchive();
_messageTypeToPrototypeMap[163]= new KN::RemoveBuildDescriptionArchive();
_messageTypeToPrototypeMap[164]= new KN::DocumentSelectionTransformerArchive();
_messageTypeToPrototypeMap[165]= new KN::SlideCollectionSelectionTransformerArchive();
_messageTypeToPrototypeMap[166]= new KN::OutlineCanvasSelectionTransformerArchive();
_messageTypeToPrototypeMap[167]= new KN::NoteCanvasSelectionTransformerArchive();
_messageTypeToPrototypeMap[168]= new KN::CanvasSelectionTransformerArchive();
_messageTypeToPrototypeMap[169]= new KN::OutlineSelectionTransformerArchive();
_messageTypeToPrototypeMap[170]= new KN::UndoObjectArchive();
_messageTypeToPrototypeMap[172]= new KN::PrototypeForUndoTemplateChangeArchive();
_messageTypeToPrototypeMap[173]= new KN::CommandShowMarkOutOfSyncRecordingIfNeededArchive();
_messageTypeToPrototypeMap[174]= new KNSOS::InducedVerifyDocumentWithServerCommandArchive();
_messageTypeToPrototypeMap[175]= new KNSOS::InducedVerifyDrawableZOrdersWithServerCommandArchive();
_messageTypeToPrototypeMap[176]= new KN::CommandPrimitiveInsertTemplateArchive();
_messageTypeToPrototypeMap[177]= new KN::CommandPrimitiveRemoveTemplateArchive();
_messageTypeToPrototypeMap[178]= new KN::CommandTemplateSlideSetPlaceholderForTagArchive();
_messageTypeToPrototypeMap[179]= new KN::CommandSlidePropagateSetPlaceholderForTagArchive();
_messageTypeToPrototypeMap[180]= new KN::ActionGhostSelectionArchive();
_messageTypeToPrototypeMap[181]= new KN::ActionGhostSelectionTransformerArchive();
_messageTypeToPrototypeMap[10011]= new TSWP::SectionPlaceholderArchive();
}
void ProtoMapping::registerCommonMessageTypes() {
_messageTypeToPrototypeMap[200]= new TSK::DocumentArchive();
_messageTypeToPrototypeMap[201]= new TSK::LocalCommandHistory();
_messageTypeToPrototypeMap[202]= new TSK::CommandGroupArchive();
_messageTypeToPrototypeMap[203]= new TSK::CommandContainerArchive();
_messageTypeToPrototypeMap[205]= new TSK::TreeNode();
_messageTypeToPrototypeMap[210]= new TSK::ViewStateArchive();
_messageTypeToPrototypeMap[211]= new TSK::DocumentSupportArchive();
_messageTypeToPrototypeMap[212]= new TSK::AnnotationAuthorArchive();
_messageTypeToPrototypeMap[213]= new TSK::AnnotationAuthorStorageArchive();
_messageTypeToPrototypeMap[215]= new TSK::SetAnnotationAuthorColorCommandArchive();
_messageTypeToPrototypeMap[218]= new TSK::CollaborationCommandHistory();
_messageTypeToPrototypeMap[219]= new TSK::DocumentSelectionArchive();
_messageTypeToPrototypeMap[220]= new TSK::CommandSelectionBehaviorArchive();
_messageTypeToPrototypeMap[221]= new TSK::NullCommandArchive();
_messageTypeToPrototypeMap[222]= new TSK::CustomFormatListArchive();
_messageTypeToPrototypeMap[223]= new TSK::GroupCommitCommandArchive();
_messageTypeToPrototypeMap[224]= new TSK::InducedCommandCollectionArchive();
_messageTypeToPrototypeMap[225]= new TSK::InducedCommandCollectionCommitCommandArchive();
_messageTypeToPrototypeMap[226]= new TSK::CollaborationDocumentSessionState();
_messageTypeToPrototypeMap[227]= new TSK::CollaborationCommandHistoryCoalescingGroup();
_messageTypeToPrototypeMap[228]= new TSK::CollaborationCommandHistoryCoalescingGroupNode();
_messageTypeToPrototypeMap[229]= new TSK::CollaborationCommandHistoryOriginatingCommandAcknowledgementObserver();
_messageTypeToPrototypeMap[230]= new TSK::DocumentSupportCollaborationState();
_messageTypeToPrototypeMap[231]= new TSK::ChangeDocumentPackageTypeCommandArchive();
_messageTypeToPrototypeMap[232]= new TSK::UpgradeDocPostProcessingCommandArchive();
_messageTypeToPrototypeMap[233]= new TSK::FinalCommandPairArchive();
_messageTypeToPrototypeMap[234]= new TSK::OutgoingCommandQueueItem();
_messageTypeToPrototypeMap[235]= new TSK::TransformerEntry();
_messageTypeToPrototypeMap[238]= new TSK::CreateLocalStorageSnapshotCommandArchive();
_messageTypeToPrototypeMap[240]= new TSK::SelectionPathTransformerArchive();
_messageTypeToPrototypeMap[241]= new TSK::NativeContentDescription();
_messageTypeToPrototypeMap[242]= new TSD::PencilAnnotationStorageArchive();
_messageTypeToPrototypeMap[245]= new TSK::OperationStorage();
_messageTypeToPrototypeMap[246]= new TSK::OperationStorageEntryArray();
_messageTypeToPrototypeMap[247]= new TSK::OperationStorageEntryArraySegment();
_messageTypeToPrototypeMap[248]= new TSK::BlockDiffsAtCurrentRevisionCommand();
_messageTypeToPrototypeMap[249]= new TSK::OutgoingCommandQueue();
_messageTypeToPrototypeMap[250]= new TSK::OutgoingCommandQueueSegment();
_messageTypeToPrototypeMap[251]= new TSK::PropagatedCommandCollectionArchive();
_messageTypeToPrototypeMap[252]= new TSK::LocalCommandHistoryItem();
_messageTypeToPrototypeMap[253]= new TSK::LocalCommandHistoryArray();
_messageTypeToPrototypeMap[254]= new TSK::LocalCommandHistoryArraySegment();
_messageTypeToPrototypeMap[255]= new TSK::CollaborationCommandHistoryItem();
_messageTypeToPrototypeMap[256]= new TSK::CollaborationCommandHistoryArray();
_messageTypeToPrototypeMap[257]= new TSK::CollaborationCommandHistoryArraySegment();
_messageTypeToPrototypeMap[258]= new TSK::PencilAnnotationUIState();
_messageTypeToPrototypeMap[259]= new TSKSOS::FixCorruptedDataCommandArchive();
_messageTypeToPrototypeMap[260]= new TSK::CommandAssetChunkArchive();
_messageTypeToPrototypeMap[261]= new TSK::AssetUploadStatusCommandArchive();
_messageTypeToPrototypeMap[262]= new TSK::AssetUnmaterializedOnServerCommandArchive();
_messageTypeToPrototypeMap[400]= new TSS::StyleArchive();
_messageTypeToPrototypeMap[401]= new TSS::StylesheetArchive();
_messageTypeToPrototypeMap[402]= new TSS::ThemeArchive();
_messageTypeToPrototypeMap[412]= new TSS::StyleUpdatePropertyMapCommandArchive();
_messageTypeToPrototypeMap[413]= new TSS::ThemeReplacePresetCommandArchive();
_messageTypeToPrototypeMap[414]= new TSS::ThemeAddStylePresetCommandArchive();
_messageTypeToPrototypeMap[415]= new TSS::ThemeRemoveStylePresetCommandArchive();
_messageTypeToPrototypeMap[416]= new TSS::ThemeReplaceColorPresetCommandArchive();
_messageTypeToPrototypeMap[417]= new TSS::ThemeMovePresetCommandArchive();
_messageTypeToPrototypeMap[419]= new TSS::ThemeReplaceStylePresetAndDisconnectStylesCommandArchive();
_messageTypeToPrototypeMap[600]= new TSA::DocumentArchive();
_messageTypeToPrototypeMap[601]= new TSA::FunctionBrowserStateArchive();
_messageTypeToPrototypeMap[602]= new TSA::PropagatePresetCommandArchive();
_messageTypeToPrototypeMap[603]= new TSA::ShortcutControllerArchive();
_messageTypeToPrototypeMap[604]= new TSA::ShortcutCommandArchive();
_messageTypeToPrototypeMap[605]= new TSA::AddCustomFormatCommandArchive();
_messageTypeToPrototypeMap[606]= new TSA::UpdateCustomFormatCommandArchive();
_messageTypeToPrototypeMap[607]= new TSA::ReplaceCustomFormatCommandArchive();
_messageTypeToPrototypeMap[611]= new TSASOS::VerifyObjectsWithServerCommandArchive();
_messageTypeToPrototypeMap[612]= new TSA::InducedVerifyObjectsWithServerCommandArchive();
_messageTypeToPrototypeMap[613]= new TSASOS::VerifyDocumentWithServerCommandArchive();
_messageTypeToPrototypeMap[614]= new TSASOS::VerifyDrawableZOrdersWithServerCommandArchive();
_messageTypeToPrototypeMap[615]= new TSASOS::InducedVerifyDrawableZOrdersWithServerCommandArchive();
_messageTypeToPrototypeMap[616]= new TSA::NeedsMediaCompatibilityUpgradeCommandArchive();
_messageTypeToPrototypeMap[617]= new TSA::ChangeDocumentLocaleCommandArchive();
_messageTypeToPrototypeMap[618]= new TSA::StyleUpdatePropertyMapCommandArchive();
_messageTypeToPrototypeMap[619]= new TSA::RemoteDataChangeCommandArchive();
_messageTypeToPrototypeMap[623]= new TSA::GalleryItem();
_messageTypeToPrototypeMap[624]= new TSA::GallerySelectionTransformer();
_messageTypeToPrototypeMap[625]= new TSA::GalleryItemSelection();
_messageTypeToPrototypeMap[626]= new TSA::GalleryItemSelectionTransformer();
_messageTypeToPrototypeMap[627]= new TSA::GalleryInfoSetValueCommandArchive();
_messageTypeToPrototypeMap[628]= new TSA::GalleryItemSetGeometryCommand();
_messageTypeToPrototypeMap[629]= new TSA::GalleryItemSetValueCommand();
_messageTypeToPrototypeMap[630]= new TSA::InducedVerifyTransformHistoryWithServerCommandArchive();
_messageTypeToPrototypeMap[631]= new TSASOS::CommandReapplyMasterArchive();
_messageTypeToPrototypeMap[632]= new TSASOS::PropagateMasterChangeCommandArchive();
_messageTypeToPrototypeMap[633]= new TSA::CaptionInfoArchive();
_messageTypeToPrototypeMap[634]= new TSA::CaptionPlacementArchive();
_messageTypeToPrototypeMap[635]= new TSA::TitlePlacementCommandArchive();
_messageTypeToPrototypeMap[636]= new TSA::GalleryInfoInsertItemsCommandArchive();
_messageTypeToPrototypeMap[637]= new TSA::GalleryInfoRemoveItemsCommandArchive();
_messageTypeToPrototypeMap[2001]= new TSWP::StorageArchive();
_messageTypeToPrototypeMap[2002]= new TSWP::SelectionArchive();
_messageTypeToPrototypeMap[2003]= new TSWP::DrawableAttachmentArchive();
_messageTypeToPrototypeMap[2004]= new TSWP::TextualAttachmentArchive();
_messageTypeToPrototypeMap[2005]= new TSWP::StorageArchive();
_messageTypeToPrototypeMap[2006]= new TSWP::UIGraphicalAttachment();
_messageTypeToPrototypeMap[2007]= new TSWP::TextualAttachmentArchive();
_messageTypeToPrototypeMap[2008]= new TSWP::FootnoteReferenceAttachmentArchive();
_messageTypeToPrototypeMap[2009]= new TSWP::TextualAttachmentArchive();
_messageTypeToPrototypeMap[2010]= new TSWP::TSWPTOCPageNumberAttachmentArchive();
_messageTypeToPrototypeMap[2011]= new TSWP::ShapeInfoArchive();
_messageTypeToPrototypeMap[2013]= new TSWP::HighlightArchive();
_messageTypeToPrototypeMap[2014]= new TSWP::CommentInfoArchive();
_messageTypeToPrototypeMap[2015]= new TSWP::EquationInfoArchive();
_messageTypeToPrototypeMap[2016]= new TSWP::PencilAnnotationArchive();
_messageTypeToPrototypeMap[2021]= new TSWP::CharacterStyleArchive();
_messageTypeToPrototypeMap[2022]= new TSWP::ParagraphStyleArchive();
_messageTypeToPrototypeMap[2023]= new TSWP::ListStyleArchive();
_messageTypeToPrototypeMap[2024]= new TSWP::ColumnStyleArchive();
_messageTypeToPrototypeMap[2025]= new TSWP::ShapeStyleArchive();
_messageTypeToPrototypeMap[2026]= new TSWP::TOCEntryStyleArchive();
_messageTypeToPrototypeMap[2031]= new TSWP::PlaceholderSmartFieldArchive();
_messageTypeToPrototypeMap[2032]= new TSWP::HyperlinkFieldArchive();
_messageTypeToPrototypeMap[2033]= new TSWP::FilenameSmartFieldArchive();
_messageTypeToPrototypeMap[2034]= new TSWP::DateTimeSmartFieldArchive();
_messageTypeToPrototypeMap[2035]= new TSWP::BookmarkFieldArchive();
_messageTypeToPrototypeMap[2036]= new TSWP::MergeSmartFieldArchive();
_messageTypeToPrototypeMap[2037]= new TSWP::CitationRecordArchive();
_messageTypeToPrototypeMap[2038]= new TSWP::CitationSmartFieldArchive();
_messageTypeToPrototypeMap[2039]= new TSWP::UnsupportedHyperlinkFieldArchive();
_messageTypeToPrototypeMap[2040]= new TSWP::BibliographySmartFieldArchive();
_messageTypeToPrototypeMap[2041]= new TSWP::TOCSmartFieldArchive();
_messageTypeToPrototypeMap[2042]= new TSWP::RubyFieldArchive();
_messageTypeToPrototypeMap[2043]= new TSWP::NumberAttachmentArchive();
_messageTypeToPrototypeMap[2050]= new TSWP::TextStylePresetArchive();
_messageTypeToPrototypeMap[2051]= new TSWP::TOCSettingsArchive();
_messageTypeToPrototypeMap[2052]= new TSWP::TOCEntryInstanceArchive();
_messageTypeToPrototypeMap[2053]= new TSWPSOS::StyleDiffArchive();
_messageTypeToPrototypeMap[2060]= new TSWP::ChangeArchive();
_messageTypeToPrototypeMap[2061]= new TSK::DeprecatedChangeAuthorArchive();
_messageTypeToPrototypeMap[2062]= new TSWP::ChangeSessionArchive();
_messageTypeToPrototypeMap[2101]= new TSWP::TextCommandArchive();
_messageTypeToPrototypeMap[2107]= new TSWP::ApplyPlaceholderTextCommandArchive();
_messageTypeToPrototypeMap[2116]= new TSWP::ApplyRubyTextCommandArchive();
_messageTypeToPrototypeMap[2118]= new TSWP::ModifyRubyTextCommandArchive();
_messageTypeToPrototypeMap[2119]= new TSWP::UpdateDateTimeFieldCommandArchive();
_messageTypeToPrototypeMap[2120]= new TSWP::ModifyTOCSettingsBaseCommandArchive();
_messageTypeToPrototypeMap[2121]= new TSWP::ModifyTOCSettingsForTOCInfoCommandArchive();
_messageTypeToPrototypeMap[2122]= new TSWP::ModifyTOCSettingsPresetForThemeCommandArchive();
_messageTypeToPrototypeMap[2123]= new TSWP::SetObjectPropertiesCommandArchive();
_messageTypeToPrototypeMap[2124]= new TSWP::UpdateFlowInfoCommandArchive();
_messageTypeToPrototypeMap[2125]= new TSWP::AddFlowInfoCommandArchive();
_messageTypeToPrototypeMap[2126]= new TSWP::RemoveFlowInfoCommandArchive();
_messageTypeToPrototypeMap[2127]= new TSWP::ContainedObjectsCommandArchive();
_messageTypeToPrototypeMap[2128]= new TSWP::EquationInfoGeometryCommandArchive();
_messageTypeToPrototypeMap[2206]= new TSWP::AnchorAttachmentCommandArchive();
_messageTypeToPrototypeMap[2217]= new TSWP::TextCommentReplyCommandArchive();
_messageTypeToPrototypeMap[2231]= new TSWP::ShapeApplyPresetCommandArchive();
_messageTypeToPrototypeMap[2240]= new TSWP::TOCInfoArchive();
_messageTypeToPrototypeMap[2241]= new TSWP::TOCAttachmentArchive();
_messageTypeToPrototypeMap[2242]= new TSWP::TOCLayoutHintArchive();
_messageTypeToPrototypeMap[2400]= new TSWP::StyleBaseCommandArchive();
_messageTypeToPrototypeMap[2401]= new TSWP::StyleCreateCommandArchive();
_messageTypeToPrototypeMap[2402]= new TSWP::StyleRenameCommandArchive();
_messageTypeToPrototypeMap[2404]= new TSWP::StyleDeleteCommandArchive();
_messageTypeToPrototypeMap[2405]= new TSWP::StyleReorderCommandArchive();
_messageTypeToPrototypeMap[2406]= new TSWP::StyleUpdatePropertyMapCommandArchive();
_messageTypeToPrototypeMap[2407]= new TSWP::StorageActionCommandArchive();
_messageTypeToPrototypeMap[2408]= new TSWP::ShapeStyleSetValueCommandArchive();
_messageTypeToPrototypeMap[2409]= new TSWP::HyperlinkSelectionArchive();
_messageTypeToPrototypeMap[2410]= new TSWP::FlowInfoArchive();
_messageTypeToPrototypeMap[2411]= new TSWP::FlowInfoContainerArchive();
_messageTypeToPrototypeMap[2412]= new TSWP::PencilAnnotationSelectionTransformerArchive();
_messageTypeToPrototypeMap[3002]= new TSD::DrawableArchive();
_messageTypeToPrototypeMap[3003]= new TSD::ContainerArchive();
_messageTypeToPrototypeMap[3004]= new TSD::ShapeArchive();
_messageTypeToPrototypeMap[3005]= new TSD::ImageArchive();
_messageTypeToPrototypeMap[3006]= new TSD::MaskArchive();
_messageTypeToPrototypeMap[3007]= new TSD::MovieArchive();
_messageTypeToPrototypeMap[3008]= new TSD::GroupArchive();
_messageTypeToPrototypeMap[3009]= new TSD::ConnectionLineArchive();
_messageTypeToPrototypeMap[3015]= new TSD::ShapeStyleArchive();
_messageTypeToPrototypeMap[3016]= new TSD::MediaStyleArchive();
_messageTypeToPrototypeMap[3021]= new TSD::InfoGeometryCommandArchive();
_messageTypeToPrototypeMap[3022]= new TSD::DrawablePathSourceCommandArchive();
_messageTypeToPrototypeMap[3024]= new TSD::ImageMaskCommandArchive();
_messageTypeToPrototypeMap[3025]= new TSD::ImageMediaCommandArchive();
_messageTypeToPrototypeMap[3026]= new TSD::ImageReplaceCommandArchive();
_messageTypeToPrototypeMap[3027]= new TSD::MediaOriginalSizeCommandArchive();
_messageTypeToPrototypeMap[3028]= new TSD::ShapeStyleSetValueCommandArchive();
_messageTypeToPrototypeMap[3030]= new TSD::MediaStyleSetValueCommandArchive();
_messageTypeToPrototypeMap[3031]= new TSD::ShapeApplyPresetCommandArchive();
_messageTypeToPrototypeMap[3032]= new TSD::MediaApplyPresetCommandArchive();
_messageTypeToPrototypeMap[3034]= new TSD::MovieSetValueCommandArchive();
_messageTypeToPrototypeMap[3036]= new TSD::ExteriorTextWrapCommandArchive();
_messageTypeToPrototypeMap[3037]= new TSD::MediaFlagsCommandArchive();
_messageTypeToPrototypeMap[3040]= new TSD::DrawableHyperlinkCommandArchive();
_messageTypeToPrototypeMap[3041]= new TSD::ConnectionLineConnectCommandArchive();
_messageTypeToPrototypeMap[3042]= new TSD::InstantAlphaCommandArchive();
_messageTypeToPrototypeMap[3043]= new TSD::DrawableLockCommandArchive();
_messageTypeToPrototypeMap[3044]= new TSD::ImageNaturalSizeCommandArchive();
_messageTypeToPrototypeMap[3045]= new TSD::CanvasSelectionArchive();
_messageTypeToPrototypeMap[3047]= new TSD::GuideStorageArchive();
_messageTypeToPrototypeMap[3048]= new TSD::StyledInfoSetStyleCommandArchive();
_messageTypeToPrototypeMap[3049]= new TSD::DrawableInfoCommentCommandArchive();
_messageTypeToPrototypeMap[3050]= new TSD::GuideCommandArchive();
_messageTypeToPrototypeMap[3051]= new TSD::DrawableAspectRatioLockedCommandArchive();
_messageTypeToPrototypeMap[3052]= new TSD::ContainerRemoveChildrenCommandArchive();
_messageTypeToPrototypeMap[3053]= new TSD::ContainerInsertChildrenCommandArchive();
_messageTypeToPrototypeMap[3054]= new TSD::ContainerReorderChildrenCommandArchive();
_messageTypeToPrototypeMap[3055]= new TSD::ImageAdjustmentsCommandArchive();
_messageTypeToPrototypeMap[3056]= new TSD::CommentStorageArchive();
_messageTypeToPrototypeMap[3057]= new TSD::ThemeReplaceFillPresetCommandArchive();
_messageTypeToPrototypeMap[3058]= new TSD::DrawableAccessibilityDescriptionCommandArchive();
_messageTypeToPrototypeMap[3059]= new TSD::PasteStyleCommandArchive();
_messageTypeToPrototypeMap[3061]= new TSD::DrawableSelectionArchive();
_messageTypeToPrototypeMap[3062]= new TSD::GroupSelectionArchive();
_messageTypeToPrototypeMap[3063]= new TSD::PathSelectionArchive();
_messageTypeToPrototypeMap[3064]= new TSD::CommentInvalidatingCommandSelectionBehaviorArchive();
_messageTypeToPrototypeMap[3065]= new TSD::ImageInfoAbstractGeometryCommandArchive();
_messageTypeToPrototypeMap[3066]= new TSD::ImageInfoGeometryCommandArchive();
_messageTypeToPrototypeMap[3067]= new TSD::ImageInfoMaskGeometryCommandArchive();
_messageTypeToPrototypeMap[3068]= new TSD::UndoObjectArchive();
_messageTypeToPrototypeMap[3070]= new TSD::ReplaceAnnotationAuthorCommandArchive();
_messageTypeToPrototypeMap[3071]= new TSD::DrawableSelectionTransformerArchive();
_messageTypeToPrototypeMap[3072]= new TSD::GroupSelectionTransformerArchive();
_messageTypeToPrototypeMap[3073]= new TSD::ShapeSelectionTransformerArchive();
_messageTypeToPrototypeMap[3074]= new TSD::PathSelectionTransformerArchive();
_messageTypeToPrototypeMap[3080]= new TSD::MediaInfoGeometryCommandArchive();
_messageTypeToPrototypeMap[3082]= new TSD::GroupUngroupInformativeCommandArchive();
_messageTypeToPrototypeMap[3083]= new TSD::DrawableContentDescription();
_messageTypeToPrototypeMap[3084]= new TSD::ContainerRemoveDrawablesCommandArchive();
_messageTypeToPrototypeMap[3085]= new TSD::ContainerInsertDrawablesCommandArchive();
_messageTypeToPrototypeMap[3086]= new TSD::PencilAnnotationArchive();
_messageTypeToPrototypeMap[3087]= new TSD::FreehandDrawingOpacityCommandArchive();
_messageTypeToPrototypeMap[3088]= new TSD::DrawablePencilAnnotationCommandArchive();
_messageTypeToPrototypeMap[3089]= new TSD::PencilAnnotationSelectionArchive();
_messageTypeToPrototypeMap[3090]= new TSD::FreehandDrawingContentDescription();
_messageTypeToPrototypeMap[3091]= new TSD::FreehandDrawingToolkitUIState();
_messageTypeToPrototypeMap[3092]= new TSD::PencilAnnotationSelectionTransformerArchive();
_messageTypeToPrototypeMap[3094]= new TSD::FreehandDrawingAnimationCommandArchive();
_messageTypeToPrototypeMap[3095]= new TSD::InsertCaptionOrTitleCommandArchive();
_messageTypeToPrototypeMap[3096]= new TSD::RemoveCaptionOrTitleCommandArchive();
_messageTypeToPrototypeMap[3097]= new TSD::StandinCaptionArchive();
_messageTypeToPrototypeMap[3098]= new TSD::SetCaptionOrTitleVisibilityCommandArchive();
_messageTypeToPrototypeMap[4000]= new TSCE::CalculationEngineArchive();
_messageTypeToPrototypeMap[4001]= new TSCE::FormulaRewriteCommandArchive();
_messageTypeToPrototypeMap[4002]= new TSCE::TrackedReferencesRewriteCommandArchive();
_messageTypeToPrototypeMap[4003]= new TSCE::NamedReferenceManagerArchive();
_messageTypeToPrototypeMap[4004]= new TSCE::ReferenceTrackerArchive();
_messageTypeToPrototypeMap[4005]= new TSCE::TrackedReferenceArchive();
_messageTypeToPrototypeMap[4006]= new TSCE::ExtendTableIDHistoryCommandArchive();
_messageTypeToPrototypeMap[4007]= new TSCE::RemoteDataStoreArchive();
_messageTypeToPrototypeMap[4008]= new TSCE::FormulaOwnerDependenciesArchive();
_messageTypeToPrototypeMap[4009]= new TSCE::CellRecordTileArchive();
_messageTypeToPrototypeMap[4010]= new TSCE::RangePrecedentsTileArchive();
_messageTypeToPrototypeMap[4011]= new TSCE::ReferencesToDirtyArchive();
_messageTypeToPrototypeMap[5000]= new TSCH::PreUFF::ChartInfoArchive();
_messageTypeToPrototypeMap[5002]= new TSCH::PreUFF::ChartGridArchive();
_messageTypeToPrototypeMap[5004]= new TSCH::ChartMediatorArchive();
_messageTypeToPrototypeMap[5010]= new TSCH::PreUFF::ChartStyleArchive();
_messageTypeToPrototypeMap[5011]= new TSCH::PreUFF::ChartSeriesStyleArchive();
_messageTypeToPrototypeMap[5012]= new TSCH::PreUFF::ChartAxisStyleArchive();
_messageTypeToPrototypeMap[5013]= new TSCH::PreUFF::LegendStyleArchive();
_messageTypeToPrototypeMap[5014]= new TSCH::PreUFF::ChartNonStyleArchive();
_messageTypeToPrototypeMap[5015]= new TSCH::PreUFF::ChartSeriesNonStyleArchive();
_messageTypeToPrototypeMap[5016]= new TSCH::PreUFF::ChartAxisNonStyleArchive();
_messageTypeToPrototypeMap[5017]= new TSCH::PreUFF::LegendNonStyleArchive();
_messageTypeToPrototypeMap[5020]= new TSCH::ChartStylePreset();
_messageTypeToPrototypeMap[5021]= new TSCH::ChartDrawableArchive();
_messageTypeToPrototypeMap[5022]= new TSCH::ChartStyleArchive();
_messageTypeToPrototypeMap[5023]= new TSCH::ChartNonStyleArchive();
_messageTypeToPrototypeMap[5024]= new TSCH::LegendStyleArchive();
_messageTypeToPrototypeMap[5025]= new TSCH::LegendNonStyleArchive();
_messageTypeToPrototypeMap[5026]= new TSCH::ChartAxisStyleArchive();
_messageTypeToPrototypeMap[5027]= new TSCH::ChartAxisNonStyleArchive();
_messageTypeToPrototypeMap[5028]= new TSCH::ChartSeriesStyleArchive();
_messageTypeToPrototypeMap[5029]= new TSCH::ChartSeriesNonStyleArchive();
_messageTypeToPrototypeMap[5030]= new TSCH::ReferenceLineStyleArchive();
_messageTypeToPrototypeMap[5031]= new TSCH::ReferenceLineNonStyleArchive();
_messageTypeToPrototypeMap[5103]= new TSCH::CommandSetChartTypeArchive();
_messageTypeToPrototypeMap[5104]= new TSCH::CommandSetSeriesNameArchive();
_messageTypeToPrototypeMap[5105]= new TSCH::CommandSetCategoryNameArchive();
_messageTypeToPrototypeMap[5107]= new TSCH::CommandSetScatterFormatArchive();
_messageTypeToPrototypeMap[5108]= new TSCH::CommandSetLegendFrameArchive();
_messageTypeToPrototypeMap[5109]= new TSCH::CommandSetGridValueArchive();
_messageTypeToPrototypeMap[5110]= new TSCH::CommandSetGridDirectionArchive();
_messageTypeToPrototypeMap[5115]= new TSCH::CommandAddGridRowsArchive();
_messageTypeToPrototypeMap[5116]= new TSCH::CommandAddGridColumnsArchive();
_messageTypeToPrototypeMap[5118]= new TSCH::CommandMoveGridRowsArchive();
_messageTypeToPrototypeMap[5119]= new TSCH::CommandMoveGridColumnsArchive();
_messageTypeToPrototypeMap[5122]= new TSCH::CommandSetPieWedgeExplosion();
_messageTypeToPrototypeMap[5123]= new TSCH::CommandStyleSwapArchive();
_messageTypeToPrototypeMap[5125]= new TSCH::CommandChartApplyPreset();
_messageTypeToPrototypeMap[5126]= new TSCH::ChartCommandArchive();
_messageTypeToPrototypeMap[5127]= new TSCH::CommandReplaceGridValuesArchive();
_messageTypeToPrototypeMap[5129]= new TSCH::StylePasteboardDataArchive();
_messageTypeToPrototypeMap[5130]= new TSCH::CommandSetMultiDataSetIndexArchive();
_messageTypeToPrototypeMap[5131]= new TSCH::CommandReplaceThemePresetArchive();
_messageTypeToPrototypeMap[5132]= new TSCH::CommandInvalidateWPCaches();
_messageTypeToPrototypeMap[5135]= new TSCH::CommandMutatePropertiesArchive();
_messageTypeToPrototypeMap[5136]= new TSCH::CommandScaleAllTextArchive();
_messageTypeToPrototypeMap[5137]= new TSCH::CommandSetFontFamilyArchive();
_messageTypeToPrototypeMap[5138]= new TSCH::CommandApplyFillSetArchive();
_messageTypeToPrototypeMap[5139]= new TSCH::CommandReplaceCustomFormatArchive();
_messageTypeToPrototypeMap[5140]= new TSCH::CommandAddReferenceLineArchive();
_messageTypeToPrototypeMap[5141]= new TSCH::CommandDeleteReferenceLineArchive();
_messageTypeToPrototypeMap[5142]= new TSCH::CommandDeleteGridColumnsArchive();
_messageTypeToPrototypeMap[5143]= new TSCH::CommandDeleteGridRowsArchive();
_messageTypeToPrototypeMap[5145]= new TSCH::ChartSelectionArchive();
_messageTypeToPrototypeMap[5146]= new TSCH::ChartTextSelectionTransformerArchive();
_messageTypeToPrototypeMap[5147]= new TSCH::ChartSubselectionTransformerArchive();
_messageTypeToPrototypeMap[5148]= new TSCH::ChartDrawableSelectionTransformerArchive();
_messageTypeToPrototypeMap[5149]= new TSCH::ChartSubselectionTransformerHelperArchive();
_messageTypeToPrototypeMap[5150]= new TSCH::ChartRefLineSubselectionTransformerHelperArchive();
_messageTypeToPrototypeMap[5151]= new TSCH::CDESelectionTransformerArchive();
_messageTypeToPrototypeMap[5152]= new TSCH::ChartSubselectionIdentityTransformerHelperArchive();
_messageTypeToPrototypeMap[5154]= new TSCH::CommandPasteStyleArchive();
_messageTypeToPrototypeMap[5155]= new TSCH::CommandInducedReplaceChartGrid();
_messageTypeToPrototypeMap[5156]= new TSCH::CommandReplaceImageDataArchive();
_messageTypeToPrototypeMap[6000]= new TST::TableInfoArchive();
_messageTypeToPrototypeMap[6001]= new TST::TableModelArchive();
_messageTypeToPrototypeMap[6002]= new TST::Tile();
_messageTypeToPrototypeMap[6003]= new TST::TableStyleArchive();
_messageTypeToPrototypeMap[6004]= new TST::CellStyleArchive();
_messageTypeToPrototypeMap[6005]= new TST::TableDataList();
_messageTypeToPrototypeMap[6006]= new TST::HeaderStorageBucket();
_messageTypeToPrototypeMap[6007]= new TST::WPTableInfoArchive();
_messageTypeToPrototypeMap[6008]= new TST::TableStylePresetArchive();
_messageTypeToPrototypeMap[6009]= new TST::TableStrokePresetArchive();
_messageTypeToPrototypeMap[6010]= new TST::ConditionalStyleSetArchive();
_messageTypeToPrototypeMap[6011]= new TST::TableDataListSegment();
_messageTypeToPrototypeMap[6030]= new TST::SelectionArchive();
_messageTypeToPrototypeMap[6031]= new TST::CellMapArchive();
_messageTypeToPrototypeMap[6032]= new TST::DeathhawkRdar39989167CellSelectionArchive();
_messageTypeToPrototypeMap[6033]= new TST::ConcurrentCellMapArchive();
_messageTypeToPrototypeMap[6034]= new TST::ConcurrentCellListArchive();
_messageTypeToPrototypeMap[6100]= new TST::TableCommandArchive();
_messageTypeToPrototypeMap[6101]= new TST::CommandDeleteCellsArchive();
_messageTypeToPrototypeMap[6102]= new TST::CommandInsertColumnsOrRowsArchive();
_messageTypeToPrototypeMap[6103]= new TST::CommandRemoveColumnsOrRowsArchive();
_messageTypeToPrototypeMap[6104]= new TST::CommandResizeColumnOrRowArchive();
_messageTypeToPrototypeMap[6107]= new TST::CommandSetTableNameArchive();
_messageTypeToPrototypeMap[6111]= new TST::CommandChangeFreezeHeaderStateArchive();
_messageTypeToPrototypeMap[6114]= new TST::CommandSetTableNameEnabledArchive();
_messageTypeToPrototypeMap[6117]= new TST::CommandApplyTableStylePresetArchive();
_messageTypeToPrototypeMap[6120]= new TST::CommandSetRepeatingHeaderEnabledArchive();
_messageTypeToPrototypeMap[6123]= new TST::CommandSortArchive();
_messageTypeToPrototypeMap[6125]= new TST::CommandStyleTableArchive();
_messageTypeToPrototypeMap[6126]= new TST::CommandSetNumberOfDecimalPlacesArchive();
_messageTypeToPrototypeMap[6127]= new TST::CommandSetShowThousandsSeparatorArchive();
_messageTypeToPrototypeMap[6128]= new TST::CommandSetNegativeNumberStyleArchive();
_messageTypeToPrototypeMap[6129]= new TST::CommandSetFractionAccuracyArchive();
_messageTypeToPrototypeMap[6131]= new TST::CommandSetCurrencyCodeArchive();
_messageTypeToPrototypeMap[6132]= new TST::CommandSetUseAccountingStyleArchive();
_messageTypeToPrototypeMap[6136]= new TST::CommandSetTableFontNameArchive();
_messageTypeToPrototypeMap[6137]= new TST::CommandSetTableFontSizeArchive();
_messageTypeToPrototypeMap[6142]= new TST::CommandSetTableNameHeightArchive();
_messageTypeToPrototypeMap[6144]= new TST::MergeRegionMapArchive();
_messageTypeToPrototypeMap[6145]= new TST::CommandHideShowArchive();
_messageTypeToPrototypeMap[6146]= new TST::CommandSetBaseArchive();
_messageTypeToPrototypeMap[6147]= new TST::CommandSetBasePlacesArchive();
_messageTypeToPrototypeMap[6148]= new TST::CommandSetBaseUseMinusSignArchive();
_messageTypeToPrototypeMap[6149]= new TST::CommandSetTextStylePropertiesArchive();
_messageTypeToPrototypeMap[6150]= new TST::CommandCategoryChangeSummaryAggregateType();
_messageTypeToPrototypeMap[6152]= new TST::CommandCategoryResizeColumnOrRowArchive();
_messageTypeToPrototypeMap[6153]= new TST::CommandCategoryMoveRowsArchive();
_messageTypeToPrototypeMap[6156]= new TST::CommandSetPencilAnnotationsArchive();
_messageTypeToPrototypeMap[6157]= new TST::CommandCategoryWillChangeGroupValue();
_messageTypeToPrototypeMap[6158]= new TST::CommandApplyConcurrentCellMapArchive();
_messageTypeToPrototypeMap[6179]= new TST::FormulaEqualsTokenAttachmentArchive();
_messageTypeToPrototypeMap[6181]= new TST::TokenAttachmentArchive();
_messageTypeToPrototypeMap[6182]= new TST::ExpressionNodeArchive();
_messageTypeToPrototypeMap[6183]= new TST::BooleanNodeArchive();
_messageTypeToPrototypeMap[6184]= new TST::NumberNodeArchive();
_messageTypeToPrototypeMap[6185]= new TST::StringNodeArchive();
_messageTypeToPrototypeMap[6186]= new TST::ArrayNodeArchive();
_messageTypeToPrototypeMap[6187]= new TST::ListNodeArchive();
_messageTypeToPrototypeMap[6188]= new TST::OperatorNodeArchive();
_messageTypeToPrototypeMap[6189]= new TST::FunctionNodeArchive();
_messageTypeToPrototypeMap[6190]= new TST::DateNodeArchive();
_messageTypeToPrototypeMap[6191]= new TST::ReferenceNodeArchive();
_messageTypeToPrototypeMap[6192]= new TST::DurationNodeArchive();
_messageTypeToPrototypeMap[6193]= new TST::ArgumentPlaceholderNodeArchive();
_messageTypeToPrototypeMap[6194]= new TST::PostfixOperatorNodeArchive();
_messageTypeToPrototypeMap[6195]= new TST::PrefixOperatorNodeArchive();
_messageTypeToPrototypeMap[6196]= new TST::FunctionEndNodeArchive();
_messageTypeToPrototypeMap[6197]= new TST::EmptyExpressionNodeArchive();
_messageTypeToPrototypeMap[6198]= new TST::LayoutHintArchive();
_messageTypeToPrototypeMap[6199]= new TST::CompletionTokenAttachmentArchive();
_messageTypeToPrototypeMap[6201]= new TST::TableDataList();
_messageTypeToPrototypeMap[6204]= new TST::HiddenStateFormulaOwnerArchive();
_messageTypeToPrototypeMap[6205]= new TST::CommandSetAutomaticDurationUnitsArchive();
_messageTypeToPrototypeMap[6206]= new TST::PopUpMenuModel();
_messageTypeToPrototypeMap[6218]= new TST::RichTextPayloadArchive();
_messageTypeToPrototypeMap[6220]= new TST::FilterSetArchive();
_messageTypeToPrototypeMap[6221]= new TST::CommandSetFiltersEnabledArchive();
_messageTypeToPrototypeMap[6224]= new TST::CommandRewriteFilterFormulasForTableResizeArchive();
_messageTypeToPrototypeMap[6226]= new TST::CommandTextPreflightInsertCellArchive();
_messageTypeToPrototypeMap[6228]= new TST::CommandDeleteCellContentsArchive();
_messageTypeToPrototypeMap[6229]= new TST::CommandPostflightSetCellArchive();
_messageTypeToPrototypeMap[6235]= new TST::IdentifierNodeArchive();
_messageTypeToPrototypeMap[6238]= new TST::CommandSetDateTimeFormatArchive();
_messageTypeToPrototypeMap[6239]= new TST::TableCommandSelectionBehaviorArchive();
_messageTypeToPrototypeMap[6244]= new TST::CommandApplyCellCommentArchive();
_messageTypeToPrototypeMap[6246]= new TST::CommandSetFormulaTokenizationArchive();
_messageTypeToPrototypeMap[6247]= new TST::TableStyleNetworkArchive();
_messageTypeToPrototypeMap[6250]= new TST::CommandSetFilterSetTypeArchive();
_messageTypeToPrototypeMap[6255]= new TST::CommandSetTextStyleArchive();
_messageTypeToPrototypeMap[6256]= new TST::CommandJustForNotifyingArchive();
_messageTypeToPrototypeMap[6258]= new TST::CommandSetSortOrderArchive();
_messageTypeToPrototypeMap[6262]= new TST::CommandAddTableStylePresetArchive();
_messageTypeToPrototypeMap[6264]= new TST::CellDiffMapArchive();
_messageTypeToPrototypeMap[6265]= new TST::CommandApplyCellContentsArchive();
_messageTypeToPrototypeMap[6266]= new TST::CommandRemoveTableStylePresetArchive();
_messageTypeToPrototypeMap[6267]= new TST::ColumnRowUIDMapArchive();
_messageTypeToPrototypeMap[6268]= new TST::CommandMoveColumnsOrRowsArchive();
_messageTypeToPrototypeMap[6269]= new TST::CommandReplaceCustomFormatArchive();
_messageTypeToPrototypeMap[6270]= new TST::CommandReplaceTableStylePresetArchive();
_messageTypeToPrototypeMap[6271]= new TST::FormulaSelectionArchive();
_messageTypeToPrototypeMap[6273]= new TST::CellListArchive();
_messageTypeToPrototypeMap[6275]= new TST::CommandApplyCellDiffMapArchive();
_messageTypeToPrototypeMap[6276]= new TST::CommandSetFilterSetArchive();
_messageTypeToPrototypeMap[6277]= new TST::CommandMutateCellFormatArchive();
_messageTypeToPrototypeMap[6278]= new TST::CommandSetStorageLanguageArchive();
_messageTypeToPrototypeMap[6280]= new TST::CommandMergeArchive();
_messageTypeToPrototypeMap[6281]= new TST::CommandUnmergeArchive();
_messageTypeToPrototypeMap[6282]= new TST::CommandApplyCellMapArchive();
_messageTypeToPrototypeMap[6283]= new TST::ControlCellSelectionArchive();
_messageTypeToPrototypeMap[6284]= new TST::TableNameSelectionArchive();
_messageTypeToPrototypeMap[6285]= new TST::CommandRewriteFormulasForTransposeArchive();
_messageTypeToPrototypeMap[6287]= new TST::CommandTransposeTableArchive();
_messageTypeToPrototypeMap[6289]= new TST::CommandSetDurationStyleArchive();
_messageTypeToPrototypeMap[6290]= new TST::CommandSetDurationUnitSmallestLargestArchive();
_messageTypeToPrototypeMap[6291]= new TST::CommandRewriteTableFormulasForRewriteSpecArchive();
_messageTypeToPrototypeMap[6292]= new TST::CommandRewriteConditionalStylesForRewriteSpecArchive();
_messageTypeToPrototypeMap[6293]= new TST::CommandRewriteFilterFormulasForRewriteSpecArchive();
_messageTypeToPrototypeMap[6294]= new TST::CommandRewriteSortOrderForRewriteSpecArchive();
_messageTypeToPrototypeMap[6295]= new TST::StrokeSelectionArchive();
_messageTypeToPrototypeMap[6297]= new TST::LetNodeArchive();
_messageTypeToPrototypeMap[6298]= new TST::VariableNodeArchive();
_messageTypeToPrototypeMap[6299]= new TST::InNodeArchive();
_messageTypeToPrototypeMap[6300]= new TST::CommandInverseMergeArchive();
_messageTypeToPrototypeMap[6301]= new TST::CommandMoveCellsArchive();
_messageTypeToPrototypeMap[6302]= new TST::DefaultCellStylesContainerArchive();
_messageTypeToPrototypeMap[6303]= new TST::CommandRewriteMergeFormulasArchive();
_messageTypeToPrototypeMap[6304]= new TST::CommandChangeTableAreaForColumnOrRowArchive();
_messageTypeToPrototypeMap[6305]= new TST::StrokeSidecarArchive();
_messageTypeToPrototypeMap[6306]= new TST::StrokeLayerArchive();
_messageTypeToPrototypeMap[6307]= new TST::CommandChooseTableIdRemapperArchive();
_messageTypeToPrototypeMap[6310]= new TST::CommandSetWasCutArchive();
_messageTypeToPrototypeMap[6311]= new TST::AutofillSelectionArchive();
_messageTypeToPrototypeMap[6312]= new TST::StockCellSelectionArchive();
_messageTypeToPrototypeMap[6313]= new TST::CommandSetNowArchive();
_messageTypeToPrototypeMap[6314]= new TST::CommandSetStructuredTextImportRecordArchive();
_messageTypeToPrototypeMap[6315]= new TST::CommandRewriteCategoryFormulasArchive();
_messageTypeToPrototypeMap[6316]= new TST::SummaryModelArchive();
_messageTypeToPrototypeMap[6317]= new TST::SummaryCellVendorArchive();
_messageTypeToPrototypeMap[6318]= new TST::CategoryOrderArchive();
_messageTypeToPrototypeMap[6320]= new TST::CommandCategoryCollapseExpandGroupArchive();
_messageTypeToPrototypeMap[6321]= new TST::CommandCategorySetGroupingColumnsArchive();
_messageTypeToPrototypeMap[6323]= new TST::CommandRewriteHiddenStatesForGroupByChangeArchive();
_messageTypeToPrototypeMap[6350]= new TST::IdempotentSelectionTransformerArchive();
_messageTypeToPrototypeMap[6351]= new TST::TableSubSelectionTransformerBaseArchive();
_messageTypeToPrototypeMap[6352]= new TST::TableNameSelectionTransformerArchive();
_messageTypeToPrototypeMap[6353]= new TST::RegionSelectionTransformerArchive();
_messageTypeToPrototypeMap[6354]= new TST::RowColumnSelectionTransformerArchive();
_messageTypeToPrototypeMap[6355]= new TST::ControlCellSelectionTransformerArchive();
_messageTypeToPrototypeMap[6357]= new TST::ChangePropagationMapWrapper();
_messageTypeToPrototypeMap[6358]= new TST::WPSelectionTransformerArchive();
_messageTypeToPrototypeMap[6359]= new TST::StockCellSelectionTransformerArchive();
_messageTypeToPrototypeMap[6360]= new TST::CommandSetRangeControlMinMaxIncArchive();
_messageTypeToPrototypeMap[6361]= new TST::CommandCategorySetLabelRowVisibility();
_messageTypeToPrototypeMap[6362]= new TST::CommandRewritePencilAnnotationFormulasArchive();
_messageTypeToPrototypeMap[6363]= new TST::PencilAnnotationArchive();
_messageTypeToPrototypeMap[6364]= new TST::StrokeSelectionTransformerArchive();
_messageTypeToPrototypeMap[6365]= new TST::HeaderNameMgrTileArchive();
_messageTypeToPrototypeMap[6366]= new TST::HeaderNameMgrArchive();
_messageTypeToPrototypeMap[6367]= new TST::CellDiffArray();
_messageTypeToPrototypeMap[6368]= new TST::CellDiffArraySegment();
_messageTypeToPrototypeMap[10020]= new TSWP::ShapeSelectionTransformerArchive();
_messageTypeToPrototypeMap[10021]= new TSWP::SelectionTransformerArchive();
_messageTypeToPrototypeMap[10022]= new TSWP::ShapeContentDescription();
_messageTypeToPrototypeMap[10023]= new TSWP::TateChuYokoFieldArchive();
_messageTypeToPrototypeMap[10024]= new TSWP::DropCapStyleArchive();
_messageTypeToPrototypeMap[11000]= new TSP::PasteboardObject();
_messageTypeToPrototypeMap[11006]= new TSP::PackageMetadata();
_messageTypeToPrototypeMap[11007]= new TSP::PasteboardMetadata();
_messageTypeToPrototypeMap[11008]= new TSP::ObjectContainer();
_messageTypeToPrototypeMap[11009]= new TSP::ViewStateMetadata();
_messageTypeToPrototypeMap[11010]= new TSP::ObjectCollection();
_messageTypeToPrototypeMap[11011]= new TSP::DocumentMetadata();
_messageTypeToPrototypeMap[11012]= new TSP::SupportMetadata();
_messageTypeToPrototypeMap[11013]= new TSP::ObjectSerializationMetadata();
_messageTypeToPrototypeMap[11014]= new TSP::DataMetadata();
_messageTypeToPrototypeMap[11015]= new TSP::DataMetadataMap();
_messageTypeToPrototypeMap[11016]= new TSP::LargeNumberArraySegment();
_messageTypeToPrototypeMap[11017]= new TSP::LargeStringArraySegment();
_messageTypeToPrototypeMap[11018]= new TSP::LargeLazyObjectArraySegment();
_messageTypeToPrototypeMap[11019]= new TSP::LargeNumberArray();
_messageTypeToPrototypeMap[11020]= new TSP::LargeStringArray();
_messageTypeToPrototypeMap[11021]= new TSP::LargeLazyObjectArray();
_messageTypeToPrototypeMap[11024]= new TSP::LargeUUIDArraySegment();
_messageTypeToPrototypeMap[11025]= new TSP::LargeUUIDArray();
_messageTypeToPrototypeMap[11026]= new TSP::LargeObjectArraySegment();
_messageTypeToPrototypeMap[11027]= new TSP::LargeObjectArray();
}
| 74.292845
| 114
| 0.838343
|
eth-siplab
|
3bf431893357d5412ea6d49dc7c6445247413980
| 255
|
cpp
|
C++
|
11_variadic_templates/11_02_pack_expansion/11_02_03_inheritance.cpp
|
pAbogn/cpp_courses
|
6ffa7da5cc440af3327139a38cfdefcfaae1ebed
|
[
"MIT"
] | 13
|
2020-09-01T14:57:21.000Z
|
2021-11-24T06:00:26.000Z
|
11_variadic_templates/11_02_pack_expansion/11_02_03_inheritance.cpp
|
pAbogn/cpp_courses
|
6ffa7da5cc440af3327139a38cfdefcfaae1ebed
|
[
"MIT"
] | 5
|
2020-06-11T14:13:00.000Z
|
2021-07-14T05:27:53.000Z
|
11_variadic_templates/11_02_pack_expansion/11_02_03_inheritance.cpp
|
pAbogn/cpp_courses
|
6ffa7da5cc440af3327139a38cfdefcfaae1ebed
|
[
"MIT"
] | 10
|
2021-03-22T07:54:36.000Z
|
2021-09-15T04:03:32.000Z
|
#include <vector>
template <typename... Bases>
struct Derived : Bases... {};
struct Object {};
struct Widget {};
int main() {
Derived<std::vector<int>, Object, Widget> obj;
// Equivalent to
// Derived : std::vector<int>, Object, Widget
}
| 15.9375
| 50
| 0.627451
|
pAbogn
|
3bf6ee0a38861a1b51a9a2d21cb7ca2d7bf724f4
| 1,155
|
cpp
|
C++
|
test/generated/SequenceOf.cpp
|
Roboauto/fast_ber
|
089d3a2dfb3c8b14da066791f578fbec86dcf6c6
|
[
"BSL-1.0"
] | null | null | null |
test/generated/SequenceOf.cpp
|
Roboauto/fast_ber
|
089d3a2dfb3c8b14da066791f578fbec86dcf6c6
|
[
"BSL-1.0"
] | null | null | null |
test/generated/SequenceOf.cpp
|
Roboauto/fast_ber
|
089d3a2dfb3c8b14da066791f578fbec86dcf6c6
|
[
"BSL-1.0"
] | null | null | null |
#include "autogen/sequence_of.hpp"
#include "catch2/catch.hpp"
#include <array>
TEST_CASE("Sequence Of: Encode and decode sequence of")
{
std::array<uint8_t, 100> buffer = {};
fast_ber::Sequence_::SequenceFive sequence = {fast_ber::Sequence_::UnnamedSet0{{""}}};
fast_ber::EncodeResult encode_result = fast_ber::encode(std::span(buffer.data(), buffer.size()), sequence);
fast_ber::DecodeResult decode_result = fast_ber::decode(std::span(buffer.data(), buffer.size()), sequence);
REQUIRE(encode_result.success);
REQUIRE(decode_result.success);
}
TEST_CASE("Sequence Of: Empty sequence of")
{
std::array<uint8_t, 2> buffer = {};
fast_ber::Sequence_::SequenceFive sequence = {};
size_t encoded_length = fast_ber::encoded_length(sequence);
fast_ber::EncodeResult encode_result = fast_ber::encode(std::span(buffer.data(), buffer.size()), sequence);
fast_ber::DecodeResult decode_result = fast_ber::decode(std::span(buffer.data(), buffer.size()), sequence);
REQUIRE(encoded_length == 2);
REQUIRE(encode_result.success);
REQUIRE(decode_result.success);
}
| 36.09375
| 112
| 0.688312
|
Roboauto
|
3bf745c95b119c5f2068372f1906a1a429a20952
| 45,153
|
cpp
|
C++
|
modules/core/opencl_kernels.cpp
|
stalinizer/opencv
|
baefce5e9edf2fdbc35a2d08a8457fa29cfb6ba2
|
[
"BSD-3-Clause"
] | null | null | null |
modules/core/opencl_kernels.cpp
|
stalinizer/opencv
|
baefce5e9edf2fdbc35a2d08a8457fa29cfb6ba2
|
[
"BSD-3-Clause"
] | null | null | null |
modules/core/opencl_kernels.cpp
|
stalinizer/opencv
|
baefce5e9edf2fdbc35a2d08a8457fa29cfb6ba2
|
[
"BSD-3-Clause"
] | null | null | null |
// This file is auto-generated. Do not edit!
#include "precomp.hpp"
#include "opencl_kernels.hpp"
namespace cv
{
namespace ocl
{
namespace core
{
const struct ProgramEntry arithm={"arithm",
"#ifdef DOUBLE_SUPPORT\n"
"#ifdef cl_amd_fp64\n"
"#pragma OPENCL EXTENSION cl_amd_fp64:enable\n"
"#elif defined cl_khr_fp64\n"
"#pragma OPENCL EXTENSION cl_khr_fp64:enable\n"
"#endif\n"
"#endif\n"
"#if depth <= 5\n"
"#define CV_PI M_PI_F\n"
"#else\n"
"#define CV_PI M_PI\n"
"#endif\n"
"#ifndef cn\n"
"#define cn 1\n"
"#endif\n"
"#if cn == 1\n"
"#undef srcT1_C1\n"
"#undef srcT2_C1\n"
"#undef dstT_C1\n"
"#define srcT1_C1 srcT1\n"
"#define srcT2_C1 srcT2\n"
"#define dstT_C1 dstT\n"
"#endif\n"
"#if cn != 3\n"
"#define storedst(val) *(__global dstT *)(dstptr + dst_index) = val\n"
"#define storedst2(val) *(__global dstT *)(dstptr2 + dst_index2) = val\n"
"#else\n"
"#define storedst(val) vstore3(val, 0, (__global dstT_C1 *)(dstptr + dst_index))\n"
"#define storedst2(val) vstore3(val, 0, (__global dstT_C1 *)(dstptr2 + dst_index2))\n"
"#endif\n"
"#define noconvert\n"
"#ifndef workT\n"
"#ifndef srcT1\n"
"#define srcT1 dstT\n"
"#endif\n"
"#ifndef srcT1_C1\n"
"#define srcT1_C1 dstT_C1\n"
"#endif\n"
"#ifndef srcT2\n"
"#define srcT2 dstT\n"
"#endif\n"
"#ifndef srcT2_C1\n"
"#define srcT2_C1 dstT_C1\n"
"#endif\n"
"#define workT dstT\n"
"#if cn != 3\n"
"#define srcelem1 *(__global srcT1 *)(srcptr1 + src1_index)\n"
"#define srcelem2 *(__global srcT2 *)(srcptr2 + src2_index)\n"
"#else\n"
"#define srcelem1 vload3(0, (__global srcT1_C1 *)(srcptr1 + src1_index))\n"
"#define srcelem2 vload3(0, (__global srcT2_C1 *)(srcptr2 + src2_index))\n"
"#endif\n"
"#ifndef convertToDT\n"
"#define convertToDT noconvert\n"
"#endif\n"
"#else\n"
"#ifndef convertToWT2\n"
"#define convertToWT2 convertToWT1\n"
"#endif\n"
"#if cn != 3\n"
"#define srcelem1 convertToWT1(*(__global srcT1 *)(srcptr1 + src1_index))\n"
"#define srcelem2 convertToWT2(*(__global srcT2 *)(srcptr2 + src2_index))\n"
"#else\n"
"#define srcelem1 convertToWT1(vload3(0, (__global srcT1_C1 *)(srcptr1 + src1_index)))\n"
"#define srcelem2 convertToWT2(vload3(0, (__global srcT2_C1 *)(srcptr2 + src2_index)))\n"
"#endif\n"
"#endif\n"
"#ifndef workST\n"
"#define workST workT\n"
"#endif\n"
"#define EXTRA_PARAMS\n"
"#define EXTRA_INDEX\n"
"#if defined OP_ADD\n"
"#define PROCESS_ELEM storedst(convertToDT(srcelem1 + srcelem2))\n"
"#elif defined OP_SUB\n"
"#define PROCESS_ELEM storedst(convertToDT(srcelem1 - srcelem2))\n"
"#elif defined OP_RSUB\n"
"#define PROCESS_ELEM storedst(convertToDT(srcelem2 - srcelem1))\n"
"#elif defined OP_ABSDIFF\n"
"#define PROCESS_ELEM \\\n"
"workT v = srcelem1 - srcelem2; \\\n"
"storedst(convertToDT(v >= (workT)(0) ? v : -v))\n"
"#elif defined OP_AND\n"
"#define PROCESS_ELEM storedst(srcelem1 & srcelem2)\n"
"#elif defined OP_OR\n"
"#define PROCESS_ELEM storedst(srcelem1 | srcelem2)\n"
"#elif defined OP_XOR\n"
"#define PROCESS_ELEM storedst(srcelem1 ^ srcelem2)\n"
"#elif defined OP_NOT\n"
"#define PROCESS_ELEM storedst(~srcelem1)\n"
"#elif defined OP_MIN\n"
"#define PROCESS_ELEM storedst(min(srcelem1, srcelem2))\n"
"#elif defined OP_MAX\n"
"#define PROCESS_ELEM storedst(max(srcelem1, srcelem2))\n"
"#elif defined OP_MUL\n"
"#define PROCESS_ELEM storedst(convertToDT(srcelem1 * srcelem2))\n"
"#elif defined OP_MUL_SCALE\n"
"#undef EXTRA_PARAMS\n"
"#ifdef UNARY_OP\n"
"#define EXTRA_PARAMS , workST srcelem2_, scaleT scale\n"
"#undef srcelem2\n"
"#define srcelem2 srcelem2_\n"
"#else\n"
"#define EXTRA_PARAMS , scaleT scale\n"
"#endif\n"
"#define PROCESS_ELEM storedst(convertToDT(srcelem1 * scale * srcelem2))\n"
"#elif defined OP_DIV\n"
"#define PROCESS_ELEM \\\n"
"workT e2 = srcelem2, zero = (workT)(0); \\\n"
"storedst(convertToDT(e2 != zero ? srcelem1 / e2 : zero))\n"
"#elif defined OP_DIV_SCALE\n"
"#undef EXTRA_PARAMS\n"
"#ifdef UNARY_OP\n"
"#define EXTRA_PARAMS , workST srcelem2_, scaleT scale\n"
"#undef srcelem2\n"
"#define srcelem2 srcelem2_\n"
"#else\n"
"#define EXTRA_PARAMS , scaleT scale\n"
"#endif\n"
"#define PROCESS_ELEM \\\n"
"workT e2 = srcelem2, zero = (workT)(0); \\\n"
"storedst(convertToDT(e2 == zero ? zero : (srcelem1 * (workT)(scale) / e2)))\n"
"#elif defined OP_RDIV_SCALE\n"
"#undef EXTRA_PARAMS\n"
"#ifdef UNARY_OP\n"
"#define EXTRA_PARAMS , workST srcelem2_, scaleT scale\n"
"#undef srcelem2\n"
"#define srcelem2 srcelem2_\n"
"#else\n"
"#define EXTRA_PARAMS , scaleT scale\n"
"#endif\n"
"#define PROCESS_ELEM \\\n"
"workT e1 = srcelem1, zero = (workT)(0); \\\n"
"storedst(convertToDT(e1 == zero ? zero : (srcelem2 * (workT)(scale) / e1)))\n"
"#elif defined OP_RECIP_SCALE\n"
"#undef EXTRA_PARAMS\n"
"#define EXTRA_PARAMS , scaleT scale\n"
"#define PROCESS_ELEM \\\n"
"workT e1 = srcelem1, zero = (workT)(0); \\\n"
"storedst(convertToDT(e1 != zero ? scale / e1 : zero))\n"
"#elif defined OP_ADDW\n"
"#undef EXTRA_PARAMS\n"
"#define EXTRA_PARAMS , scaleT alpha, scaleT beta, scaleT gamma\n"
"#if wdepth <= 4\n"
"#define PROCESS_ELEM storedst(convertToDT(mad24(srcelem1, alpha, mad24(srcelem2, beta, gamma))))\n"
"#else\n"
"#define PROCESS_ELEM storedst(convertToDT(mad(srcelem1, alpha, mad(srcelem2, beta, gamma))))\n"
"#endif\n"
"#elif defined OP_MAG\n"
"#define PROCESS_ELEM storedst(hypot(srcelem1, srcelem2))\n"
"#elif defined OP_ABS_NOSAT\n"
"#define PROCESS_ELEM \\\n"
"dstT v = convertToDT(srcelem1); \\\n"
"storedst(v >= 0 ? v : -v)\n"
"#elif defined OP_PHASE_RADIANS\n"
"#define PROCESS_ELEM \\\n"
"workT tmp = atan2(srcelem2, srcelem1); \\\n"
"if(tmp < 0) tmp += 6.283185307179586232f; \\\n"
"storedst(tmp)\n"
"#elif defined OP_PHASE_DEGREES\n"
"#define PROCESS_ELEM \\\n"
"workT tmp = atan2(srcelem2, srcelem1)*57.29577951308232286465f; \\\n"
"if(tmp < 0) tmp += 360; \\\n"
"storedst(tmp)\n"
"#elif defined OP_EXP\n"
"#define PROCESS_ELEM storedst(exp(srcelem1))\n"
"#elif defined OP_POW\n"
"#define PROCESS_ELEM storedst(pow(srcelem1, srcelem2))\n"
"#elif defined OP_POWN\n"
"#undef workT\n"
"#define workT int\n"
"#define PROCESS_ELEM storedst(pown(srcelem1, srcelem2))\n"
"#elif defined OP_SQRT\n"
"#define PROCESS_ELEM storedst(sqrt(srcelem1))\n"
"#elif defined OP_LOG\n"
"#define PROCESS_ELEM \\\n"
"dstT v = (dstT)(srcelem1);\\\n"
"storedst(v > (dstT)(0) ? log(v) : log(-v))\n"
"#elif defined OP_CMP\n"
"#define srcT2 srcT1\n"
"#ifndef convertToWT1\n"
"#define convertToWT1\n"
"#endif\n"
"#define PROCESS_ELEM \\\n"
"workT __s1 = srcelem1; \\\n"
"workT __s2 = srcelem2; \\\n"
"storedst(((__s1 CMP_OPERATOR __s2) ? (dstT)(255) : (dstT)(0)))\n"
"#elif defined OP_CONVERT_SCALE_ABS\n"
"#undef EXTRA_PARAMS\n"
"#define EXTRA_PARAMS , workT1 alpha, workT1 beta\n"
"#if wdepth <= 4\n"
"#define PROCESS_ELEM \\\n"
"workT value = mad24(srcelem1, (workT)(alpha), (workT)(beta)); \\\n"
"storedst(convertToDT(value >= 0 ? value : -value))\n"
"#else\n"
"#define PROCESS_ELEM \\\n"
"workT value = mad(srcelem1, (workT)(alpha), (workT)(beta)); \\\n"
"storedst(convertToDT(value >= 0 ? value : -value))\n"
"#endif\n"
"#elif defined OP_SCALE_ADD\n"
"#undef EXTRA_PARAMS\n"
"#define EXTRA_PARAMS , workT1 alpha\n"
"#if wdepth <= 4\n"
"#define PROCESS_ELEM storedst(convertToDT(mad24(srcelem1, (workT)(alpha), srcelem2)))\n"
"#else\n"
"#define PROCESS_ELEM storedst(convertToDT(mad(srcelem1, (workT)(alpha), srcelem2)))\n"
"#endif\n"
"#elif defined OP_CTP_AD || defined OP_CTP_AR\n"
"#if depth <= 5\n"
"#define CV_EPSILON FLT_EPSILON\n"
"#else\n"
"#define CV_EPSILON DBL_EPSILON\n"
"#endif\n"
"#ifdef OP_CTP_AD\n"
"#define TO_DEGREE cartToPolar *= (180 / CV_PI);\n"
"#elif defined OP_CTP_AR\n"
"#define TO_DEGREE\n"
"#endif\n"
"#define PROCESS_ELEM \\\n"
"dstT x = srcelem1, y = srcelem2; \\\n"
"dstT x2 = x * x, y2 = y * y; \\\n"
"dstT magnitude = sqrt(x2 + y2); \\\n"
"dstT tmp = y >= 0 ? 0 : CV_PI * 2; \\\n"
"tmp = x < 0 ? CV_PI : tmp; \\\n"
"dstT tmp1 = y >= 0 ? CV_PI * 0.5f : CV_PI * 1.5f; \\\n"
"dstT cartToPolar = y2 <= x2 ? x * y / mad((dstT)(0.28f), y2, x2 + CV_EPSILON) + tmp : (tmp1 - x * y / mad((dstT)(0.28f), x2, y2 + CV_EPSILON)); \\\n"
"TO_DEGREE \\\n"
"storedst(magnitude); \\\n"
"storedst2(cartToPolar)\n"
"#elif defined OP_PTC_AD || defined OP_PTC_AR\n"
"#ifdef OP_PTC_AD\n"
"#define FROM_DEGREE \\\n"
"dstT ascale = CV_PI/180.0f; \\\n"
"dstT alpha = y * ascale\n"
"#else\n"
"#define FROM_DEGREE \\\n"
"dstT alpha = y\n"
"#endif\n"
"#define PROCESS_ELEM \\\n"
"dstT x = srcelem1, y = srcelem2; \\\n"
"FROM_DEGREE; \\\n"
"storedst(cos(alpha) * x); \\\n"
"storedst2(sin(alpha) * x)\n"
"#elif defined OP_PATCH_NANS\n"
"#undef EXTRA_PARAMS\n"
"#define EXTRA_PARAMS , int val\n"
"#define PROCESS_ELEM \\\n"
"if (( srcelem1 & 0x7fffffff) > 0x7f800000 ) \\\n"
"storedst(val)\n"
"#else\n"
"#error \"unknown op type\"\n"
"#endif\n"
"#if defined OP_CTP_AD || defined OP_CTP_AR || defined OP_PTC_AD || defined OP_PTC_AR\n"
"#undef EXTRA_PARAMS\n"
"#define EXTRA_PARAMS , __global uchar* dstptr2, int dststep2, int dstoffset2\n"
"#undef EXTRA_INDEX\n"
"#define EXTRA_INDEX int dst_index2 = mad24(y, dststep2, mad24(x, (int)sizeof(dstT_C1) * cn, dstoffset2))\n"
"#endif\n"
"#if defined UNARY_OP || defined MASK_UNARY_OP\n"
"#if defined OP_AND || defined OP_OR || defined OP_XOR || defined OP_ADD || defined OP_SAT_ADD || \\\n"
"defined OP_SUB || defined OP_SAT_SUB || defined OP_RSUB || defined OP_SAT_RSUB || \\\n"
"defined OP_ABSDIFF || defined OP_CMP || defined OP_MIN || defined OP_MAX || defined OP_POW || \\\n"
"defined OP_MUL || defined OP_DIV || defined OP_POWN\n"
"#undef EXTRA_PARAMS\n"
"#define EXTRA_PARAMS , workST srcelem2_\n"
"#undef srcelem2\n"
"#define srcelem2 srcelem2_\n"
"#endif\n"
"#if cn == 3\n"
"#undef srcelem2\n"
"#define srcelem2 (workT)(srcelem2_.x, srcelem2_.y, srcelem2_.z)\n"
"#endif\n"
"#endif\n"
"#if defined BINARY_OP\n"
"__kernel void KF(__global const uchar * srcptr1, int srcstep1, int srcoffset1,\n"
"__global const uchar * srcptr2, int srcstep2, int srcoffset2,\n"
"__global uchar * dstptr, int dststep, int dstoffset,\n"
"int rows, int cols EXTRA_PARAMS )\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < cols && y < rows)\n"
"{\n"
"int src1_index = mad24(y, srcstep1, mad24(x, (int)sizeof(srcT1_C1) * cn, srcoffset1));\n"
"#if !(defined(OP_RECIP_SCALE) || defined(OP_NOT))\n"
"int src2_index = mad24(y, srcstep2, mad24(x, (int)sizeof(srcT2_C1) * cn, srcoffset2));\n"
"#endif\n"
"int dst_index = mad24(y, dststep, mad24(x, (int)sizeof(dstT_C1) * cn, dstoffset));\n"
"EXTRA_INDEX;\n"
"PROCESS_ELEM;\n"
"}\n"
"}\n"
"#elif defined MASK_BINARY_OP\n"
"__kernel void KF(__global const uchar * srcptr1, int srcstep1, int srcoffset1,\n"
"__global const uchar * srcptr2, int srcstep2, int srcoffset2,\n"
"__global const uchar * mask, int maskstep, int maskoffset,\n"
"__global uchar * dstptr, int dststep, int dstoffset,\n"
"int rows, int cols EXTRA_PARAMS )\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < cols && y < rows)\n"
"{\n"
"int mask_index = mad24(y, maskstep, x + maskoffset);\n"
"if( mask[mask_index] )\n"
"{\n"
"int src1_index = mad24(y, srcstep1, mad24(x, (int)sizeof(srcT1_C1) * cn, srcoffset1));\n"
"int src2_index = mad24(y, srcstep2, mad24(x, (int)sizeof(srcT2_C1) * cn, srcoffset2));\n"
"int dst_index = mad24(y, dststep, mad24(x, (int)sizeof(dstT_C1) * cn, dstoffset));\n"
"PROCESS_ELEM;\n"
"}\n"
"}\n"
"}\n"
"#elif defined UNARY_OP\n"
"__kernel void KF(__global const uchar * srcptr1, int srcstep1, int srcoffset1,\n"
"__global uchar * dstptr, int dststep, int dstoffset,\n"
"int rows, int cols EXTRA_PARAMS )\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < cols && y < rows)\n"
"{\n"
"int src1_index = mad24(y, srcstep1, mad24(x, (int)sizeof(srcT1_C1) * cn, srcoffset1));\n"
"int dst_index = mad24(y, dststep, mad24(x, (int)sizeof(dstT_C1) * cn, dstoffset));\n"
"PROCESS_ELEM;\n"
"}\n"
"}\n"
"#elif defined MASK_UNARY_OP\n"
"__kernel void KF(__global const uchar * srcptr1, int srcstep1, int srcoffset1,\n"
"__global const uchar * mask, int maskstep, int maskoffset,\n"
"__global uchar * dstptr, int dststep, int dstoffset,\n"
"int rows, int cols EXTRA_PARAMS )\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < cols && y < rows)\n"
"{\n"
"int mask_index = mad24(y, maskstep, x + maskoffset);\n"
"if( mask[mask_index] )\n"
"{\n"
"int src1_index = mad24(y, srcstep1, mad24(x, (int)sizeof(srcT1_C1) * cn, srcoffset1));\n"
"int dst_index = mad24(y, dststep, mad24(x, (int)sizeof(dstT_C1) * cn, dstoffset));\n"
"PROCESS_ELEM;\n"
"}\n"
"}\n"
"}\n"
"#else\n"
"#error \"Unknown operation type\"\n"
"#endif\n"
, "7b756ec5d7cb050293373f8e2b237901"};
ProgramSource arithm_oclsrc(arithm.programStr);
const struct ProgramEntry convert={"convert",
"#ifdef DOUBLE_SUPPORT\n"
"#ifdef cl_amd_fp64\n"
"#pragma OPENCL EXTENSION cl_amd_fp64:enable\n"
"#elif defined (cl_khr_fp64)\n"
"#pragma OPENCL EXTENSION cl_khr_fp64:enable\n"
"#endif\n"
"#endif\n"
"#define noconvert\n"
"__kernel void convertTo(__global const uchar * srcptr, int src_step, int src_offset,\n"
"__global uchar * dstptr, int dst_step, int dst_offset, int dst_rows, int dst_cols,\n"
"WT alpha, WT beta)\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < dst_cols && y < dst_rows)\n"
"{\n"
"int src_index = mad24(y, src_step, mad24(x, (int)sizeof(srcT), src_offset));\n"
"int dst_index = mad24(y, dst_step, mad24(x, (int)sizeof(dstT), dst_offset));\n"
"__global const srcT * src = (__global const srcT *)(srcptr + src_index);\n"
"__global dstT * dst = (__global dstT *)(dstptr + dst_index);\n"
"dst[0] = convertToDT(mad(convertToWT(src[0]), alpha, beta));\n"
"}\n"
"}\n"
, "0acb6f5cc70a98d14932ec11acf43e21"};
ProgramSource convert_oclsrc(convert.programStr);
const struct ProgramEntry copymakeborder={"copymakeborder",
"#ifdef DOUBLE_SUPPORT\n"
"#ifdef cl_amd_fp64\n"
"#pragma OPENCL EXTENSION cl_amd_fp64:enable\n"
"#elif defined (cl_khr_fp64)\n"
"#pragma OPENCL EXTENSION cl_khr_fp64:enable\n"
"#endif\n"
"#endif\n"
"#if cn != 3\n"
"#define loadpix(addr) *(__global const T*)(addr)\n"
"#define storepix(val, addr) *(__global T*)(addr) = val\n"
"#define TSIZE ((int)sizeof(T))\n"
"#define convertScalar(a) (a)\n"
"#else\n"
"#define loadpix(addr) vload3(0, (__global const T1*)(addr))\n"
"#define storepix(val, addr) vstore3(val, 0, (__global T1*)(addr))\n"
"#define TSIZE ((int)sizeof(T1)*3)\n"
"#define convertScalar(a) (T)(a.x, a.y, a.z)\n"
"#endif\n"
"#ifdef BORDER_CONSTANT\n"
"#define EXTRAPOLATE(x, y, v) v = scalar;\n"
"#elif defined BORDER_REPLICATE\n"
"#define EXTRAPOLATE(x, y, v) \\\n"
"{ \\\n"
"x = clamp(x, 0, src_cols - 1); \\\n"
"y = clamp(y, 0, src_rows - 1); \\\n"
"v = loadpix(srcptr + mad24(y, src_step, mad24(x, TSIZE, src_offset))); \\\n"
"}\n"
"#elif defined BORDER_WRAP\n"
"#define EXTRAPOLATE(x, y, v) \\\n"
"{ \\\n"
"if (x < 0) \\\n"
"x -= ((x - src_cols + 1) / src_cols) * src_cols; \\\n"
"if (x >= src_cols) \\\n"
"x %= src_cols; \\\n"
"\\\n"
"if (y < 0) \\\n"
"y -= ((y - src_rows + 1) / src_rows) * src_rows; \\\n"
"if( y >= src_rows ) \\\n"
"y %= src_rows; \\\n"
"v = loadpix(srcptr + mad24(y, src_step, mad24(x, TSIZE, src_offset))); \\\n"
"}\n"
"#elif defined(BORDER_REFLECT) || defined(BORDER_REFLECT_101)\n"
"#ifdef BORDER_REFLECT\n"
"#define DELTA int delta = 0\n"
"#else\n"
"#define DELTA int delta = 1\n"
"#endif\n"
"#define EXTRAPOLATE(x, y, v) \\\n"
"{ \\\n"
"DELTA; \\\n"
"if (src_cols == 1) \\\n"
"x = 0; \\\n"
"else \\\n"
"do \\\n"
"{ \\\n"
"if( x < 0 ) \\\n"
"x = -x - 1 + delta; \\\n"
"else \\\n"
"x = src_cols - 1 - (x - src_cols) - delta; \\\n"
"} \\\n"
"while (x >= src_cols || x < 0); \\\n"
"\\\n"
"if (src_rows == 1) \\\n"
"y = 0; \\\n"
"else \\\n"
"do \\\n"
"{ \\\n"
"if( y < 0 ) \\\n"
"y = -y - 1 + delta; \\\n"
"else \\\n"
"y = src_rows - 1 - (y - src_rows) - delta; \\\n"
"} \\\n"
"while (y >= src_rows || y < 0); \\\n"
"v = loadpix(srcptr + mad24(y, src_step, mad24(x, TSIZE, src_offset))); \\\n"
"}\n"
"#else\n"
"#error No extrapolation method\n"
"#endif\n"
"#define NEED_EXTRAPOLATION(gx, gy) (gx >= src_cols || gy >= src_rows || gx < 0 || gy < 0)\n"
"__kernel void copyMakeBorder(__global const uchar * srcptr, int src_step, int src_offset, int src_rows, int src_cols,\n"
"__global uchar * dstptr, int dst_step, int dst_offset, int dst_rows, int dst_cols,\n"
"int top, int left, ST nVal)\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"#ifdef BORDER_CONSTANT\n"
"T scalar = convertScalar(nVal);\n"
"#endif\n"
"if (x < dst_cols && y < dst_rows)\n"
"{\n"
"int src_x = x - left;\n"
"int src_y = y - top;\n"
"int dst_index = mad24(y, dst_step, mad24(x, (int)TSIZE, dst_offset));\n"
"__global T * dst = (__global T *)(dstptr + dst_index);\n"
"T v;\n"
"if (NEED_EXTRAPOLATION(src_x, src_y))\n"
"{\n"
"EXTRAPOLATE(src_x, src_y, v)\n"
"}\n"
"else\n"
"{\n"
"int src_index = mad24(src_y, src_step, mad24(src_x, TSIZE, src_offset));\n"
"v = loadpix(srcptr + src_index);\n"
"}\n"
"storepix(v, dst);\n"
"}\n"
"}\n"
, "bd493b7fa2197165f144292f04f6c07d"};
ProgramSource copymakeborder_oclsrc(copymakeborder.programStr);
const struct ProgramEntry copyset={"copyset",
"#ifdef COPY_TO_MASK\n"
"#define DEFINE_DATA \\\n"
"int src_index = mad24(y, src_step, mad24(x, (int)sizeof(T) * scn, src_offset)); \\\n"
"int dst_index = mad24(y, dst_step, mad24(x, (int)sizeof(T) * scn, dst_offset)); \\\n"
"\\\n"
"__global const T * src = (__global const T *)(srcptr + src_index); \\\n"
"__global T * dst = (__global T *)(dstptr + dst_index)\n"
"__kernel void copyToMask(__global const uchar * srcptr, int src_step, int src_offset,\n"
"__global const uchar * maskptr, int mask_step, int mask_offset,\n"
"__global uchar * dstptr, int dst_step, int dst_offset,\n"
"int dst_rows, int dst_cols)\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < dst_cols && y < dst_rows)\n"
"{\n"
"int mask_index = mad24(y, mask_step, mad24(x, mcn, mask_offset));\n"
"__global const uchar * mask = (__global const uchar *)(maskptr + mask_index);\n"
"#if mcn == 1\n"
"if (mask[0])\n"
"{\n"
"DEFINE_DATA;\n"
"#pragma unroll\n"
"for (int c = 0; c < scn; ++c)\n"
"dst[c] = src[c];\n"
"}\n"
"#elif scn == mcn\n"
"DEFINE_DATA;\n"
"#pragma unroll\n"
"for (int c = 0; c < scn; ++c)\n"
"if (mask[c])\n"
"dst[c] = src[c];\n"
"#else\n"
"#error \"(mcn == 1 || mcn == scn) should be true\"\n"
"#endif\n"
"}\n"
"}\n"
"#else\n"
"#ifndef dstST\n"
"#define dstST dstT\n"
"#endif\n"
"#if cn != 3\n"
"#define value value_\n"
"#define storedst(val) *(__global dstT *)(dstptr + dst_index) = val\n"
"#else\n"
"#define value (dstT)(value_.x, value_.y, value_.z)\n"
"#define storedst(val) vstore3(val, 0, (__global dstT1 *)(dstptr + dst_index))\n"
"#endif\n"
"__kernel void setMask(__global const uchar* mask, int maskstep, int maskoffset,\n"
"__global uchar* dstptr, int dststep, int dstoffset,\n"
"int rows, int cols, dstST value_ )\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < cols && y < rows)\n"
"{\n"
"int mask_index = mad24(y, maskstep, x + maskoffset);\n"
"if( mask[mask_index] )\n"
"{\n"
"int dst_index = mad24(y, dststep, mad24(x, (int)sizeof(dstT1) * cn, dstoffset));\n"
"storedst(value);\n"
"}\n"
"}\n"
"}\n"
"__kernel void set(__global uchar* dstptr, int dststep, int dstoffset,\n"
"int rows, int cols, dstST value_ )\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < cols && y < rows)\n"
"{\n"
"int dst_index = mad24(y, dststep, mad24(x, (int)sizeof(dstT1) * cn, dstoffset));\n"
"storedst(value);\n"
"}\n"
"}\n"
"#endif\n"
, "08a40f6ae0e165d23de44f81527684b0"};
ProgramSource copyset_oclsrc(copyset.programStr);
const struct ProgramEntry flip={"flip",
"#if cn != 3\n"
"#define loadpix(addr) *(__global const T *)(addr)\n"
"#define storepix(val, addr) *(__global T *)(addr) = val\n"
"#define TSIZE (int)sizeof(T)\n"
"#else\n"
"#define loadpix(addr) vload3(0, (__global const T1 *)(addr))\n"
"#define storepix(val, addr) vstore3(val, 0, (__global T1 *)(addr))\n"
"#define TSIZE ((int)sizeof(T1)*3)\n"
"#endif\n"
"__kernel void arithm_flip_rows(__global const uchar * srcptr, int src_step, int src_offset,\n"
"__global uchar * dstptr, int dst_step, int dst_offset,\n"
"int rows, int cols, int thread_rows, int thread_cols)\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < cols && y < thread_rows)\n"
"{\n"
"T src0 = loadpix(srcptr + mad24(y, src_step, mad24(x, TSIZE, src_offset)));\n"
"T src1 = loadpix(srcptr + mad24(rows - y - 1, src_step, mad24(x, TSIZE, src_offset)));\n"
"storepix(src1, dstptr + mad24(y, dst_step, mad24(x, TSIZE, dst_offset)));\n"
"storepix(src0, dstptr + mad24(rows - y - 1, dst_step, mad24(x, TSIZE, dst_offset)));\n"
"}\n"
"}\n"
"__kernel void arithm_flip_rows_cols(__global const uchar * srcptr, int src_step, int src_offset,\n"
"__global uchar * dstptr, int dst_step, int dst_offset,\n"
"int rows, int cols, int thread_rows, int thread_cols)\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < cols && y < thread_rows)\n"
"{\n"
"int x1 = cols - x - 1;\n"
"T src0 = loadpix(srcptr + mad24(y, src_step, mad24(x, TSIZE, src_offset)));\n"
"T src1 = loadpix(srcptr + mad24(rows - y - 1, src_step, mad24(x1, TSIZE, src_offset)));\n"
"storepix(src0, dstptr + mad24(rows - y - 1, dst_step, mad24(x1, TSIZE, dst_offset)));\n"
"storepix(src1, dstptr + mad24(y, dst_step, mad24(x, TSIZE, dst_offset)));\n"
"}\n"
"}\n"
"__kernel void arithm_flip_cols(__global const uchar * srcptr, int src_step, int src_offset,\n"
"__global uchar * dstptr, int dst_step, int dst_offset,\n"
"int rows, int cols, int thread_rows, int thread_cols)\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < thread_cols && y < rows)\n"
"{\n"
"int x1 = cols - x - 1;\n"
"T src0 = loadpix(srcptr + mad24(y, src_step, mad24(x, TSIZE, src_offset)));\n"
"T src1 = loadpix(srcptr + mad24(y, src_step, mad24(x1, TSIZE, src_offset)));\n"
"storepix(src0, dstptr + mad24(y, dst_step, mad24(x1, TSIZE, dst_offset)));\n"
"storepix(src1, dstptr + mad24(y, dst_step, mad24(x, TSIZE, dst_offset)));\n"
"}\n"
"}\n"
, "6cd2ab0daa50f87184c56156e79553d7"};
ProgramSource flip_oclsrc(flip.programStr);
const struct ProgramEntry inrange={"inrange",
"#ifdef DOUBLE_SUPPORT\n"
"#ifdef cl_amd_fp64\n"
"#pragma OPENCL EXTENSION cl_amd_fp64:enable\n"
"#elif defined (cl_khr_fp64)\n"
"#pragma OPENCL EXTENSION cl_khr_fp64:enable\n"
"#endif\n"
"#endif\n"
"__kernel void inrange(__global const uchar * src1ptr, int src1_step, int src1_offset,\n"
"__global uchar * dstptr, int dst_step, int dst_offset, int dst_rows, int dst_cols,\n"
"#ifdef HAVE_SCALAR\n"
"__global const T * src2, __global const T * src3\n"
"#else\n"
"__global const uchar * src2ptr, int src2_step, int src2_offset,\n"
"__global const uchar * src3ptr, int src3_step, int src3_offset\n"
"#endif\n"
")\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < dst_cols && y < dst_rows)\n"
"{\n"
"int src1_index = mad24(y, src1_step, mad24(x, (int)sizeof(T) * cn, src1_offset));\n"
"int dst_index = mad24(y, dst_step, x + dst_offset);\n"
"__global const T * src1 = (__global const T *)(src1ptr + src1_index);\n"
"__global uchar * dst = dstptr + dst_index;\n"
"#ifndef HAVE_SCALAR\n"
"int src2_index = mad24(y, src2_step, mad24(x, (int)sizeof(T) * cn, src2_offset));\n"
"int src3_index = mad24(y, src3_step, mad24(x, (int)sizeof(T) * cn, src3_offset));\n"
"__global const T * src2 = (__global const T *)(src2ptr + src2_index);\n"
"__global const T * src3 = (__global const T *)(src3ptr + src3_index);\n"
"#endif\n"
"dst[0] = 255;\n"
"for (int c = 0; c < cn; ++c)\n"
"if (src2[c] > src1[c] || src3[c] < src1[c])\n"
"{\n"
"dst[0] = 0;\n"
"break;\n"
"}\n"
"}\n"
"}\n"
, "30c9e8ee4bb45d8277c206ee43306b32"};
ProgramSource inrange_oclsrc(inrange.programStr);
const struct ProgramEntry lut={"lut",
"__kernel void LUT(__global const uchar * srcptr, int src_step, int src_offset,\n"
"__global const uchar * lutptr, int lut_step, int lut_offset,\n"
"__global uchar * dstptr, int dst_step, int dst_offset, int rows, int cols)\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < cols && y < rows)\n"
"{\n"
"int src_index = mad24(y, src_step, mad24(x, (int)sizeof(srcT) * dcn, src_offset));\n"
"int dst_index = mad24(y, dst_step, mad24(x, (int)sizeof(dstT) * dcn, dst_offset));\n"
"__global const srcT * src = (__global const srcT *)(srcptr + src_index);\n"
"__global const dstT * lut = (__global const dstT *)(lutptr + lut_offset);\n"
"__global dstT * dst = (__global dstT *)(dstptr + dst_index);\n"
"#if lcn == 1\n"
"#pragma unroll\n"
"for (int cn = 0; cn < dcn; ++cn)\n"
"dst[cn] = lut[src[cn]];\n"
"#else\n"
"#pragma unroll\n"
"for (int cn = 0; cn < dcn; ++cn)\n"
"dst[cn] = lut[mad24(src[cn], dcn, cn)];\n"
"#endif\n"
"}\n"
"}\n"
, "1071f7f2dd0cd68dbcbd46b019e430b6"};
ProgramSource lut_oclsrc(lut.programStr);
const struct ProgramEntry mixchannels={"mixchannels",
"#define DECLARE_INPUT_MAT(i) \\\n"
"__global const uchar * src##i##ptr, int src##i##_step, int src##i##_offset,\n"
"#define DECLARE_OUTPUT_MAT(i) \\\n"
"__global uchar * dst##i##ptr, int dst##i##_step, int dst##i##_offset,\n"
"#define PROCESS_ELEM(i) \\\n"
"int src##i##_index = mad24(src##i##_step, y, mad24(x, (int)sizeof(T) * scn##i, src##i##_offset)); \\\n"
"__global const T * src##i = (__global const T *)(src##i##ptr + src##i##_index); \\\n"
"int dst##i##_index = mad24(dst##i##_step, y, mad24(x, (int)sizeof(T) * dcn##i, dst##i##_offset)); \\\n"
"__global T * dst##i = (__global T *)(dst##i##ptr + dst##i##_index); \\\n"
"dst##i[0] = src##i[0];\n"
"__kernel void mixChannels(DECLARE_INPUT_MATS DECLARE_OUTPUT_MATS int rows, int cols)\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < cols && y < rows)\n"
"{\n"
"PROCESS_ELEMS\n"
"}\n"
"}\n"
, "ba04ea999ebe7526e6bd463ebf70b67f"};
ProgramSource mixchannels_oclsrc(mixchannels.programStr);
const struct ProgramEntry mulspectrums={"mulspectrums",
"inline float2 cmulf(float2 a, float2 b)\n"
"{\n"
"return (float2)(mad(a.x, b.x, - a.y * b.y), mad(a.x, b.y, a.y * b.x));\n"
"}\n"
"inline float2 conjf(float2 a)\n"
"{\n"
"return (float2)(a.x, - a.y);\n"
"}\n"
"__kernel void mulAndScaleSpectrums(__global const uchar * src1ptr, int src1_step, int src1_offset,\n"
"__global const uchar * src2ptr, int src2_step, int src2_offset,\n"
"__global uchar * dstptr, int dst_step, int dst_offset,\n"
"int dst_rows, int dst_cols)\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < dst_cols && y < dst_rows)\n"
"{\n"
"int src1_index = mad24(y, src1_step, mad24(x, (int)sizeof(float2), src1_offset));\n"
"int src2_index = mad24(y, src2_step, mad24(x, (int)sizeof(float2), src2_offset));\n"
"int dst_index = mad24(y, dst_step, mad24(x, (int)sizeof(float2), dst_offset));\n"
"float2 src0 = *(__global const float2 *)(src1ptr + src1_index);\n"
"float2 src1 = *(__global const float2 *)(src2ptr + src2_index);\n"
"__global float2 * dst = (__global float2 *)(dstptr + dst_index);\n"
"#ifdef CONJ\n"
"float2 v = cmulf(src0, conjf(src1));\n"
"#else\n"
"float2 v = cmulf(src0, src1);\n"
"#endif\n"
"dst[0] = v;\n"
"}\n"
"}\n"
, "a1ca37b9deb30256f4144a70a424ea4b"};
ProgramSource mulspectrums_oclsrc(mulspectrums.programStr);
const struct ProgramEntry reduce={"reduce",
"#ifdef DOUBLE_SUPPORT\n"
"#ifdef cl_amd_fp64\n"
"#pragma OPENCL EXTENSION cl_amd_fp64:enable\n"
"#elif defined (cl_khr_fp64)\n"
"#pragma OPENCL EXTENSION cl_khr_fp64:enable\n"
"#endif\n"
"#endif\n"
"#define noconvert\n"
"#if cn != 3\n"
"#define loadpix(addr) *(__global const srcT *)(addr)\n"
"#define storepix(val, addr) *(__global dstT *)(addr) = val\n"
"#define srcTSIZE (int)sizeof(srcT)\n"
"#define dstTSIZE (int)sizeof(dstT)\n"
"#else\n"
"#define loadpix(addr) vload3(0, (__global const srcT1 *)(addr))\n"
"#define storepix(val, addr) vstore3(val, 0, (__global dstT1 *)(addr))\n"
"#define srcTSIZE ((int)sizeof(srcT1)*3)\n"
"#define dstTSIZE ((int)sizeof(dstT1)*3)\n"
"#endif\n"
"#ifdef HAVE_MASK\n"
"#define EXTRA_PARAMS , __global const uchar * mask, int mask_step, int mask_offset\n"
"#else\n"
"#define EXTRA_PARAMS\n"
"#endif\n"
"#if defined OP_SUM || defined OP_SUM_ABS || defined OP_SUM_SQR || defined OP_DOT\n"
"#ifdef OP_DOT\n"
"#if ddepth <= 4\n"
"#define FUNC(a, b, c) a = mad24(b, c, a)\n"
"#else\n"
"#define FUNC(a, b, c) a = mad(b, c, a)\n"
"#endif\n"
"#elif defined OP_SUM\n"
"#define FUNC(a, b) a += b\n"
"#elif defined OP_SUM_ABS\n"
"#define FUNC(a, b) a += b >= (dstT)(0) ? b : -b\n"
"#elif defined OP_SUM_SQR\n"
"#if ddepth <= 4\n"
"#define FUNC(a, b) a = mad24(b, b, a)\n"
"#else\n"
"#define FUNC(a, b) a = mad(b, b, a)\n"
"#endif\n"
"#endif\n"
"#define DECLARE_LOCAL_MEM \\\n"
"__local dstT localmem[WGS2_ALIGNED]\n"
"#define DEFINE_ACCUMULATOR \\\n"
"dstT accumulator = (dstT)(0)\n"
"#ifdef HAVE_MASK\n"
"#define REDUCE_GLOBAL \\\n"
"int mask_index = mad24(id / cols, mask_step, mask_offset + (id % cols)); \\\n"
"if (mask[mask_index]) \\\n"
"{ \\\n"
"dstT temp = convertToDT(loadpix(srcptr + src_index)); \\\n"
"FUNC(accumulator, temp); \\\n"
"}\n"
"#elif defined OP_DOT\n"
"#define REDUCE_GLOBAL \\\n"
"int src2_index = mad24(id / cols, src2_step, mad24(id % cols, srcTSIZE, src2_offset)); \\\n"
"dstT temp = convertToDT(loadpix(srcptr + src_index)), temp2 = convertToDT(loadpix(src2ptr + src2_index)); \\\n"
"FUNC(accumulator, temp, temp2)\n"
"#else\n"
"#define REDUCE_GLOBAL \\\n"
"dstT temp = convertToDT(loadpix(srcptr + src_index)); \\\n"
"FUNC(accumulator, temp)\n"
"#endif\n"
"#define SET_LOCAL_1 \\\n"
"localmem[lid] = accumulator\n"
"#define REDUCE_LOCAL_1 \\\n"
"localmem[lid - WGS2_ALIGNED] += accumulator\n"
"#define REDUCE_LOCAL_2 \\\n"
"localmem[lid] += localmem[lid2]\n"
"#define CALC_RESULT \\\n"
"storepix(localmem[0], dstptr + dstTSIZE * gid)\n"
"#elif defined OP_COUNT_NON_ZERO\n"
"#define dstT int\n"
"#define DECLARE_LOCAL_MEM \\\n"
"__local dstT localmem[WGS2_ALIGNED]\n"
"#define DEFINE_ACCUMULATOR \\\n"
"dstT accumulator = (dstT)(0); \\\n"
"srcT zero = (srcT)(0), one = (srcT)(1)\n"
"#define REDUCE_GLOBAL \\\n"
"accumulator += loadpix(srcptr + src_index) == zero ? zero : one\n"
"#define SET_LOCAL_1 \\\n"
"localmem[lid] = accumulator\n"
"#define REDUCE_LOCAL_1 \\\n"
"localmem[lid - WGS2_ALIGNED] += accumulator\n"
"#define REDUCE_LOCAL_2 \\\n"
"localmem[lid] += localmem[lid2]\n"
"#define CALC_RESULT \\\n"
"storepix(localmem[0], dstptr + dstTSIZE * gid)\n"
"#elif defined OP_MIN_MAX_LOC || defined OP_MIN_MAX_LOC_MASK\n"
"#ifdef DEPTH_0\n"
"#define srcT uchar\n"
"#define MIN_VAL 0\n"
"#define MAX_VAL 255\n"
"#elif defined DEPTH_1\n"
"#define srcT char\n"
"#define MIN_VAL -128\n"
"#define MAX_VAL 127\n"
"#elif defined DEPTH_2\n"
"#define srcT ushort\n"
"#define MIN_VAL 0\n"
"#define MAX_VAL 65535\n"
"#elif defined DEPTH_3\n"
"#define srcT short\n"
"#define MIN_VAL -32768\n"
"#define MAX_VAL 32767\n"
"#elif defined DEPTH_4\n"
"#define srcT int\n"
"#define MIN_VAL INT_MIN\n"
"#define MAX_VAL INT_MAX\n"
"#elif defined DEPTH_5\n"
"#define srcT float\n"
"#define MIN_VAL (-FLT_MAX)\n"
"#define MAX_VAL FLT_MAX\n"
"#elif defined DEPTH_6\n"
"#define srcT double\n"
"#define MIN_VAL (-DBL_MAX)\n"
"#define MAX_VAL DBL_MAX\n"
"#endif\n"
"#define dstT srcT\n"
"#define DECLARE_LOCAL_MEM \\\n"
"__local srcT localmem_min[WGS2_ALIGNED]; \\\n"
"__local srcT localmem_max[WGS2_ALIGNED]; \\\n"
"__local int localmem_minloc[WGS2_ALIGNED]; \\\n"
"__local int localmem_maxloc[WGS2_ALIGNED]\n"
"#define DEFINE_ACCUMULATOR \\\n"
"srcT minval = MAX_VAL; \\\n"
"srcT maxval = MIN_VAL; \\\n"
"int negative = -1; \\\n"
"int minloc = negative; \\\n"
"int maxloc = negative; \\\n"
"srcT temp; \\\n"
"int temploc\n"
"#define REDUCE_GLOBAL \\\n"
"temp = loadpix(srcptr + src_index); \\\n"
"temploc = id; \\\n"
"srcT temp_minval = minval, temp_maxval = maxval; \\\n"
"minval = min(minval, temp); \\\n"
"maxval = max(maxval, temp); \\\n"
"minloc = (minval == temp_minval) ? (temp_minval == MAX_VAL) ? temploc : minloc : temploc; \\\n"
"maxloc = (maxval == temp_maxval) ? (temp_maxval == MIN_VAL) ? temploc : maxloc : temploc\n"
"#define SET_LOCAL_1 \\\n"
"localmem_min[lid] = minval; \\\n"
"localmem_max[lid] = maxval; \\\n"
"localmem_minloc[lid] = minloc; \\\n"
"localmem_maxloc[lid] = maxloc\n"
"#define REDUCE_LOCAL_1 \\\n"
"srcT oldmin = localmem_min[lid-WGS2_ALIGNED]; \\\n"
"srcT oldmax = localmem_max[lid-WGS2_ALIGNED]; \\\n"
"localmem_min[lid - WGS2_ALIGNED] = min(minval, localmem_min[lid-WGS2_ALIGNED]); \\\n"
"localmem_max[lid - WGS2_ALIGNED] = max(maxval, localmem_max[lid-WGS2_ALIGNED]); \\\n"
"srcT minv = localmem_min[lid - WGS2_ALIGNED], maxv = localmem_max[lid - WGS2_ALIGNED]; \\\n"
"localmem_minloc[lid - WGS2_ALIGNED] = (minv == minval) ? (minv == oldmin) ? \\\n"
"min(minloc, localmem_minloc[lid-WGS2_ALIGNED]) : minloc : localmem_minloc[lid-WGS2_ALIGNED]; \\\n"
"localmem_maxloc[lid - WGS2_ALIGNED] = (maxv == maxval) ? (maxv == oldmax) ? \\\n"
"min(maxloc, localmem_maxloc[lid-WGS2_ALIGNED]) : maxloc : localmem_maxloc[lid-WGS2_ALIGNED]\n"
"#define REDUCE_LOCAL_2 \\\n"
"srcT oldmin = localmem_min[lid]; \\\n"
"srcT oldmax = localmem_max[lid]; \\\n"
"localmem_min[lid] = min(localmem_min[lid], localmem_min[lid2]); \\\n"
"localmem_max[lid] = max(localmem_max[lid], localmem_max[lid2]); \\\n"
"srcT min1 = localmem_min[lid], min2 = localmem_min[lid2]; \\\n"
"localmem_minloc[lid] = (localmem_minloc[lid] == negative) ? localmem_minloc[lid2] : (localmem_minloc[lid2] == negative) ? \\\n"
"localmem_minloc[lid] : (min1 == min2) ? (min1 == oldmin) ? min(localmem_minloc[lid2],localmem_minloc[lid]) : \\\n"
"localmem_minloc[lid2] : localmem_minloc[lid]; \\\n"
"srcT max1 = localmem_max[lid], max2 = localmem_max[lid2]; \\\n"
"localmem_maxloc[lid] = (localmem_maxloc[lid] == negative) ? localmem_maxloc[lid2] : (localmem_maxloc[lid2] == negative) ? \\\n"
"localmem_maxloc[lid] : (max1 == max2) ? (max1 == oldmax) ? min(localmem_maxloc[lid2],localmem_maxloc[lid]) : \\\n"
"localmem_maxloc[lid2] : localmem_maxloc[lid]\n"
"#define CALC_RESULT \\\n"
"storepix(localmem_min[0], dstptr + dstTSIZE * gid); \\\n"
"storepix(localmem_max[0], dstptr2 + dstTSIZE * gid); \\\n"
"dstlocptr[gid] = localmem_minloc[0]; \\\n"
"dstlocptr2[gid] = localmem_maxloc[0]\n"
"#if defined OP_MIN_MAX_LOC_MASK\n"
"#undef DEFINE_ACCUMULATOR\n"
"#define DEFINE_ACCUMULATOR \\\n"
"srcT minval = MAX_VAL; \\\n"
"srcT maxval = MIN_VAL; \\\n"
"int negative = -1; \\\n"
"int minloc = negative; \\\n"
"int maxloc = negative; \\\n"
"srcT temp, temp_mask, zeroVal = (srcT)(0); \\\n"
"int temploc\n"
"#undef REDUCE_GLOBAL\n"
"#define REDUCE_GLOBAL \\\n"
"temp = loadpix(srcptr + src_index); \\\n"
"temploc = id; \\\n"
"int mask_index = mad24(id / cols, mask_step, mask_offset + (id % cols) * (int)sizeof(uchar)); \\\n"
"__global const uchar * mask = (__global const uchar *)(maskptr + mask_index); \\\n"
"temp_mask = mask[0]; \\\n"
"srcT temp_minval = minval, temp_maxval = maxval; \\\n"
"minval = (temp_mask == zeroVal) ? minval : min(minval, temp); \\\n"
"maxval = (temp_mask == zeroVal) ? maxval : max(maxval, temp); \\\n"
"minloc = (temp_mask == zeroVal) ? minloc : (minval == temp_minval) ? (temp_minval == MAX_VAL) ? temploc : minloc : temploc; \\\n"
"maxloc = (temp_mask == zeroVal) ? maxloc : (maxval == temp_maxval) ? (temp_maxval == MIN_VAL) ? temploc : maxloc : temploc\n"
"#endif\n"
"#else\n"
"#error \"No operation\"\n"
"#endif\n"
"#ifdef OP_MIN_MAX_LOC\n"
"#undef EXTRA_PARAMS\n"
"#define EXTRA_PARAMS , __global uchar * dstptr2, __global int * dstlocptr, __global int * dstlocptr2\n"
"#elif defined OP_MIN_MAX_LOC_MASK\n"
"#undef EXTRA_PARAMS\n"
"#define EXTRA_PARAMS , __global uchar * dstptr2, __global int * dstlocptr, __global int * dstlocptr2, \\\n"
"__global const uchar * maskptr, int mask_step, int mask_offset\n"
"#elif defined OP_DOT\n"
"#undef EXTRA_PARAMS\n"
"#define EXTRA_PARAMS , __global uchar * src2ptr, int src2_step, int src2_offset\n"
"#endif\n"
"__kernel void reduce(__global const uchar * srcptr, int src_step, int src_offset, int cols,\n"
"int total, int groupnum, __global uchar * dstptr EXTRA_PARAMS)\n"
"{\n"
"int lid = get_local_id(0);\n"
"int gid = get_group_id(0);\n"
"int id = get_global_id(0);\n"
"DECLARE_LOCAL_MEM;\n"
"DEFINE_ACCUMULATOR;\n"
"for (int grain = groupnum * WGS; id < total; id += grain)\n"
"{\n"
"int src_index = mad24(id / cols, src_step, mad24(id % cols, srcTSIZE, src_offset));\n"
"REDUCE_GLOBAL;\n"
"}\n"
"if (lid < WGS2_ALIGNED)\n"
"{\n"
"SET_LOCAL_1;\n"
"}\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"if (lid >= WGS2_ALIGNED && total >= WGS2_ALIGNED)\n"
"{\n"
"REDUCE_LOCAL_1;\n"
"}\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"for (int lsize = WGS2_ALIGNED >> 1; lsize > 0; lsize >>= 1)\n"
"{\n"
"if (lid < lsize)\n"
"{\n"
"int lid2 = lsize + lid;\n"
"REDUCE_LOCAL_2;\n"
"}\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"}\n"
"if (lid == 0)\n"
"{\n"
"CALC_RESULT;\n"
"}\n"
"}\n"
, "baee7a7605f637133d0560c295214d91"};
ProgramSource reduce_oclsrc(reduce.programStr);
const struct ProgramEntry reduce2={"reduce2",
"#ifdef DOUBLE_SUPPORT\n"
"#ifdef cl_amd_fp64\n"
"#pragma OPENCL EXTENSION cl_amd_fp64:enable\n"
"#elif defined (cl_khr_fp64)\n"
"#pragma OPENCL EXTENSION cl_khr_fp64:enable\n"
"#endif\n"
"#endif\n"
"#if ddepth == 0\n"
"#define MIN_VAL 0\n"
"#define MAX_VAL 255\n"
"#elif ddepth == 1\n"
"#define MIN_VAL -128\n"
"#define MAX_VAL 127\n"
"#elif ddepth == 2\n"
"#define MIN_VAL 0\n"
"#define MAX_VAL 65535\n"
"#elif ddepth == 3\n"
"#define MIN_VAL -32768\n"
"#define MAX_VAL 32767\n"
"#elif ddepth == 4\n"
"#define MIN_VAL INT_MIN\n"
"#define MAX_VAL INT_MAX\n"
"#elif ddepth == 5\n"
"#define MIN_VAL (-FLT_MAX)\n"
"#define MAX_VAL FLT_MAX\n"
"#elif ddepth == 6\n"
"#define MIN_VAL (-DBL_MAX)\n"
"#define MAX_VAL DBL_MAX\n"
"#else\n"
"#error \"Unsupported depth\"\n"
"#endif\n"
"#define noconvert\n"
"#ifdef OCL_CV_REDUCE_SUM\n"
"#define INIT_VALUE 0\n"
"#define PROCESS_ELEM(acc, value) acc += value\n"
"#elif defined(OCL_CV_REDUCE_MAX)\n"
"#define INIT_VALUE MIN_VAL\n"
"#define PROCESS_ELEM(acc, value) acc = value > acc ? value : acc\n"
"#elif defined(OCL_CV_REDUCE_MIN)\n"
"#define INIT_VALUE MAX_VAL\n"
"#define PROCESS_ELEM(acc, value) acc = value < acc ? value : acc\n"
"#elif defined(OCL_CV_REDUCE_AVG)\n"
"#error \"This operation should be implemented through OCL_CV_REDUCE_SUM\"\n"
"#else\n"
"#error \"No operation is specified\"\n"
"#endif\n"
"__kernel void reduce(__global const uchar * srcptr, int src_step, int src_offset, int rows, int cols,\n"
"__global uchar * dstptr, int dst_step, int dst_offset)\n"
"{\n"
"#if dim == 0\n"
"int x = get_global_id(0);\n"
"if (x < cols)\n"
"{\n"
"int src_index = mad24(x, (int)sizeof(srcT) * cn, src_offset);\n"
"__global dstT * dst = (__global dstT *)(dstptr + dst_offset) + x * cn;\n"
"dstT tmp[cn] = { INIT_VALUE };\n"
"for (int y = 0; y < rows; ++y, src_index += src_step)\n"
"{\n"
"__global const srcT * src = (__global const srcT *)(srcptr + src_index);\n"
"#pragma unroll\n"
"for (int c = 0; c < cn; ++c)\n"
"{\n"
"dstT value = convertToDT(src[c]);\n"
"PROCESS_ELEM(tmp[c], value);\n"
"}\n"
"}\n"
"#pragma unroll\n"
"for (int c = 0; c < cn; ++c)\n"
"dst[c] = tmp[c];\n"
"}\n"
"#elif dim == 1\n"
"int y = get_global_id(0);\n"
"if (y < rows)\n"
"{\n"
"int src_index = mad24(y, src_step, src_offset);\n"
"int dst_index = mad24(y, dst_step, dst_offset);\n"
"__global const srcT * src = (__global const srcT *)(srcptr + src_index);\n"
"__global dstT * dst = (__global dstT *)(dstptr + dst_index);\n"
"dstT tmp[cn] = { INIT_VALUE };\n"
"for (int x = 0; x < cols; ++x, src += cn)\n"
"{\n"
"#pragma unroll\n"
"for (int c = 0; c < cn; ++c)\n"
"{\n"
"dstT value = convertToDT(src[c]);\n"
"PROCESS_ELEM(tmp[c], value);\n"
"}\n"
"}\n"
"#pragma unroll\n"
"for (int c = 0; c < cn; ++c)\n"
"dst[c] = tmp[c];\n"
"}\n"
"#else\n"
"#error \"Dims must be either 0 or 1\"\n"
"#endif\n"
"}\n"
, "730a159bc63f95ef59b6f0554239d2f4"};
ProgramSource reduce2_oclsrc(reduce2.programStr);
const struct ProgramEntry set_identity={"set_identity",
"#if cn != 3\n"
"#define loadpix(addr) *(__global const T *)(addr)\n"
"#define storepix(val, addr) *(__global T *)(addr) = val\n"
"#define TSIZE (int)sizeof(T)\n"
"#define scalar scalar_\n"
"#else\n"
"#define loadpix(addr) vload3(0, (__global const T1 *)(addr))\n"
"#define storepix(val, addr) vstore3(val, 0, (__global T1 *)(addr))\n"
"#define TSIZE ((int)sizeof(T1)*3)\n"
"#define scalar (T)(scalar_.x, scalar_.y, scalar_.z)\n"
"#endif\n"
"__kernel void setIdentity(__global uchar * srcptr, int src_step, int src_offset, int rows, int cols,\n"
"ST scalar_)\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < cols && y < rows)\n"
"{\n"
"int src_index = mad24(y, src_step, mad24(x, TSIZE, src_offset));\n"
"storepix(x == y ? scalar : (T)(0), srcptr + src_index);\n"
"}\n"
"}\n"
, "1d2a1acbc8b124d65c83ae270527a222"};
ProgramSource set_identity_oclsrc(set_identity.programStr);
const struct ProgramEntry split_merge={"split_merge",
"#ifdef OP_MERGE\n"
"#define DECLARE_SRC_PARAM(index) __global const uchar * src##index##ptr, int src##index##_step, int src##index##_offset,\n"
"#define DECLARE_DATA(index) __global const T * src##index = \\\n"
"(__global T *)(src##index##ptr + mad24(src##index##_step, y, mad24(x, (int)sizeof(T) * scn##index, src##index##_offset)));\n"
"#define PROCESS_ELEM(index) dst[index] = src##index[0];\n"
"__kernel void merge(DECLARE_SRC_PARAMS_N\n"
"__global uchar * dstptr, int dst_step, int dst_offset,\n"
"int rows, int cols)\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < cols && y < rows)\n"
"{\n"
"DECLARE_DATA_N\n"
"__global T * dst = (__global T *)(dstptr + mad24(dst_step, y, mad24(x, (int)sizeof(T) * cn, dst_offset)));\n"
"PROCESS_ELEMS_N\n"
"}\n"
"}\n"
"#elif defined OP_SPLIT\n"
"#define DECLARE_DST_PARAM(index) , __global uchar * dst##index##ptr, int dst##index##_step, int dst##index##_offset\n"
"#define DECLARE_DATA(index) __global T * dst##index = \\\n"
"(__global T *)(dst##index##ptr + mad24(y, dst##index##_step, mad24(x, (int)sizeof(T), dst##index##_offset)));\n"
"#define PROCESS_ELEM(index) dst##index[0] = src[index];\n"
"__kernel void split(__global uchar* srcptr, int src_step, int src_offset, int rows, int cols DECLARE_DST_PARAMS)\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (x < cols && y < rows)\n"
"{\n"
"DECLARE_DATA_N\n"
"__global const T * src = (__global const T *)(srcptr + mad24(y, src_step, mad24(x, cn * (int)sizeof(T), src_offset)));\n"
"PROCESS_ELEMS_N\n"
"}\n"
"}\n"
"#else\n"
"#error \"No operation\"\n"
"#endif\n"
, "8d2c7107f57a4d42d08fe0b27cfd5f80"};
ProgramSource split_merge_oclsrc(split_merge.programStr);
const struct ProgramEntry transpose={"transpose",
"#if cn != 3\n"
"#define loadpix(addr) *(__global const T *)(addr)\n"
"#define storepix(val, addr) *(__global T *)(addr) = val\n"
"#define TSIZE (int)sizeof(T)\n"
"#else\n"
"#define loadpix(addr) vload3(0, (__global const T1 *)(addr))\n"
"#define storepix(val, addr) vstore3(val, 0, (__global T1 *)(addr))\n"
"#define TSIZE ((int)sizeof(T1)*3)\n"
"#endif\n"
"#define LDS_STEP TILE_DIM\n"
"__kernel void transpose(__global const uchar * srcptr, int src_step, int src_offset, int src_rows, int src_cols,\n"
"__global uchar * dstptr, int dst_step, int dst_offset)\n"
"{\n"
"int gp_x = get_group_id(0), gp_y = get_group_id(1);\n"
"int gs_x = get_num_groups(0), gs_y = get_num_groups(1);\n"
"int groupId_x, groupId_y;\n"
"if (src_rows == src_cols)\n"
"{\n"
"groupId_y = gp_x;\n"
"groupId_x = (gp_x + gp_y) % gs_x;\n"
"}\n"
"else\n"
"{\n"
"int bid = mad24(gs_x, gp_y, gp_x);\n"
"groupId_y = bid % gs_y;\n"
"groupId_x = ((bid / gs_y) + groupId_y) % gs_x;\n"
"}\n"
"int lx = get_local_id(0);\n"
"int ly = get_local_id(1);\n"
"int x = mad24(groupId_x, TILE_DIM, lx);\n"
"int y = mad24(groupId_y, TILE_DIM, ly);\n"
"int x_index = mad24(groupId_y, TILE_DIM, lx);\n"
"int y_index = mad24(groupId_x, TILE_DIM, ly);\n"
"__local T tile[TILE_DIM * LDS_STEP];\n"
"if (x < src_cols && y < src_rows)\n"
"{\n"
"int index_src = mad24(y, src_step, mad24(x, TSIZE, src_offset));\n"
"for (int i = 0; i < TILE_DIM; i += BLOCK_ROWS)\n"
"if (y + i < src_rows)\n"
"{\n"
"tile[mad24(ly + i, LDS_STEP, lx)] = loadpix(srcptr + index_src);\n"
"index_src = mad24(BLOCK_ROWS, src_step, index_src);\n"
"}\n"
"}\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"if (x_index < src_rows && y_index < src_cols)\n"
"{\n"
"int index_dst = mad24(y_index, dst_step, mad24(x_index, TSIZE, dst_offset));\n"
"for (int i = 0; i < TILE_DIM; i += BLOCK_ROWS)\n"
"if ((y_index + i) < src_cols)\n"
"{\n"
"storepix(tile[mad24(lx, LDS_STEP, ly + i)], dstptr + index_dst);\n"
"index_dst = mad24(BLOCK_ROWS, dst_step, index_dst);\n"
"}\n"
"}\n"
"}\n"
"__kernel void transpose_inplace(__global uchar * srcptr, int src_step, int src_offset, int src_rows)\n"
"{\n"
"int x = get_global_id(0);\n"
"int y = get_global_id(1);\n"
"if (y < src_rows && x < y)\n"
"{\n"
"int src_index = mad24(y, src_step, mad24(x, TSIZE, src_offset));\n"
"int dst_index = mad24(x, src_step, mad24(y, TSIZE, src_offset));\n"
"__global const uchar * src = srcptr + src_index;\n"
"__global uchar * dst = srcptr + dst_index;\n"
"T tmp = loadpix(dst);\n"
"storepix(loadpix(src), dst);\n"
"storepix(tmp, src);\n"
"}\n"
"}\n"
, "ff1a3b3f7a39a2ed9ba5556bd984d694"};
ProgramSource transpose_oclsrc(transpose.programStr);
}
}}
| 36.035914
| 150
| 0.669789
|
stalinizer
|
0ec3c6b8458ce2fa78b3b112d456ac56d0ff8bfa
| 120
|
hxx
|
C++
|
src/Providers/UNIXProviders/SAPStatistics/UNIX_SAPStatistics_AIX.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | 1
|
2020-10-12T09:00:09.000Z
|
2020-10-12T09:00:09.000Z
|
src/Providers/UNIXProviders/SAPStatistics/UNIX_SAPStatistics_AIX.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | null | null | null |
src/Providers/UNIXProviders/SAPStatistics/UNIX_SAPStatistics_AIX.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | null | null | null |
#ifdef PEGASUS_OS_AIX
#ifndef __UNIX_SAPSTATISTICS_PRIVATE_H
#define __UNIX_SAPSTATISTICS_PRIVATE_H
#endif
#endif
| 10
| 38
| 0.841667
|
brunolauze
|
0ec8fb9aa846f1b3e7001810f2ffa2fd7e6cb0e2
| 6,522
|
cpp
|
C++
|
FastSparse/src/Grid2D.cpp
|
jiachangliu/fastSparse
|
1b54d5c6d49778a7510c3183f7d59d0b78112b56
|
[
"MIT"
] | 7
|
2022-02-25T02:37:40.000Z
|
2022-03-29T16:16:28.000Z
|
FastSparse/src/Grid2D.cpp
|
jiachangliu/fastSparse
|
1b54d5c6d49778a7510c3183f7d59d0b78112b56
|
[
"MIT"
] | null | null | null |
FastSparse/src/Grid2D.cpp
|
jiachangliu/fastSparse
|
1b54d5c6d49778a7510c3183f7d59d0b78112b56
|
[
"MIT"
] | 1
|
2022-03-04T18:59:31.000Z
|
2022-03-04T18:59:31.000Z
|
#include "Grid2D.h"
template <class T>
Grid2D<T>::Grid2D(const T& Xi, const arma::vec& yi, const GridParams<T>& PGi)
{
// automatically selects lambda_0 (but assumes other lambdas are given in PG.P.ModelParams)
X = Ξ
y = &yi;
p = Xi.n_cols;
PG = PGi;
G_nrows = PG.G_nrows;
G_ncols = PG.G_ncols;
G.reserve(G_nrows);
Lambda2Max = PG.Lambda2Max;
Lambda2Min = PG.Lambda2Min;
LambdaMinFactor = PG.LambdaMinFactor;
P = PG.P;
}
template <class T>
Grid2D<T>::~Grid2D(){
delete Xtr;
if (PG.P.Specs.Logistic) {
delete PG.P.Xy;
}
if (PG.P.Specs.SquaredHinge) {
delete PG.P.Xy;
}
if (PG.P.Specs.Exponential) {
delete PG.P.Xy;
delete PG.P.Xy_neg_indices;
}
}
template <class T>
std::vector< std::vector<std::unique_ptr<FitResult<T>> > > Grid2D<T>::Fit() {
arma::vec Xtrarma;
if (PG.P.Specs.Logistic) {
// std::cout << "Grid2D.cpp i'm in line 35\n";
auto n = X->n_rows;
double b0 = 0;
arma::vec ExpyXB = arma::ones<arma::vec>(n);
if (PG.intercept) {
for (std::size_t t = 0; t < 50; ++t) {
double partial_b0 = - arma::sum( *y / (1 + ExpyXB) );
b0 -= partial_b0 / (n * 0.25); // intercept is not regularized
ExpyXB = arma::exp(b0 * *y);
}
}
PG.P.b0 = b0;
Xtrarma = arma::abs(- arma::trans(*y /(1+ExpyXB)) * *X).t(); // = gradient of logistic loss at zero
//Xtrarma = 0.5 * arma::abs(y->t() * *X).t(); // = gradient of logistic loss at zero
T Xy = matrix_vector_schur_product(*X, y); // X->each_col() % *y;
PG.P.Xy = new T;
*PG.P.Xy = Xy;
} else if (PG.P.Specs.Exponential) {
// std::cout << "Grid2D.cpp i'm in line 61\n";
auto n = X->n_rows;
double b0 = 0;
// arma::vec ExpyXB = arma::ones<arma::vec>(n);
// if (PG.intercept) {
// for (std::size_t t = 0; t < 50; ++t) {
// double partial_b0 = - arma::sum( *y / (1 + ExpyXB) );
// b0 -= partial_b0 / (n * 0.25); // intercept is not regularized
// ExpyXB = arma::exp(b0 * *y);
// }
// }
// PG.P.b0 = b0;
// Xtrarma = arma::abs(- arma::trans(*y /(1+ExpyXB)) * *X).t(); // = gradient of logistic loss at zero
// //Xtrarma = 0.5 * arma::abs(y->t() * *X).t(); // = gradient of logistic loss at zero
T Xy = matrix_vector_schur_product(*X, y); // X->each_col() % *y;
PG.P.Xy = new T;
*PG.P.Xy = Xy;
std::unordered_map<std::size_t, arma::uvec> Xy_neg_indices;
for (size_t tmp = 0; tmp < Xy.n_cols; ++tmp){
Xy_neg_indices.insert(std::make_pair(tmp, arma::find(matrix_column_get(*(PG.P.Xy), tmp) < 0)));
}
Xy_neg_indices.insert(std::make_pair(-1, arma::find(*y < 0)));
PG.P.Xy_neg_indices = new std::unordered_map<std::size_t, arma::uvec>;
*PG.P.Xy_neg_indices = Xy_neg_indices;
// indices = (*(this->Xy_neg_indices))[-1];
// // this->d_minus = arma::sum(this->inverse_ExpyXB.elem(indices)) / arma::sum(this->inverse_ExpyXB);
// this->d_minus = arma::sum(this->inverse_ExpyXB.elem(indices)) / this->current_expo_loss;
// const double partial_b0 = -0.5*std::log((1-this->d_minus)/this->d_minus);
// this->b0 -= partial_b0;
arma::vec inverse_ExpyXB = arma::ones<arma::vec>(n);
// calcualte the exponential intercept when all coordinates are zero
b0 = 0.0;
if (PG.intercept) {
arma::uvec indices = Xy_neg_indices[-1];
double d_minus = (double)indices.n_elem / (double)n;
double partial_b0 = -0.5*std::log((1-d_minus)/d_minus);
b0 -= partial_b0;
inverse_ExpyXB %= arma::exp( partial_b0 * *y);
}
PG.P.b0 = b0;
Xtrarma = arma::abs(- arma::trans(*y % inverse_ExpyXB) * *X).t(); // = gradient of logistic loss at zero
} else if (PG.P.Specs.SquaredHinge) {
auto n = X->n_rows;
double b0 = 0;
arma::vec onemyxb = arma::ones<arma::vec>(n);
arma::uvec indices = arma::find(onemyxb > 0);
if (PG.intercept){
for (std::size_t t = 0; t < 50; ++t){
double partial_b0 = arma::sum(2 * onemyxb.elem(indices) % (- y->elem(indices) ) );
b0 -= partial_b0 / (n * 2); // intercept is not regularized
onemyxb = 1 - (*y * b0);
indices = arma::find(onemyxb > 0);
}
}
PG.P.b0 = b0;
T indices_rows = matrix_rows_get(*X, indices);
Xtrarma = 2 * arma::abs(arma::trans(y->elem(indices) % onemyxb.elem(indices))* indices_rows).t(); // = gradient of loss function at zero
//Xtrarma = 2 * arma::abs(y->t() * *X).t(); // = gradient of loss function at zero
T Xy = matrix_vector_schur_product(*X, y); // X->each_col() % *y;
PG.P.Xy = new T;
*PG.P.Xy = Xy;
} else {
Xtrarma = arma::abs(y->t() * *X).t();
}
double ytXmax = arma::max(Xtrarma);
std::size_t index;
if (PG.P.Specs.L0L1) {
index = 1;
if(G_nrows != 1) {
Lambda2Max = ytXmax;
Lambda2Min = Lambda2Max * LambdaMinFactor;
}
} else if (PG.P.Specs.L0L2) {
index = 2;
}
arma::vec Lambdas2 = arma::logspace(std::log10(Lambda2Min), std::log10(Lambda2Max), G_nrows);
Lambdas2 = arma::flipud(Lambdas2);
std::vector<double> Xtrvec = arma::conv_to< std::vector<double> >::from(Xtrarma);
Xtr = new std::vector<double>(X->n_cols); // needed! careful
PG.XtrAvailable = true;
// Rcpp::Rcout << "Grid2D Start\n";
for(std::size_t i=0; i<Lambdas2.size();++i) { //auto &l : Lambdas2
// Rcpp::Rcout << "Grid1D Start: " << i << "\n";
*Xtr = Xtrvec;
PG.Xtr = Xtr;
PG.ytXmax = ytXmax;
PG.P.ModelParams[index] = Lambdas2[i];
if (PG.LambdaU == true)
PG.Lambdas = PG.LambdasGrid[i];
//std::vector<std::unique_ptr<FitResult>> Gl();
//auto Gl = Grid1D(*X, *y, PG).Fit();
// Rcpp::Rcout << "Grid1D Start: " << i << "\n";
G.push_back(std::move(Grid1D<T>(*X, *y, PG).Fit()));
}
return std::move(G);
}
template class Grid2D<arma::mat>;
template class Grid2D<arma::sp_mat>;
| 36.033149
| 144
| 0.521926
|
jiachangliu
|
0ec941e2dcda2ff27db9be303022c927137d9d2d
| 1,110
|
cpp
|
C++
|
Sources/Sapphire/Tests/GraphTest/GraphFunctionalityTest.cpp
|
jwkim98/Motutapu
|
f494d23953a18be1aba3261c8e79392f96a140ef
|
[
"MIT"
] | 1
|
2021-01-11T18:14:04.000Z
|
2021-01-11T18:14:04.000Z
|
Sources/Sapphire/Tests/GraphTest/GraphFunctionalityTest.cpp
|
jlee335/Sapphire
|
f494d23953a18be1aba3261c8e79392f96a140ef
|
[
"MIT"
] | 3
|
2020-12-31T13:21:00.000Z
|
2021-04-28T09:51:33.000Z
|
Sources/Sapphire/Tests/GraphTest/GraphFunctionalityTest.cpp
|
jlee335/Sapphire
|
f494d23953a18be1aba3261c8e79392f96a140ef
|
[
"MIT"
] | 2
|
2020-12-31T06:29:54.000Z
|
2021-01-11T18:14:23.000Z
|
// Copyright (c) 2021, Justin Kim
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Sapphire/Tests/GraphTest/GraphFunctionalityTest.hpp>
#include <Sapphire/operations/Forward/Basic.hpp>
#include <Sapphire/Model.hpp>
#include "doctest.h"
namespace Sapphire::Test
{
void GraphFunctionalityTest()
{
ModelManager::AddModel("BasicModel");
ModelManager::SetCurrentModel("BasicModel");
const CudaDevice gpu(0, "cuda0");
NN::TwoOutputs twoOutputs;
NN::Basic hidden1;
NN::Basic hidden2;
NN::TwoInputs twoInputs;
NN::InplaceOp inplace1;
NN::Basic output;
Tensor x(Shape({ 10 }), gpu, Type::Dense);
Initialize::Initialize(x, std::make_unique<Initialize::Ones>());
auto [x11, x12] = twoOutputs(x);
auto x21 = hidden1(x11);
auto x22 = hidden2(x12);
auto x31 = twoInputs(x21, x22);
inplace1(x31);
auto y = output(x31);
ModelManager::CurModel().BackProp(y);
ModelManager::CurModel().Clear();
}
}
| 25.813953
| 75
| 0.695495
|
jwkim98
|
0eca4be0596ba77330809af08909fef96b3c6eff
| 2,038
|
cpp
|
C++
|
src/common/autoware_auto_common/test/test_bool_comparisons.cpp
|
fanyu2021/fyAutowareAuto
|
073661c0634de671ff01bda8a316a5ce10c96ca9
|
[
"Apache-2.0"
] | 4
|
2020-12-04T00:38:42.000Z
|
2022-02-24T05:48:58.000Z
|
src/common/autoware_auto_common/test/test_bool_comparisons.cpp
|
fanyu2021/fyAutowareAuto
|
073661c0634de671ff01bda8a316a5ce10c96ca9
|
[
"Apache-2.0"
] | null | null | null |
src/common/autoware_auto_common/test/test_bool_comparisons.cpp
|
fanyu2021/fyAutowareAuto
|
073661c0634de671ff01bda8a316a5ce10c96ca9
|
[
"Apache-2.0"
] | 2
|
2021-09-27T06:19:07.000Z
|
2021-09-28T08:18:09.000Z
|
// Copyright 2020 Mapless AI, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include <gtest/gtest.h>
#include "helper_functions/bool_comparisons.hpp"
// cppcheck does not like gtest macros inside of namespaces:
// https://sourceforge.net/p/cppcheck/discussion/general/thread/e68df47b/
// use a namespace alias instead of putting macros into the namespace
namespace comp = autoware::common::helper_functions::comparisons;
//------------------------------------------------------------------------------
TEST(HelperFunctions_Comparisons, exclusive_or) {
EXPECT_TRUE(comp::exclusive_or(0, 1));
EXPECT_TRUE(comp::exclusive_or(1, 0));
EXPECT_FALSE(comp::exclusive_or(0, 0));
EXPECT_FALSE(comp::exclusive_or(1, 1));
EXPECT_TRUE(comp::exclusive_or(false, true));
EXPECT_TRUE(comp::exclusive_or(true, false));
EXPECT_FALSE(comp::exclusive_or(false, false));
EXPECT_FALSE(comp::exclusive_or(true, true));
}
//------------------------------------------------------------------------------
| 45.288889
| 80
| 0.704122
|
fanyu2021
|
0ece22317a4a499675e02478c50ab8b1ce3b8291
| 5,817
|
hh
|
C++
|
Archive/Stroika_FINAL_for_STERL_1992/Library/Framework/Headers/Splitter.hh
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 28
|
2015-09-22T21:43:32.000Z
|
2022-02-28T01:35:01.000Z
|
Archive/Stroika_FINAL_for_STERL_1992/Library/Framework/Headers/Splitter.hh
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 98
|
2015-01-22T03:21:27.000Z
|
2022-03-02T01:47:00.000Z
|
Archive/Stroika_FINAL_for_STERL_1992/Library/Framework/Headers/Splitter.hh
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 4
|
2019-02-21T16:45:25.000Z
|
2022-02-18T13:40:04.000Z
|
/* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
#ifndef __Splitter__
#define __Splitter__
/*
* $Header: /fuji/lewis/RCS/Splitter.hh,v 1.8 1992/09/08 15:34:00 lewis Exp $
*
* Description:
* Support for grouping a bunch of views together, with splitters seperating them, and
* allowing the user to resize and alot the space available among the given views. Views which
* are invisible do not participate in layout, and when the become visible, they are automnatically
* layed out.
*
* There is support for refining the behavior of splitting by subclassing either the Splitter View,
* or more likely, the AbstractSplitView. There is also, convieniecne support to just add any old
* view to a SplitterView, and have default behavior when splitting, and closing of panes occurrs.
*
*
* TODO:
*
*
* Notes:
*
* Changes:
* $Log: Splitter.hh,v $
* Revision 1.8 1992/09/08 15:34:00 lewis
* Renamed NULL -> Nil.
*
* Revision 1.7 1992/09/01 15:42:04 sterling
* Lots of Foundation changes.
*
* Revision 1.6 1992/07/21 20:55:17 sterling
* Use Sequence instead of obsolete SequencePtr.
*
* Revision 1.5 1992/07/21 19:59:01 sterling
* changed qGUI to qUI, supported qWinUI
*
* Revision 1.4 1992/07/16 16:25:55 sterling
* renamed GUI to UI, made Mac_UI and Motif_UI variants
*
* Revision 1.3 1992/07/03 00:13:32 lewis
* Renamed Sequence_DoublyLLOfPointers->SequencePtr.
*
* Revision 1.2 1992/06/25 07:01:13 sterling
* Renamed CalcDefaultSize to CalcDefaultSize_ (+more?)/
*
* Revision 1.1 1992/06/20 17:27:41 lewis
* Initial revision
*
* Revision 1.1 1992/04/30 14:46:28 sterling
* Initial revision
*
*/
#include "Sequence.hh"
#include "View.hh"
class AbstractSplitViewInfo {
public:
AbstractSplitViewInfo ();
virtual ~AbstractSplitViewInfo ();
nonvirtual Point GetMinSize () const;
nonvirtual void SetMinSize (const Point& size);
nonvirtual Point GetMaxSize () const;
nonvirtual void SetMaxSize (const Point& size);
nonvirtual View& GetView () const;
nonvirtual void Invariant () const
{
#if qDebug
Invariant_ ();
#endif
}
protected:
virtual Point GetMinSize_ () const = Nil;
virtual void SetMinSize_ (const Point& size) = Nil;
virtual Point GetMaxSize_ () const = Nil;
virtual void SetMaxSize_ (const Point& size) = Nil;
virtual View& GetView_ () const = Nil;
#if qDebug
virtual void Invariant_ () const;
#endif
};
class SplitViewInfo : public AbstractSplitViewInfo {
public:
SplitViewInfo (View& view);
protected:
override Point GetMinSize_ () const;
override void SetMinSize_ (const Point& size);
override Point GetMaxSize_ () const;
override void SetMaxSize_ (const Point& size);
override View& GetView_ () const;
private:
View* fView;
Point fMinSize;
Point fMaxSize;
};
#if !qRealTemplatesAvailable
#if qMPW_MacroOverflowProblem
#define PrivateSplitViewInfoPtr PSptVInfoPtr
#endif
typedef class PrivateSplitViewInfo* PrivateSplitViewInfoPtr;
Declare (Iterator, PrivateSplitViewInfoPtr);
Declare (Collection, PrivateSplitViewInfoPtr);
Declare (AbSequence, PrivateSplitViewInfoPtr);
Declare (Array, PrivateSplitViewInfoPtr);
Declare (Sequence_Array, PrivateSplitViewInfoPtr);
Declare (Sequence, PrivateSplitViewInfoPtr);
#endif
class AbstractSplitter : public View {
public:
AbstractSplitter (Point::Direction orientation);
override Boolean TrackPress (const MousePressInfo& mouseInfo);
override Boolean TrackMovement (const Point& cursorAt, Region& mouseRgn, const KeyBoard& keyBoardState);
nonvirtual Point::Direction GetOrientation () const;
nonvirtual void SetOrientation (Point::Direction orientation, UpdateMode update = eDelayedUpdate);
nonvirtual void AddSplitView (const SplitViewInfo& info, UpdateMode update = eDelayedUpdate);
nonvirtual void AddSplitView (View& view, UpdateMode update = eDelayedUpdate);
nonvirtual void RemoveSplitView (const SplitViewInfo& info, UpdateMode update = eDelayedUpdate);
nonvirtual void RemoveSplitView (View& view, UpdateMode update = eDelayedUpdate);
nonvirtual Coordinate GetGapHeight () const;
nonvirtual void SetGapHeight (Coordinate gapHeight, UpdateMode update = eDelayedUpdate);
protected:
override Point CalcDefaultSize_ (const Point& defaultSize) const;
override void Layout ();
override void Draw (const Region& update);
nonvirtual Real CalcProportion (Coordinate size);
virtual void DrawGap (const Rect& where) = Nil;
virtual void ResizeSplitter (const MousePressInfo& mouseInfo, CollectionSize index);
nonvirtual Rect CalcGapRect (const View& view) const;
private:
Point::Direction fOrientation;
Coordinate fGapHeight;
Sequence(PrivateSplitViewInfoPtr) fSplitViews;
};
class Splitter_MacUI : public AbstractSplitter {
public:
Splitter_MacUI (Point::Direction orientation);
protected:
override void DrawGap (const Rect& where);
};
class Splitter_MotifUI : public AbstractSplitter {
public:
Splitter_MotifUI (Point::Direction orientation);
nonvirtual Coordinate GetSashLength () const;
nonvirtual void SetSashLength (Coordinate sashLength, UpdateMode update = eDelayedUpdate);
protected:
override void DrawGap (const Rect& where);
private:
Coordinate fSashLength;
};
class Splitter_WinUI : public AbstractSplitter {
public:
Splitter_WinUI (Point::Direction orientation);
protected:
override void DrawGap (const Rect& where);
};
class Splitter :
#if qMacUI
public Splitter_MacUI
#elif qMotifUI
public Splitter_MotifUI
#elif qWinUI
public Splitter_WinUI
#endif
{
public:
Splitter (Point::Direction orientation);
};
#endif /* __Splitter__ */
| 26.085202
| 106
| 0.731649
|
SophistSolutions
|
0eded69aeb2f85e106b23f7072dfff725c55fa57
| 627
|
cpp
|
C++
|
cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/fun/trace_inv_quad_form_ldlt_test.cpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/fun/trace_inv_quad_form_ldlt_test.cpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/fun/trace_inv_quad_form_ldlt_test.cpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
#include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>
TEST(MathMatrix, trace_inv_quad_form_ldlt) {
stan::math::matrix_d A(4,4), B(4,2);
stan::math::LDLT_factor<double,-1,-1> ldlt_A;
A <<
9.0, 3.0, 3.0, 3.0,
3.0, 10.0, 2.0, 2.0,
3.0, 2.0, 7.0, 1.0,
3.0, 2.0, 1.0, 112.0;
B <<
100, 10,
0, 1,
-3, -3,
5, 2;
ldlt_A.compute(A);
ASSERT_TRUE(ldlt_A.success());
EXPECT_FLOAT_EQ(1439.1061766207,
trace_inv_quad_form_ldlt(ldlt_A,B));
EXPECT_FLOAT_EQ((B.transpose() * A.inverse() * B).trace(),
trace_inv_quad_form_ldlt(ldlt_A,B));
}
| 25.08
| 60
| 0.561404
|
yizhang-cae
|
0eded740698742409f3bd0f125357e6375f4f459
| 1,130
|
cpp
|
C++
|
server/Common/Packets/GCOtherSkill.cpp
|
viticm/web-pap
|
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
|
[
"BSD-3-Clause"
] | 3
|
2018-06-19T21:37:38.000Z
|
2021-07-31T21:51:40.000Z
|
server/Common/Packets/GCOtherSkill.cpp
|
viticm/web-pap
|
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
|
[
"BSD-3-Clause"
] | null | null | null |
server/Common/Packets/GCOtherSkill.cpp
|
viticm/web-pap
|
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
|
[
"BSD-3-Clause"
] | 13
|
2015-01-30T17:45:06.000Z
|
2022-01-06T02:29:34.000Z
|
#include "stdafx.h"
#include "GCOtherSkill.h"
BOOL GCOtherSkill::Read( SocketInputStream& iStream )
{
__ENTER_FUNCTION
iStream.Read( (CHAR*)(&m_ObjID), sizeof(ObjID_t) ) ;
iStream.Read( (CHAR*)(&m_byListNum), sizeof(BYTE) ) ;
if(m_byListNum > MAX_DAM_LIST_NUM) m_byListNum = MAX_DAM_LIST_NUM;
iStream.Read( (CHAR*)(m_listDam), sizeof(_DAMAGE_INFO)*m_byListNum ) ;
iStream.Read( (CHAR*)(&m_SkillID), sizeof(SkillID_t) ) ;
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
BOOL GCOtherSkill::Write( SocketOutputStream& oStream )const
{
__ENTER_FUNCTION
oStream.Write( (CHAR*)(&m_ObjID), sizeof(ObjID_t) ) ;
oStream.Write( (CHAR*)(&m_byListNum), sizeof(BYTE) ) ;
oStream.Write( (CHAR*)(m_listDam), sizeof(_DAMAGE_INFO)*(m_byListNum>MAX_DAM_LIST_NUM ? MAX_DAM_LIST_NUM : m_byListNum ) ) ;
oStream.Write( (CHAR*)(&m_SkillID), sizeof(SkillID_t) ) ;
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
UINT GCOtherSkill::Execute( Player* pPlayer )
{
__ENTER_FUNCTION
return GCOtherSkillHandler::Execute( this, pPlayer ) ;
__LEAVE_FUNCTION
return FALSE ;
}
| 20.545455
| 128
| 0.695575
|
viticm
|
0ee391c540791f2c4fcd15b9ccaeddd097c87abd
| 663
|
cpp
|
C++
|
src/otus_course_project_lib/src/handlers/stop_packet_handler.cpp
|
winmord/otus_course_project
|
8fc2c71b0aa33173c92e31469630fdfe676b77d6
|
[
"MIT"
] | null | null | null |
src/otus_course_project_lib/src/handlers/stop_packet_handler.cpp
|
winmord/otus_course_project
|
8fc2c71b0aa33173c92e31469630fdfe676b77d6
|
[
"MIT"
] | null | null | null |
src/otus_course_project_lib/src/handlers/stop_packet_handler.cpp
|
winmord/otus_course_project
|
8fc2c71b0aa33173c92e31469630fdfe676b77d6
|
[
"MIT"
] | null | null | null |
#include "otus_course_project_lib/handlers/stop_packet_handler.hpp"
#include "otus_course_project_lib/packets/control_packet_ids.hpp"
namespace packet_analyzer
{
stop_packet_handler::stop_packet_handler(std::shared_ptr<std::shared_ptr<i_state>> state)
: state_(std::move(state))
{
}
void stop_packet_handler::handle(const std::shared_ptr<i_packet> packet)
{
if(is_stop_packet(packet))
{
*this->state_ = nullptr;
}
else
{
abstract_handler::handle(packet);
}
}
bool stop_packet_handler::is_stop_packet(std::shared_ptr<i_packet> const& packet)
{
return packet->get_id() == static_cast<int>(control_packet_ids::stop_packet_id);
}
}
| 22.862069
| 90
| 0.755656
|
winmord
|
0ee4b2f4aefe25f567325fa6de90a9072f9debd1
| 1,956
|
cc
|
C++
|
src_tests/test_zstream.cc
|
MatteoRagni/Utils
|
3a25aa381d6d5d9a58d33a401cb99d8988590cac
|
[
"BSD-2-Clause"
] | null | null | null |
src_tests/test_zstream.cc
|
MatteoRagni/Utils
|
3a25aa381d6d5d9a58d33a401cb99d8988590cac
|
[
"BSD-2-Clause"
] | null | null | null |
src_tests/test_zstream.cc
|
MatteoRagni/Utils
|
3a25aa381d6d5d9a58d33a401cb99d8988590cac
|
[
"BSD-2-Clause"
] | 1
|
2021-10-14T16:13:19.000Z
|
2021-10-14T16:13:19.000Z
|
/*--------------------------------------------------------------------------*\
| |
| Copyright (C) 2017 |
| |
| , __ , __ |
| /|/ \ /|/ \ |
| | __/ _ ,_ | __/ _ ,_ |
| | \|/ / | | | | \|/ / | | | |
| |(__/|__/ |_/ \_/|/|(__/|__/ |_/ \_/|/ |
| /| /| |
| \| \| |
| |
| Enrico Bertolazzi |
| Dipartimento di Ingegneria Industriale |
| Universita` degli Studi di Trento |
| email: enrico.bertolazzi@unitn.it |
| |
\*--------------------------------------------------------------------------*/
#include "Utils.hh"
#include "Utils_zstream.hh"
#include <fstream>
int
main() {
try {
std::ofstream file("test.txt.gz");;
zstream::ogzstream gzfile(file);
gzfile << "pippo\n";
gzfile << "pluto\n";
gzfile << "paperino\n";
gzfile << "paperone\n";
gzfile << "nonna papera\n";
gzfile.close();
file.close();
} catch ( std::exception const & exc ) {
std::cout << "Error: " << exc.what() << '\n';
} catch ( ... ) {
std::cout << "Unknown error\n";
}
std::cout << "All done folks\n\n";
return 0;
}
| 43.466667
| 78
| 0.227505
|
MatteoRagni
|
0ee8e39f7906ff50ef23cdac459a61a013d2a328
| 5,708
|
cpp
|
C++
|
timeintegrationrk3.cpp
|
piccolo255/mhd2d-solver
|
be635bb6f5f8d3d06a9fa02a15801eedd1f50306
|
[
"Unlicense"
] | null | null | null |
timeintegrationrk3.cpp
|
piccolo255/mhd2d-solver
|
be635bb6f5f8d3d06a9fa02a15801eedd1f50306
|
[
"Unlicense"
] | null | null | null |
timeintegrationrk3.cpp
|
piccolo255/mhd2d-solver
|
be635bb6f5f8d3d06a9fa02a15801eedd1f50306
|
[
"Unlicense"
] | null | null | null |
#include "timeintegrationrk3.hpp"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TimeIntegrationRK3::TimeIntegrationRK3
( size_t nx
, size_t ny
, size_t bufferWidth
, double dtMin
, double dtMax
, double cflNumber
, std::unique_ptr<SpatialIntegrationMethod> method
)
: TimeIntegrationMethod{ nx, ny, bufferWidth, dtMin, dtMax, cflNumber, std::move( method ) }
{
U1 = createMatrices( PRB_DIM, nxTotal, nyTotal );
U2 = createMatrices( PRB_DIM, nxTotal, nyTotal );
UL = createMatrices( PRB_DIM, nxTotal, nyTotal );
borderFlux1.left = createVectors( PRB_DIM, nyTotal );
borderFlux1.right = createVectors( PRB_DIM, nyTotal );
borderFlux1.up = createVectors( PRB_DIM, nxTotal );
borderFlux1.down = createVectors( PRB_DIM, nxTotal );
borderFlux2.left = createVectors( PRB_DIM, nyTotal );
borderFlux2.right = createVectors( PRB_DIM, nyTotal );
borderFlux2.up = createVectors( PRB_DIM, nxTotal );
borderFlux2.down = createVectors( PRB_DIM, nxTotal );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TimeIntegrationRK3::~TimeIntegrationRK3
(
){
freeMatrices( U1 );
freeMatrices( U2 );
freeMatrices( UL );
freeVectors( borderFlux1.left );
freeVectors( borderFlux1.right );
freeVectors( borderFlux1.up );
freeVectors( borderFlux1.down );
freeVectors( borderFlux2.left );
freeVectors( borderFlux2.right );
freeVectors( borderFlux2.up );
freeVectors( borderFlux2.down );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
t_status TimeIntegrationRK3::step
( t_matrices U
, t_matrices cx
, t_matrices cy
, t_matrices LUx
, t_matrices LUy
, borderVectors borderFlux
, double &dtCurrent
){
auto dt = dtCurrent;
auto dtIdeal = double{0.0};
auto retval = t_status{};
auto dtFirstStep = dtCurrent;
auto dtSecondStep = dtMax;
auto dtFinalStep = dtMax;
auto done = bool{false};
// First step: spatial integration, check for errors
retval = method->integrate( U, UL, borderFlux, dtIdeal );
if( retval.isError ){
retval.message += "\n! TimeIntegrationRK3::step: (first) spatial integration";
return retval;
}
// First step: update time step, check for errors
retval = updateDt( dtFirstStep, dtIdeal );
if( retval.isError ){
retval.message += "\n! TimeIntegrationRK3::step: (first) update time step";
return retval;
}
while( !done ){
dt = std::min({ dtFirstStep, dtSecondStep, dtFinalStep });
// First step: update variables
for( auto k = size_t{0}; k < PRB_DIM; k++ )
for( auto i = nxFirst; i < nxLast; i++ )
for( auto j = nyFirst; j < nyLast; j++ )
U1[k][i][j] = U[k][i][j] + dt*UL[k][i][j];
// Second step: spatial integration, check for errors
retval = method->integrate( U1, UL, borderFlux1, dtIdeal );
if( retval.isError ){
retval.message += "\n! TimeIntegrationRK3::step: (second) spatial integration";
return retval;
}
// Second step: update time step, check for errors
retval = updateDt( dtSecondStep, dtIdeal );
if( retval.isError ){
retval.message += "\n! TimeIntegrationRK3::step: (second) update time step";
return retval;
}
if( dtSecondStep < dt ){
continue;
}
// Second step: update variables
for( auto k = size_t{0}; k < PRB_DIM; k++ )
for( auto i = nxFirst; i < nxLast; i++ )
for( auto j = nyFirst; j < nyLast; j++ )
U2[k][i][j] = (3.0/4.0)*U[k][i][j] + (1.0/4.0)*U1[k][i][j] + (1.0/4.0)*dt*UL[k][i][j];
// Final step: spatial integration, check for errors
retval = method->integrate( U2, UL, borderFlux2, dtIdeal );
if( retval.isError ){
retval.message += "\n! TimeIntegrationRK3::step: (last) spatial integration";
return retval;
}
// Final step: update time step, check for errors
retval = updateDt( dtFinalStep, dtIdeal );
if( retval.isError ){
retval.message += "\n! TimeIntegrationRK3::step: (last) update time step";
return retval;
}
if( dtFinalStep < dt ){
continue;
}
// Final step: update variables
for( auto k = size_t{0}; k < PRB_DIM; k++ )
for( auto i = nxFirst; i < nxLast; i++ )
for( auto j = nyFirst; j < nyLast; j++ )
U[k][i][j] = (1.0/3.0)*U[k][i][j] + (2.0/3.0)*U2[k][i][j] + (2.0/3.0)*dt*UL[k][i][j];
for( auto k = size_t{0}; k < PRB_DIM; k++ ){
for( auto i = nxFirst; i < nxLast; i++ ){
borderFlux.up[k][i] = (1.0/6.0)*borderFlux.up[k][i] + (1.0/6.0)*borderFlux1.up[k][i] + (2.0/3.0)*borderFlux2.up[k][i];
borderFlux.down[k][i] = (1.0/6.0)*borderFlux.down[k][i] + (1.0/6.0)*borderFlux1.down[k][i] + (2.0/3.0)*borderFlux2.down[k][i];
}
for( auto j = nyFirst; j < nyLast; j++ ){
borderFlux.left[k][j] = (1.0/6.0)*borderFlux.left[k][j] + (1.0/6.0)*borderFlux1.left[k][j] + (2.0/3.0)*borderFlux2.left[k][j];
borderFlux.right[k][j] = (1.0/6.0)*borderFlux.right[k][j] + (1.0/6.0)*borderFlux1.right[k][j] + (2.0/3.0)*borderFlux2.right[k][j];
}
}
done = true;
}
dtCurrent = dt;
method->getCharacteristicsX( cx, LUx );
method->getCharacteristicsY( cy, LUy );
// Everything OK
return { false, ReturnStatus::OK, "" };
}
| 36.356688
| 142
| 0.553083
|
piccolo255
|
0ee93f28a62d01a83eaf76024cfffac421c87270
| 5,783
|
cpp
|
C++
|
executer/compiler/DefaultCompilerAlgorithm.cpp
|
eladraz/morph
|
e80b93af449471fb2ca9e256188f9a92f631fbc2
|
[
"BSD-3-Clause"
] | 4
|
2017-01-24T09:32:23.000Z
|
2021-08-20T03:29:54.000Z
|
executer/compiler/DefaultCompilerAlgorithm.cpp
|
eladraz/morph
|
e80b93af449471fb2ca9e256188f9a92f631fbc2
|
[
"BSD-3-Clause"
] | null | null | null |
executer/compiler/DefaultCompilerAlgorithm.cpp
|
eladraz/morph
|
e80b93af449471fb2ca9e256188f9a92f631fbc2
|
[
"BSD-3-Clause"
] | 1
|
2021-08-20T03:29:55.000Z
|
2021-08-20T03:29:55.000Z
|
/*
* Copyright (c) 2008-2016, Integrity Project Ltd. 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 the Integrity Project 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 OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE
*/
/*
* DefaultCompilerAlgorithm.cpp
*
* Implementation file
*
* Author: Elad Raz <e@eladraz.com>
*/
#include "executer/stdafx.h"
#include "xStl/types.h"
#include "xStl/os/lock.h"
#include "xStl/data/datastream.h"
#include "xStl/except/trace.h"
#include "xStl/except/assert.h"
#include "xStl/stream/traceStream.h"
#include "format/EncodingUtils.h"
#include "compiler/CallingConvention.h"
#include "runnable/GlobalContext.h"
#include "executer/ExecuterTrace.h"
#include "executer/runtime/MethodBinder.h"
#include "executer/runtime/Executer.h"
#include "executer/compiler/DefaultCompilerAlgorithm.h"
#include "executer/linker/MemoryLinker.h"
DefaultCompilerAlgorithm::DefaultCompilerAlgorithm(const TokenIndex& mainMethod,
ApartmentPtr mainApartment,
CompilerEngineThread& engine,
const LinkerInterfacePtr& linker) :
m_shouldExit(false),
m_mainMethod(mainMethod),
m_mainApartment(mainApartment),
m_engine(engine),
m_externalModuleResolver(mainApartment),
m_linker(linker)
{
// Start scanning functions and find: static .cctor for structure initializing
// and framework implemented functions.
// Store the first method into the list
m_methodStack.push(mainMethod);
// Make sure that the event is in it's reset mode.
m_event.resetEvent();
}
bool DefaultCompilerAlgorithm::getNextMethod(TokenIndex& mid)
{
// Check for previous death
if (m_shouldExit)
{
// This shouldn't be happening.
ExecuterTrace("DefaultCompilerAlgorithm: Called even if all functions has resolved" << endl);
ASSERT(false);
return false;
}
// TODO! Simple implementation
cLock lock(m_lock);
if (m_methodStack.isEmpty())
{
m_shouldExit = true;
// Time to execute out main function!
m_linker->resolveAndExecuteAllDependencies(m_mainMethod);
return false;
}
mid = m_methodStack.getArg(0);
m_methodStack.pop2null();
return true;
}
bool DefaultCompilerAlgorithm::shouldExit() const
{
return m_shouldExit;
}
void DefaultCompilerAlgorithm::onMethodCompiled(const TokenIndex& mid,
SecondPassBinary& compiled, bool inCache)
{
// NOTE! If the method is in the repository then it ALL of it's sub-methods
// are also in the repository. Change this method if methods are paged
// out from the pool
if (!inCache)
{
// Try to find all sub-methods
const BinaryDependencies::DependencyObjectList& dependencies = compiled.getDependencies().getList();
BinaryDependencies::DependencyObjectList::iterator i = dependencies.begin();
for (; i != dependencies.end(); ++i)
{
// Check for CIL methods links
TokenIndex methodToken;
if (CallingConvention::deserializeMethod((*i).m_name, methodToken))
{
m_methodStack.push(m_clrResolver.resolve(m_mainApartment, methodToken));
} else if (CallingConvention::deserializeToken((*i).m_name, methodToken))
{
// Check for vtbl
// #### Todo: This is only needed for vtbl entries that were actually used in the code!
// Any virtual method which was not called anywhere in the code, should be optimized away
if (EncodingUtils::getTokenTableIndex(getTokenID(methodToken)) == TABLE_TYPEDEF_TABLE)
{
const ResolverInterface::VirtualTable& vTbl =
m_mainApartment->getObjects().getTypedefRepository().getVirtualTable(methodToken);
ResolverInterface::VirtualTable::iterator j = vTbl.begin();
for (; j != vTbl.end(); j++)
{
m_methodStack.push(getVtblMethodIndexOverride(*j));
}
}
}
}
}
}
void DefaultCompilerAlgorithm::onCompilationFailed(const TokenIndex& mid)
{
// Break event!
m_shouldExit = true;
}
| 38.046053
| 116
| 0.667647
|
eladraz
|
0eee62c4b667affe946ec5560421af053ed8059e
| 13,724
|
cc
|
C++
|
src/mem/ruby/network/garnet2.0/Router.cc
|
farabimahmud/smart
|
d968ed5123363e9c05512b355c5d67360902d90f
|
[
"BSD-3-Clause"
] | null | null | null |
src/mem/ruby/network/garnet2.0/Router.cc
|
farabimahmud/smart
|
d968ed5123363e9c05512b355c5d67360902d90f
|
[
"BSD-3-Clause"
] | null | null | null |
src/mem/ruby/network/garnet2.0/Router.cc
|
farabimahmud/smart
|
d968ed5123363e9c05512b355c5d67360902d90f
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2008 Princeton University
* Copyright (c) 2016 Georgia Institute of Technology
* 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 the copyright holders 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
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Niket Agarwal
* Tushar Krishna
*/
#include "mem/ruby/network/garnet2.0/Router.hh"
#include "base/stl_helpers.hh"
#include "debug/FlitOrder.hh"
#include "debug/RubyNetwork.hh"
#include "debug/SMART.hh"
#include "mem/ruby/network/garnet2.0/CreditLink.hh"
#include "mem/ruby/network/garnet2.0/CrossbarSwitch.hh"
#include "mem/ruby/network/garnet2.0/GarnetNetwork.hh"
#include "mem/ruby/network/garnet2.0/InputUnit.hh"
#include "mem/ruby/network/garnet2.0/NetworkLink.hh"
#include "mem/ruby/network/garnet2.0/OutputUnit.hh"
#include "mem/ruby/network/garnet2.0/RoutingUnit.hh"
#include "mem/ruby/network/garnet2.0/SwitchAllocator.hh"
using namespace std;
using m5::stl_helpers::deletePointers;
Router::Router(const Params *p)
: BasicRouter(p), Consumer(this)
{
m_latency = p->latency;
m_virtual_networks = p->virt_nets;
m_vc_per_vnet = p->vcs_per_vnet;
m_num_vcs = m_virtual_networks * m_vc_per_vnet;
m_routing_unit = new RoutingUnit(this);
m_sw_alloc = new SwitchAllocator(this);
m_switch = new CrossbarSwitch(this);
m_input_unit.clear();
m_output_unit.clear();
lastflit = NULL;
}
Router::~Router()
{
deletePointers(m_input_unit);
deletePointers(m_output_unit);
delete m_routing_unit;
delete m_sw_alloc;
delete m_switch;
}
void
Router::init()
{
BasicRouter::init();
m_sw_alloc->init();
m_switch->init();
}
void
Router::wakeup()
{
DPRINTF(RubyNetwork, "Router %d woke up\n", m_id);
// check for incoming flits
for (int inport = 0; inport < m_input_unit.size(); inport++) {
m_input_unit[inport]->wakeup();
}
// check for incoming credits
// Note: the credit update is happening before SA
// buffer turnaround time =
// credit traversal (1-cycle) + SA (1-cycle) + Link Traversal (1-cycle)
// if we want the credit update to take place after SA, this loop should
// be moved after the SA request
for (int outport = 0; outport < m_output_unit.size(); outport++) {
m_output_unit[outport]->wakeup();
}
// Switch Allocation
m_sw_alloc->wakeup();
// Switch Traversal
m_switch->wakeup();
}
void
Router::addInPort(PortDirection inport_dirn,
NetworkLink *in_link, CreditLink *credit_link)
{
int port_num = m_input_unit.size();
InputUnit *input_unit = new InputUnit(port_num, inport_dirn, this);
input_unit->set_in_link(in_link);
input_unit->set_credit_link(credit_link);
in_link->setLinkConsumer(this);
in_link->setLinkConsumerInport(input_unit);
credit_link->setSourceQueue(input_unit->getCreditQueue());
m_input_unit.push_back(input_unit);
m_routing_unit->addInDirection(inport_dirn, port_num);
}
void
Router::addOutPort(PortDirection outport_dirn,
NetworkLink *out_link,
const NetDest& routing_table_entry, int link_weight,
CreditLink *credit_link)
{
int port_num = m_output_unit.size();
OutputUnit *output_unit = new OutputUnit(port_num, outport_dirn, this);
output_unit->set_out_link(out_link);
output_unit->set_credit_link(credit_link);
credit_link->setLinkConsumer(this);
out_link->setSourceQueue(output_unit->getOutQueue());
m_output_unit.push_back(output_unit);
m_routing_unit->addRoute(routing_table_entry);
m_routing_unit->addWeight(link_weight);
m_routing_unit->addOutDirection(outport_dirn, port_num);
}
PortDirection
Router::getOutportDirection(int outport)
{
return m_output_unit[outport]->get_direction();
}
PortDirection
Router::getInportDirection(int inport)
{
return m_input_unit[inport]->get_direction();
}
int
Router::route_compute(RouteInfo *route, int inport, PortDirection inport_dirn)
{
return m_routing_unit->outportCompute(route, inport, inport_dirn);
}
void
Router::grant_switch(int inport, flit *t_flit)
{
m_switch->update_sw_winner(inport, t_flit);
}
void
Router::schedule_wakeup(Cycles time)
{
// wake up after time cycles
scheduleEvent(time);
}
std::string
Router::getPortDirectionName(PortDirection direction)
{
// PortDirection is actually a string
// If not, then this function should add a switch
// statement to convert direction to a string
// that can be printed out
return direction;
}
void
Router::insertSSR(PortDirection inport_dirn, SSR* t_ssr)
{
DPRINTF(RubyNetwork, "Router %d Inport %s received SSR from src_hops %d for bypass = %d for Outport %s\n",
get_id(), inport_dirn, t_ssr->get_src_hops(), t_ssr->get_bypass_req(), t_ssr->get_outport_dirn());
int inport = m_routing_unit->getInportIdx(inport_dirn);
int outport = m_routing_unit->getOutportIdx(t_ssr->get_outport_dirn());
t_ssr->set_inport(inport);
// Update SSR if dest bypass enabled
if (t_ssr->get_src_hops() > 0 && !t_ssr->get_bypass_req()) {
// dest or turning router
RouteInfo* route = t_ssr->get_ref_flit()->get_route();
bool is_dest = (route->dest_router == m_id);
if (get_net_ptr()->isSMARTdestBypass() && is_dest) {
outport = m_routing_unit->lookupRoutingTable(route->vnet, route->net_dest);
PortDirection outport_dirn = m_output_unit[outport]->get_direction();
t_ssr->set_outport_dirn(outport_dirn);
t_ssr->set_bypass_req(true);
} else {
delete t_ssr;
return;
}
}
m_output_unit[outport]->insertSSR(t_ssr);
}
bool
Router::smart_vc_select(int inport, int outport, flit *t_flit)
{
DPRINTF(FlitOrder, "RT flit %d-%d smart_vc_select at R%d\n",
t_flit->get_pid(),
t_flit->get_id(),
get_id());
// VC Selection
DPRINTF(SMART, "[Router] smart_vc_select(%d, %d, %s\n",
inport, outport, *t_flit);
int vnet = t_flit->get_vnet();
bool has_free_vc = m_output_unit[outport]->has_free_vc(vnet);
if (!has_free_vc)
return false;
// Update VC in flit
int invc = t_flit->get_vc();
int outvc = invc;
if ((t_flit->get_type() == HEAD_) ||
(t_flit->get_type() == HEAD_TAIL_)) {
outvc = m_output_unit[outport]->select_free_vc(vnet);
t_flit->set_vc(outvc);
}
m_output_unit[outport]->decrement_credit(outvc);
// Send credit for VCid flit came with
// Verify input VC is free and IDLE
assert(!(m_input_unit[inport]->isReady(invc, curCycle())));
assert(m_input_unit[inport]->is_vc_idle(invc));
// Send credit for VCid flit came with
if ((t_flit->get_type() == HEAD_TAIL_ ) ||
(t_flit->get_type() == TAIL_))
m_input_unit[inport]->increment_credit(
invc, true, curCycle(), t_flit);
else
m_input_unit[inport]->increment_credit(
invc, false, curCycle(), t_flit);
DPRINTF(RubyNetwork, "[Router] Smart VC Select is returned\n");
return true;
}
void
Router::smart_route_update(int inport, int outport, flit* t_flit)
{
// Update route in flit
// Call route_compute so that x_hops/y_hops decremented
DPRINTF(RubyNetwork, "[Router] flit %s at Inport %d %s\n" ,
*t_flit, inport, m_input_unit[inport]->get_direction());
int check_outport = route_compute(t_flit->get_route(),
inport, m_input_unit[inport]->get_direction());
DPRINTF(RubyNetwork, "check_outport %d outport %d\n",
check_outport, outport);
assert(check_outport == outport);
t_flit->set_outport(outport);
}
bool
Router::try_smart_bypass(int inport, PortDirection outport_dirn, flit *t_flit)
{
int outport = m_routing_unit->getOutportIdx(outport_dirn);
// Update VC
bool has_vc = smart_vc_select(inport, outport, t_flit);
if (!has_vc){
DPRINTF(FlitOrder, "RT flit %d-%d is did not have vc R%d\n",
t_flit->get_pid(), t_flit->get_id(),
get_id());
return false;
}
else{
DPRINTF(FlitOrder, "RT flit %d-%d is have vc R%d\n",
t_flit->get_pid(), t_flit->get_id(),
get_id());
}
// Update Route
smart_route_update(inport, outport, t_flit);
DPRINTF(RubyNetwork, "Router %d Inport %s and Outport %d successful SMART Bypass for Flit %s\n",
get_id(), getPortDirectionName(m_input_unit[inport]->get_direction()), outport_dirn, *t_flit);
DPRINTF(SMART, "[Router] try_smart_bypass VC= %d\n", t_flit->get_vc());
// Add flit to output link
if (t_flit->get_type() == HEAD_ || t_flit->get_type() == HEAD_TAIL_){
if (lastflit != NULL) return false;
lastflit = t_flit;
}
else{
if (t_flit->get_id() == lastflit->get_id() ||
t_flit->get_id() == lastflit->get_id() + 1){
lastflit = t_flit;
}
else return false;
}
if (t_flit->get_type() == TAIL_ ||
t_flit->get_type() == HEAD_TAIL_){
lastflit = NULL;
}
DPRINTF(FlitOrder, "flit %d-%d is being sent to Router %d\n",
t_flit->get_pid(), t_flit->get_id(),
get_id());
m_output_unit[outport]->smart_bypass(t_flit);
t_flit->increment_hops(); // for stats
return true;
}
void
Router::regStats()
{
BasicRouter::regStats();
m_buffer_reads
.name(name() + ".buffer_reads")
.flags(Stats::nozero)
;
m_buffer_writes
.name(name() + ".buffer_writes")
.flags(Stats::nozero)
;
m_crossbar_activity
.name(name() + ".crossbar_activity")
.flags(Stats::nozero)
;
m_sw_input_arbiter_activity
.name(name() + ".sw_input_arbiter_activity")
.flags(Stats::nozero)
;
m_sw_output_arbiter_activity
.name(name() + ".sw_output_arbiter_activity")
.flags(Stats::nozero)
;
}
void
Router::collateStats()
{
for (int j = 0; j < m_virtual_networks; j++) {
for (int i = 0; i < m_input_unit.size(); i++) {
m_buffer_reads += m_input_unit[i]->get_buf_read_activity(j);
m_buffer_writes += m_input_unit[i]->get_buf_write_activity(j);
}
}
m_sw_input_arbiter_activity = m_sw_alloc->get_input_arbiter_activity();
m_sw_output_arbiter_activity = m_sw_alloc->get_output_arbiter_activity();
m_crossbar_activity = m_switch->get_crossbar_activity();
}
void
Router::resetStats()
{
for (int j = 0; j < m_virtual_networks; j++) {
for (int i = 0; i < m_input_unit.size(); i++) {
m_input_unit[i]->resetStats();
}
}
m_switch->resetStats();
m_sw_alloc->resetStats();
}
void
Router::printFaultVector(ostream& out)
{
int temperature_celcius = BASELINE_TEMPERATURE_CELCIUS;
int num_fault_types = m_network_ptr->fault_model->number_of_fault_types;
float fault_vector[num_fault_types];
get_fault_vector(temperature_celcius, fault_vector);
out << "Router-" << m_id << " fault vector: " << endl;
for (int fault_type_index = 0; fault_type_index < num_fault_types;
fault_type_index++) {
out << " - probability of (";
out <<
m_network_ptr->fault_model->fault_type_to_string(fault_type_index);
out << ") = ";
out << fault_vector[fault_type_index] << endl;
}
}
void
Router::printAggregateFaultProbability(std::ostream& out)
{
int temperature_celcius = BASELINE_TEMPERATURE_CELCIUS;
float aggregate_fault_prob;
get_aggregate_fault_probability(temperature_celcius,
&aggregate_fault_prob);
out << "Router-" << m_id << " fault probability: ";
out << aggregate_fault_prob << endl;
}
uint32_t
Router::functionalWrite(Packet *pkt)
{
uint32_t num_functional_writes = 0;
num_functional_writes += m_switch->functionalWrite(pkt);
for (uint32_t i = 0; i < m_input_unit.size(); i++) {
num_functional_writes += m_input_unit[i]->functionalWrite(pkt);
}
for (uint32_t i = 0; i < m_output_unit.size(); i++) {
num_functional_writes += m_output_unit[i]->functionalWrite(pkt);
}
return num_functional_writes;
}
Router *
GarnetRouterParams::create()
{
return new Router(this);
}
| 30.7713
| 110
| 0.671379
|
farabimahmud
|
0eef7273e5337dd1e9b81049609ae6474dcb4963
| 2,512
|
cpp
|
C++
|
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/add_transformation.cpp
|
slyubimt/openvino
|
f068a498940d6fa8ac4e831d9dcf2b35a00ed220
|
[
"Apache-2.0"
] | null | null | null |
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/add_transformation.cpp
|
slyubimt/openvino
|
f068a498940d6fa8ac4e831d9dcf2b35a00ed220
|
[
"Apache-2.0"
] | 34
|
2020-11-19T12:27:40.000Z
|
2022-02-21T13:14:04.000Z
|
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/add_transformation.cpp
|
mznamens/openvino
|
ec126c6252aa39a6c63ddf124350a92687396771
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "low_precision_transformations/add_transformation.hpp"
#include <memory>
#include <tuple>
#include <vector>
#include <string>
#include <ie_core.hpp>
#include <transformations/init_node_info.hpp>
#include "lpt_ngraph_functions/add_function.hpp"
#include "ngraph_functions/subgraph_builders.hpp"
namespace LayerTestsDefinitions {
std::string AddTransformation::getTestCaseName(const testing::TestParamInfo< AddTransformationParams>& obj) {
ngraph::element::Type netPrecision;
ngraph::PartialShape inputShapes;
std::string targetDevice;
auto params = LayerTestsUtils::LayerTransformationParamsNGraphFactory::createParamsU8I8();
AddTestValues param;
std::tie(netPrecision, inputShapes, targetDevice, param) = obj.param;
std::ostringstream result;
result << getTestCaseNameByParams(netPrecision, inputShapes, targetDevice, params) <<
(param.broadcast ? "_broadcast" : "");
for (const auto& elem : param.precisionOnActivations) {
result << "_" << elem << "_";
}
result << "expected_precisions_";
for (const auto& elem : param.expectedPrecisions) {
result << "_" << elem << "_";
}
if (!param.fakeQuantize1.empty()) {
result << "_on_branch1_" <<
param.fakeQuantize1.inputLowValues[0] << "_" <<
param.fakeQuantize1.inputHighValues[0] << "_" <<
param.fakeQuantize1.outputLowValues[0] << "_" <<
param.fakeQuantize1.outputHighValues[0];
}
if (!param.fakeQuantize2.empty()) {
result << "_on_branch2_" <<
param.fakeQuantize2.inputLowValues[0] << "_" <<
param.fakeQuantize2.inputHighValues[0] << "_" <<
param.fakeQuantize2.outputLowValues[0] << "_" <<
param.fakeQuantize2.outputHighValues[0];
}
return result.str();
}
void AddTransformation::SetUp() {
ngraph::element::Type precision;
ngraph::PartialShape inputShape;
AddTestValues param;
std::tie(precision, inputShape, targetDevice, param) = this->GetParam();
function = ngraph::builder::subgraph::AddFunction::getOriginal(
precision, inputShape, param.broadcast,
param.fakeQuantize1, param.fakeQuantize2);
ngraph::pass::InitNodeInfo().run_on_function(function);
functionRefs = ngraph::clone_function(*function);
}
TEST_P(AddTransformation, CompareWithRefImpl) {
Run();
};
} // namespace LayerTestsDefinitions
| 33.945946
| 109
| 0.68551
|
slyubimt
|
0ef5ce71a16493ecee1603ef966ab0963c00e384
| 764
|
cpp
|
C++
|
sources/Mouse.cpp
|
NiwakaDev/NIWAKA_X86
|
ae07dcd5e006c6b48459c18efd4a65e4492ce7b4
|
[
"MIT"
] | 2
|
2022-02-19T04:57:16.000Z
|
2022-02-19T05:45:39.000Z
|
sources/Mouse.cpp
|
NiwakaDev/NIWAKA_X86
|
ae07dcd5e006c6b48459c18efd4a65e4492ce7b4
|
[
"MIT"
] | 1
|
2022-02-19T04:59:05.000Z
|
2022-02-19T11:02:17.000Z
|
sources/Mouse.cpp
|
NiwakaDev/NIWAKA_X86
|
ae07dcd5e006c6b48459c18efd4a65e4492ce7b4
|
[
"MIT"
] | null | null | null |
#include "Pic.h"
#include "Mouse.h"
Mouse::Mouse(Pic* pic){
this->pic = pic;
assert(this->pic!=NULL);
this->enable_flg = false;
}
void Mouse::Out8(unsigned int addr, unsigned char data){
this->Error("Stopped at Mouse::Out8");
}
unsigned char Mouse::In8(unsigned int addr){
switch(addr){
case 0x60:
return this->data;
default:
this->Error("addr(0x%02X) is not implemented at Mouse::In8", addr);
}
}
bool Mouse::IsEnable(){
return this->enable_flg;
}
void Mouse::SetEnable(){
this->enable_flg = true;
}
void Mouse::Receive(unsigned char data){
this->pic->Set(12);
this->data = data;
}
void Mouse::HandleMouseMotion(unsigned char state, unsigned char dx, unsigned char dy){
}
| 20.105263
| 87
| 0.626963
|
NiwakaDev
|
0ef6031a84b2fe235faee44ebfc5dabe2ac328d2
| 4,066
|
cc
|
C++
|
src/lib/shader.cc
|
jube/mapmaker
|
e2eb6b1fbc3d803d56817aea86b350bd26ad5fa4
|
[
"ISC"
] | 15
|
2015-03-18T18:07:30.000Z
|
2020-10-15T16:59:19.000Z
|
src/lib/shader.cc
|
jube/mapmaker
|
e2eb6b1fbc3d803d56817aea86b350bd26ad5fa4
|
[
"ISC"
] | null | null | null |
src/lib/shader.cc
|
jube/mapmaker
|
e2eb6b1fbc3d803d56817aea86b350bd26ad5fa4
|
[
"ISC"
] | 1
|
2020-01-16T17:37:11.000Z
|
2020-01-16T17:37:11.000Z
|
/*
* Copyright (c) 2014, Julien Bernard
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <mm/shader.h>
#include <iostream>
#include <fstream>
#include <cassert>
#include <mm/normalize.h>
#include <mm/curve.h>
namespace mm {
static color lerp(const color& lhs, const color& rhs, double t) {
return {
lerp(lhs.red_channel(), rhs.red_channel(), t),
lerp(lhs.green_channel(), rhs.green_channel(), t),
lerp(lhs.blue_channel(), rhs.blue_channel(), t),
lerp(lhs.alpha_channel(), rhs.alpha_channel(), t)
};
}
static const vector3 light = {-1, -1, 0};
colormap shader::operator()(const colormap& src, const heightmap& map) const {
assert(src.width() == map.width());
assert(src.height() == map.height());
heightmap factor(size_only, map);
for (heightmap::size_type x = 0; x < map.width(); ++x) {
for (heightmap::size_type y = 0; y < map.height(); ++y) {
double xx = x;
double yy = y;
// compute the normal vector
double nx = 0;
double ny = 0;
double nz = 0;
unsigned count = 0;
vector3 p{xx, yy, map(x, y)};
if (x > 0 && y > 0) {
vector3 pw{xx - 1, yy , map(x - 1, y )};
vector3 pn{xx , yy - 1, map(x , y - 1)};
vector3 v3 = cross(p - pw, p - pn);
assert(v3.z > 0);
nx += v3.x;
ny += v3.y;
nz += v3.z;
count += 1;
}
if (x > 0 && y < src.height() - 1) {
vector3 pw{xx - 1, yy , map(x - 1, y )};
vector3 ps{xx , yy + 1, map(x , y + 1)};
vector3 v3 = cross(p - ps, p - pw);
assert(v3.z > 0);
nx += v3.x;
ny += v3.y;
nz += v3.z;
count += 1;
}
if (x < src.width() - 1 && y > 0) {
vector3 pe{xx + 1, yy , map(x + 1, y )};
vector3 pn{xx , yy - 1, map(x , y - 1)};
vector3 v3 = cross(p - pn, p - pe);
assert(v3.z > 0);
nx += v3.x;
ny += v3.y;
nz += v3.z;
count += 1;
}
if (x < src.width() - 1 && y < src.height() - 1) {
vector3 pe{xx + 1, yy , map(x + 1, y )};
vector3 ps{xx , yy + 1, map(x , y + 1)};
vector3 v3 = cross(p - pe, p - ps);
assert(v3.z > 0);
nx += v3.x;
ny += v3.y;
nz += v3.z;
count += 1;
}
vector3 normal = unit({nx / count, ny / count, nz / count});
double d = dot(light, normal);
d = 0.5 + 35 * d;
if (d > 1) {
d = 1;
}
if (d < 0) {
d = 0;
}
factor(x, y) = d;
}
}
colormap result(size_only, src);
for (colormap::size_type x = 0; x < src.width(); ++x) {
for (colormap::size_type y = 0; y < src.height(); ++y) {
if (map(x, y) < m_sea_level) {
result(x, y) = src(x, y);
continue;
}
double d = factor(x, y);
auto lo = lerp(src(x, y), {0x33, 0x11, 0x33}, 0.7);
auto hi = lerp(src(x, y), {0xFF, 0xFF, 0xCC}, 0.3);
if (d < 0.5) {
result(x, y) = lerp(lo, src(x, y), 2 * d);
} else {
result(x, y) = lerp(src(x, y), hi, 2 * d - 1);
}
}
}
return result;
}
}
| 26.575163
| 80
| 0.490408
|
jube
|
0efa0eb26e19988f843998738a12ccfa700dacb6
| 885
|
cpp
|
C++
|
TinyEngine/src/math/SphericalCoordinate.cpp
|
Kimau/KhronosSandbox
|
e06caed3ab85e620ac2c5860fd31cef6ed6418c3
|
[
"Apache-2.0"
] | 68
|
2020-04-14T11:03:26.000Z
|
2020-06-11T16:17:29.000Z
|
TinyEngine/src/math/SphericalCoordinate.cpp
|
Kimau/KhronosSandbox
|
e06caed3ab85e620ac2c5860fd31cef6ed6418c3
|
[
"Apache-2.0"
] | 5
|
2020-05-16T05:32:16.000Z
|
2020-05-21T11:09:52.000Z
|
TinyEngine/src/math/SphericalCoordinate.cpp
|
Kimau/KhronosSandbox
|
e06caed3ab85e620ac2c5860fd31cef6ed6418c3
|
[
"Apache-2.0"
] | 1
|
2021-03-19T22:47:00.000Z
|
2021-03-19T22:47:00.000Z
|
#include "SphericalCoordinate.h"
#include <cmath>
// https://en.wikipedia.org/wiki/Spherical_coordinate_system#Cartesian_coordinates
SphericalCoordinate::SphericalCoordinate(float theta, float phi, float rho) :
theta(theta), phi(phi), rho(rho)
{
}
SphericalCoordinate::SphericalCoordinate(const glm::vec3& cartesian)
{
rho = glm::length(cartesian);
theta = acosf(cartesian.z / rho);
phi = atanf(cartesian.y / cartesian.x);
}
SphericalCoordinate::~SphericalCoordinate()
{
}
SphericalCoordinate::operator glm::vec3() const
{
return toCartesianCoordinate();
}
glm::vec3 SphericalCoordinate::toCartesianCoordinate() const
{
float x = rho * sinf(theta) * cosf(phi);
float y = rho * sinf(theta) * sinf(phi);
float z = rho * cosf(theta);
return glm::vec3(x, y, z);
}
SphericalCoordinate SphericalCoordinate::normalize() const
{
return SphericalCoordinate(theta, phi);
}
| 20.113636
| 82
| 0.736723
|
Kimau
|
0efa41989f4a97fb86a1afda9994f8fd1199bbd5
| 511
|
cpp
|
C++
|
set1/fixed_xor_test.cpp
|
guzhoucan/cryptopals
|
a45280158867a86b5d8c61bf7194277d05abdf14
|
[
"MIT"
] | 1
|
2020-08-07T22:38:27.000Z
|
2020-08-07T22:38:27.000Z
|
set1/fixed_xor_test.cpp
|
guzhoucan/cryptopals
|
a45280158867a86b5d8c61bf7194277d05abdf14
|
[
"MIT"
] | null | null | null |
set1/fixed_xor_test.cpp
|
guzhoucan/cryptopals
|
a45280158867a86b5d8c61bf7194277d05abdf14
|
[
"MIT"
] | null | null | null |
#include "fixed_xor.h"
#include "absl/strings/escaping.h"
#include "gtest/gtest.h"
namespace cryptopals {
namespace {
TEST(FixedXorTest, Test) {
std::string str1 =
absl::HexStringToBytes("1c0111001f010100061a024b53535009181c");
std::string str2 =
absl::HexStringToBytes("686974207468652062756c6c277320657965");
std::string result =
absl::HexStringToBytes("746865206b696420646f6e277420706c6179");
EXPECT_EQ(result, FixedXor(str1, str2));
}
} // namespace
} // namespace cryptopals
| 25.55
| 69
| 0.739726
|
guzhoucan
|
0efec0e1d0a0d75f12b4de3dad7dcd9e2eba9bf3
| 9,358
|
hpp
|
C++
|
source/NanairoCore/Material/SurfaceModel/Surface/microcylinder.hpp
|
byzin/Nanairo
|
23fb6deeec73509c538a9c21009e12be63e8d0e4
|
[
"MIT"
] | 30
|
2015-09-06T03:14:29.000Z
|
2021-06-18T11:00:19.000Z
|
source/NanairoCore/Material/SurfaceModel/Surface/microcylinder.hpp
|
byzin/Nanairo
|
23fb6deeec73509c538a9c21009e12be63e8d0e4
|
[
"MIT"
] | 31
|
2016-01-14T14:50:34.000Z
|
2018-06-25T13:21:48.000Z
|
source/NanairoCore/Material/SurfaceModel/Surface/microcylinder.hpp
|
byzin/Nanairo
|
23fb6deeec73509c538a9c21009e12be63e8d0e4
|
[
"MIT"
] | 6
|
2017-04-09T13:07:47.000Z
|
2021-05-29T21:17:34.000Z
|
///*!
// \file microcylinder.hpp
// \author Sho Ikeda
//
// Copyright (c) 2015-2018 Sho Ikeda
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
// */
//
//#ifndef NANAIRO_MICROCYLINDER_HPP
//#define NANAIRO_MICROCYLINDER_HPP
//
//// Standard C++ library
//#include <tuple>
//#include <utility>
//// Nanairo
//#include "NanairoCore/nanairo_core_config.hpp"
//#include "NanairoCore/Sampling/sampled_direction.hpp"
//#include "NanairoCore/Sampling/sampled_spectra.hpp"
//
//namespace nanairo {
//
////! \addtogroup Core
////! \{
//
///*!
// */
//class Microcylinder
//{
// public:
// //! Evaluate the reflectance
// static Float evalPdf(const Vector3& vin,
// const Vector3& vout,
// const Vector3& normal,
// const Float k_d,
// const Float gamma_r,
// const Float gamma_v) noexcept;
//
// //! Evaluate the reflectance
// static SampledSpectra evalReflectance(
// const Vector3& vin,
// const Vector3& vout,
// const Vector3& normal,
// const SampledSpectra& albedo,
// const Float n,
// const Float k_d,
// const Float gamma_r,
// const Float gamma_v,
// const Float rho,
// Float* pdf = nullptr) noexcept;
//
// //! Sample a direction
// static std::tuple<SampledDirection, SampledSpectra>
// sample(const Vector3& vin,
// const Vector3& normal,
// const SampledSpectra& albedo,
// const Float n,
// const Float k_d,
// const Float gamma_r,
// const Float gamma_v,
// const Float rho,
// Sampler& sampler) noexcept;
//
// //! Evaluate the azimuthal pdf
// static Float evalAzimuthalAnglePdf(const Float phi_i,
// const Float phi_o) noexcept;
//
// //! Evaluate the pdf of the surface angles
// static Float evalSurfaceAnglesPdf(const Float theta_i,
// const Float phi_i,
// const Float theta_o,
// const Float phi_o,
// const Float gamma) noexcept;
//
// //! Calculate the longitudinal angle pdf of the surface reflection
// static Float evalSurfaceLongitudinalAnglePdf(const Float theta_i,
// const Float theta_o,
// const Float gamma) noexcept;
//
// //! Evaluate the pdf of the volume angles
// static Float evalVolumeAnglesPdf(const Float theta_i,
// const Float phi_i,
// const Float theta_o,
// const Float phi_o,
// const Float k_d,
// const Float gamma) noexcept;
//
// constexpr static Float evalVolumeIsotropicLongitudinalAnglePdf(
// const Float theta_i,
// const Float theta_o) noexcept;
//
// //! Calculate the longitudinal angle pdf of the volumetric reflection
// static Float evalVolumeLongitudinalAnglePdf(const Float theta_i,
// const Float theta_o,
// const Float k_d,
// const Float gamma) noexcept;
//
// private:
// //! Calculate the incident and outgoing angles
// static std::tuple<Float, Float, Float, Float>
// calcAngles(const Vector3& vin, const Vector3& vout, const Vector3& normal) noexcept;
//
// //! Calculate the effective angle
// static Float calcEffectiveAngle(const Float theta_i, const Float theta_o) noexcept;
//
// //! Calculate the half-angle
// static Float calcHalfAngle(const Float theta_i, const Float theta_o) noexcept;
//
// //! Calculate the fresnel reflectance
// static Float calcFresnelReflectance(const Float theta_i,
// const Float phi_i,
// const Float theta_o,
// const Float phi_o,
// const Float n) noexcept;
//
// //! Calculate the pdf
// static Float calcPdf(const Float theta_i,
// const Float phi_i,
// const Float theta_o,
// const Float phi_o,
// const Float k_d,
// const Float gamma_r,
// const Float gamma_v) noexcept;
//
// //! Evaluate the reflectance
// static SampledSpectra calcReflectance(
// const Float theta_i,
// const Float phi_i,
// const Float theta_o,
// const Float phi_o,
// const SampledSpectra& albedo,
// const Float n,
// const Float k_d,
// const Float gamma_r,
// const Float gamma_v,
// const Float rho) noexcept;
//
// //! Evaluate the D function
// static Float evalD(const Float x, const Float y, const Float z) noexcept;
//
// //! Evaluate the gaussian function
// static Float evalGaussian(const Float mu,
// const Float rho,
// const Float x) noexcept;
//
// //! Evaluate the shadowing masking function
// static Float evalShadowingMasking(const Float phi_i,
// const Float phi_o,
// const Float rho) noexcept;
//
// //! Evaluate the reflectance of the surface scattering
// static Float evalSurfaceScattering(const Float theta_i,
// const Float phi_i,
// const Float theta_o,
// const Float phi_o,
// const Float gamma) noexcept;
//
// //! Evaluate the uni gaussian function
// static Float evalUnitGaussian(const Float mu,
// const Float rho,
// const Float x) noexcept;
//
// //! Evaluate the reflectance of the volume scattering
// static Float evalVolumeScattering(const Float theta_i,
// const Float phi_i,
// const Float theta_o,
// const Float phi_o,
// const Float n,
// const Float k_d,
// const Float gamma) noexcept;
//};
//
///*!
// */
//class SampledMicrocylinderDir
//{
// public:
// //! Initialize
// SampledMicrocylinderDir(const SampledDirection& direction,
// const Float theta_i,
// const Float phi_i,
// const Float theta_o,
// const Float phi_o) noexcept;
//
//
// //! Return the direction
// const SampledDirection& direction() const noexcept;
//
// //! Return the phi_i
// Float phiI() const noexcept;
//
// //! Return the phi_o
// Float phiO() const noexcept;
//
// //! Sample a direction
// static SampledMicrocylinderDir sample(const Vector3& vin,
// const Vector3& normal,
// const Float k_d,
// const Float gamma_r,
// const Float gamma_v,
// Sampler& sampler) noexcept;
//
// //! Return the theta_i
// Float thetaI() const noexcept;
//
// //! Return the theta_o
// Float thetaO() const noexcept;
//
// private:
// //! Sample a direction angles
// static std::tuple<Float, Float, Float> sampleAngles(
// const Float theta_i,
// const Float phi_i,
// const Float k_d,
// const Float gamma_r,
// const Float gamma_v,
// Sampler& sampler) noexcept;
//
// //! Sample a azimuthal angle
// static std::tuple<Float, Float> sampleAzimuthalAngle(
// const Float phi_i,
// Sampler& sampler) noexcept;
//
// //! Sample a direction angles
// static std::tuple<Float, Float, Float> sampleSurfaceAngles(
// const Float theta_i,
// const Float phi_i,
// const Float gamma,
// Sampler& sampler) noexcept;
//
// //! Sample a longitudinal angle
// static std::tuple<Float, Float> sampleSurfaceLongitudinalAngle(
// const Float theta_i,
// const Float gamma,
// Sampler& sampler) noexcept;
//
// //! Sample a direction angles
// static std::tuple<Float, Float, Float> sampleVolumeAngles(
// const Float theta_i,
// const Float phi_i,
// const Float k_d,
// const Float gamma,
// Sampler& sampler) noexcept;
//
// //! Sample a longitudinal angle
// static std::tuple<Float, Float> sampleVolumeIsotropicLongitudinalAngle(
// const Float theta_i,
// Sampler& sampler) noexcept;
//
// //! Sample a longitudinal angle
// static std::tuple<Float, Float> sampleVolumeLongitudinalAngle(
// const Float theta_i,
// const Float k_d,
// const Float gamma,
// Sampler& sampler) noexcept;
//
//
// SampledDirection direction_;
// Float theta_i_;
// Float phi_i_;
// Float theta_o_;
// Float phi_o_;
//};
//
////! \} Core
//
//} // namespace nanairo
//
//#include "microcylinder-inl.hpp"
//
//#endif // NANAIRO_MICROCYLINDER_HPP
| 34.404412
| 88
| 0.543172
|
byzin
|
0efff81ac4c3b0f07d92761306b2ff776a092c86
| 13,590
|
cpp
|
C++
|
Tasks/Task-396-Azure_IoT_Hub/main.cpp
|
KTP20/Embedded-Systems
|
0b2d78c813c056bfc1779370986bde4970716638
|
[
"Apache-2.0"
] | null | null | null |
Tasks/Task-396-Azure_IoT_Hub/main.cpp
|
KTP20/Embedded-Systems
|
0b2d78c813c056bfc1779370986bde4970716638
|
[
"Apache-2.0"
] | null | null | null |
Tasks/Task-396-Azure_IoT_Hub/main.cpp
|
KTP20/Embedded-Systems
|
0b2d78c813c056bfc1779370986bde4970716638
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2020 Arm Limited
* SPDX-License-Identifier: Apache-2.0
*/
#include "mbed.h"
#include "rtos/ThisThread.h"
#include "NTPClient.h"
#include "certs.h"
#include "iothub.h"
#include "iothub_client_options.h"
#include "iothub_device_client.h"
#include "iothub_message.h"
#include "azure_c_shared_utility/shared_util_options.h"
#include "azure_c_shared_utility/threadapi.h"
#include "azure_c_shared_utility/tickcounter.h"
#include "azure_c_shared_utility/xlogging.h"
#include "iothubtransportmqtt.h"
#include "azure_cloud_credentials.h"
#include <cstdio>
#include <cstring>
#include <string.h>
#include "uop_msb.h"
/**
* This example sends and receives messages to and from Azure IoT Hub.
* The API usages are based on Azure SDK's official iothub_convenience_sample.
*/
// Global symbol referenced by the Azure SDK's port for Mbed OS, via "extern"
NetworkInterface *_defaultSystemNetwork;
static bool message_received = false;
int temp[] ={0,0};
int light[] = {0,0};
int pressure[] = {0,0};
char RESPONSE_STRING[] = "Failue to send command";
static void on_connection_status(IOTHUB_CLIENT_CONNECTION_STATUS result, IOTHUB_CLIENT_CONNECTION_STATUS_REASON reason, void* user_context)
{
if (result == IOTHUB_CLIENT_CONNECTION_AUTHENTICATED) {
LogInfo("Connected to IoT Hub");
} else {
LogError("Connection failed, reason: %s", MU_ENUM_TO_STRING(IOTHUB_CLIENT_CONNECTION_STATUS_REASON, reason));
}
}
// **************************************
// * MESSAGE HANDLER (no response sent) *
// **************************************
DigitalOut led2(LED2);
static IOTHUBMESSAGE_DISPOSITION_RESULT on_message_received(IOTHUB_MESSAGE_HANDLE message, void* user_context)
{
LogInfo("Message received from IoT Hub");
const unsigned char *data_ptr;
size_t len;
if (IoTHubMessage_GetByteArray(message, &data_ptr, &len) != IOTHUB_MESSAGE_OK) {
LogError("Failed to extract message data, please try again on IoT Hub");
return IOTHUBMESSAGE_ABANDONED;
}
message_received = true;
LogInfo("Message body: %.*s", len, data_ptr);
if (strncmp("true", (const char*)data_ptr, len) == 0) {
led2 = 1;
} else {
led2 = 0;
}
return IOTHUBMESSAGE_ACCEPTED;
}
static void on_message_sent(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback)
{
if (result == IOTHUB_CLIENT_CONFIRMATION_OK) {
LogInfo("Message sent successfully");
} else {
LogInfo("Failed to send message, error: %s",
MU_ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result));
}
}
// ****************************************************
// * COMMAND HANDLER (sends a response back to Azure) *
// ****************************************************
DigitalOut led1(LED1);
DigitalOut led3(LED3);
DigitalIn blueButton(USER_BUTTON);
uop_msb::LCD_16X2_DISPLAY lcd;
void LcdValue(const char* payload)
{
lcd.cls();
lcd.printf("value: %s",(const char*)payload);
}
void RedLEDToggle(const char* payload, size_t size)
{
if (strncmp("true", (const char*)payload, size) == 0 ) {
printf("LED3 ON\n");
led3 = 1;
} else {
printf("LED3 OFF\n");
led3 = 0;
}
}
void GreenLEDToggle(const char* payload, size_t size)
{
if ( strncmp("true", (const char*)payload, size) == 0 ) {
printf("LED1 ON\n");
led1 = 1;
} else {
printf("LED1 OFF\n");
led1 = 0;
}
}
int SetThreshold(const char* payload, int size, int* temp, int* light, int* pressure)
{
printf("entered SetLow\n");
int j = 0;
int l = 0;
char xtemp[10];
char ytemp[10];
char ztemp[10];
for (int i=0;i<2;i++)
{
int startOfPhrase = j;
while(payload[l] != ':')
{
l++;
}
while(payload[j] != ','){
j++;
if(j>size){
break;
}
}
int counter = 0;
for(int k=l+1;k<j;k++)
{
switch(i){
case 0:
xtemp[counter] = payload[k];
break;
case 1:
ytemp[counter] = payload[k];
break;
case 2:
ztemp[counter] = payload[k];
break;
default:
printf("Error");
break;
}
counter++;
}
j++;
l++;
}
while(payload[l] != ':')
{
l++;
}
while(payload[j] != '}'){
j++;
if(j>size){
break;
}
}
int counter = 0;
for(int k=l+1;k<j;k++)
{
ztemp[counter] = payload[k];
counter++;
}
int x = std::atoi(xtemp);
int y = std::atoi(ytemp);
int z = std::atoi(ztemp);
printf("x = %d, y = %d, z = %d\n",x,y,z);
*temp = x;
*light = y;
*pressure = z;
return 1;
}
void Plot(const char* payload, int size, bool* success)
{
bool Recieved =false;
if(strncmp("\"T\"", (const char*)payload, size) == 0 ){
printf("Temperature output");
//assign Temperature to the LED Matrix
//maybe a message or a function call
Recieved = true;
}
else if(strncmp("\"P\"", (const char*)payload, size) == 0 ){
printf("Pressure Output");
//same applies
//TBC
Recieved = true;
}
else if(strncmp("\"L\"", (const char*)payload, size) == 0 ){
printf("Light output");
Recieved = true;
}
else{
printf("Error in the Plot function, invalid Character");
Recieved = false;
}
*success = Recieved;
}
static int on_method_callback(const char* method_name, const unsigned char* payload, size_t size, unsigned char** response, size_t* response_size, void* userContextCallback)
{
const char* device_id = (const char*)userContextCallback;
const char * input_string = (const char *) payload;
char RESPONSE_STRING[] = "\"Failue to send command\"";
bool messageSent = 1;
printf("\r\nDevice Method called for device %s\r\n", device_id);
printf("Device Method name: %s\r\n", method_name);
printf("Device Method payload: %.*s\r\n", (int)size, input_string);
if (strncmp("ToggleLED",(const char*)method_name, 11) == 0) {
GreenLEDToggle((const char*)payload, (size_t)size);
strcpy(RESPONSE_STRING, "{ \"Response\" : \"Command Recieved\" }");
}
else if (strncmp("ToggleLED3",(const char*)method_name, 11) == 0) {
RedLEDToggle(input_string,size);
strcpy(RESPONSE_STRING, "{ \"Response\" : \"Command Recieved\" }");
}
else if(strncmp("TestValue",(const char*)method_name, 11) == 0) {
LcdValue(input_string);
strcpy(RESPONSE_STRING, "{ \"Response\" : \"Command Recieved\" }");
}
else if(strncmp("SetLowVector",(const char*)method_name, 12) == 0){
SetThreshold(input_string,size,&(temp[0]),&(light[0]),&(pressure[0]));
printf("low threshold: temp is %d, light is %d, pressure is %d",temp[0], light[0],pressure[0]);
strcpy(RESPONSE_STRING, "{ \"Response\" : \"Command Recieved\" }");
}
else if(strncmp("SetHighVector",(const char*)method_name, 13) == 0){
SetThreshold(input_string,size,&(temp[1]),&(light[1]),&(pressure[1]));
printf("highthreshold: temp is %d, light is %d, pressure is %d\n",temp[1], light[1],pressure[1]);
strcpy(RESPONSE_STRING, "{ \"Response\" : \"Command Recieved\" }");
}
else if (strncmp("Plot",(const char*)method_name, 13) == 0){
bool success = false;
printf("PLOT payload is %s\t size is %u\n",payload,size);
Plot(input_string,size,&success);
if (success == true){
strcpy(RESPONSE_STRING, "{ \"Response\" :\"Commmand Recieved\"");
} else {
strcpy(RESPONSE_STRING, "{ \"Response\" :\"Invalid Character for the plot function, please choose a T,P or L\"");
}
}
else {
printf("error somewhere lol");
strcpy(RESPONSE_STRING, "{ \"Responce\" : \"Failue to send command\" }");
}
int status = 200;
printf("\r\nResponse status: %d\r\n", status);
printf("Response payload: %s\r\n\r\n", RESPONSE_STRING);
int rlen = strlen(RESPONSE_STRING);
*response_size = rlen;
if ((*response = (unsigned char*)malloc(rlen)) == NULL) {
status = -1;
}
else {
memcpy(*response, RESPONSE_STRING, *response_size);
}
return status;
}
void demo() {
bool trace_on = MBED_CONF_APP_IOTHUB_CLIENT_TRACE;
tickcounter_ms_t interval = 100;
IOTHUB_CLIENT_RESULT res;
LogInfo("Initializing IoT Hub client");
IoTHub_Init();
IOTHUB_DEVICE_CLIENT_HANDLE client_handle = IoTHubDeviceClient_CreateFromConnectionString(
azure_cloud::credentials::iothub_connection_string,
MQTT_Protocol
);
if (client_handle == nullptr) {
LogError("Failed to create IoT Hub client handle");
goto cleanup;
}
// Enable SDK tracing
res = IoTHubDeviceClient_SetOption(client_handle, OPTION_LOG_TRACE, &trace_on);
if (res != IOTHUB_CLIENT_OK) {
LogError("Failed to enable IoT Hub client tracing, error: %d", res);
goto cleanup;
}
// Enable static CA Certificates defined in the SDK
res = IoTHubDeviceClient_SetOption(client_handle, OPTION_TRUSTED_CERT, certificates);
if (res != IOTHUB_CLIENT_OK) {
LogError("Failed to set trusted certificates, error: %d", res);
goto cleanup;
}
// Process communication every 100ms
res = IoTHubDeviceClient_SetOption(client_handle, OPTION_DO_WORK_FREQUENCY_IN_MS, &interval);
if (res != IOTHUB_CLIENT_OK) {
LogError("Failed to set communication process frequency, error: %d", res);
goto cleanup;
}
// set incoming message callback
res = IoTHubDeviceClient_SetMessageCallback(client_handle, on_message_received, nullptr);
if (res != IOTHUB_CLIENT_OK) {
LogError("Failed to set message callback, error: %d", res);
goto cleanup;
}
// Set incoming command callback
res = IoTHubDeviceClient_SetDeviceMethodCallback(client_handle, on_method_callback, nullptr);
if (res != IOTHUB_CLIENT_OK) {
LogError("Failed to set method callback, error: %d", res);
goto cleanup;
}
// Set connection/disconnection callback
res = IoTHubDeviceClient_SetConnectionStatusCallback(client_handle, on_connection_status, nullptr);
if (res != IOTHUB_CLIENT_OK) {
LogError("Failed to set connection status callback, error: %d", res);
goto cleanup;
}
// Send ten message to the cloud (one per second)
// or until we receive a message from the cloud
IOTHUB_MESSAGE_HANDLE message_handle;
char message[80];
for (int i = 0; i < 10; ++i) {
if (message_received) {
// If we have received a message from the cloud, don't send more messeges
break;
}
//Send data in this format:
/*
{
"LightLevel" : 0.12,
"Temperature" : 36.0,
"Pressure" : 3.5
}
*/
double light = (float) i;
double temp = (float)36.0f-0.1*(float)i;
double pressure = (float) i+2;
sprintf(message, "{ \"LightLevel\" : %5.2f, \"Temperature\" : %5.2f, \"Pressure\" : %5.2f}", light, temp, pressure);
LogInfo("Sending: \"%s\"", message);
message_handle = IoTHubMessage_CreateFromString(message);
if (message_handle == nullptr) {
LogError("Failed to create message");
goto cleanup;
}
res = IoTHubDeviceClient_SendEventAsync(client_handle, message_handle, on_message_sent, nullptr);
IoTHubMessage_Destroy(message_handle); // message already copied into the SDK
if (res != IOTHUB_CLIENT_OK) {
LogError("Failed to send message event, error: %d", res);
goto cleanup;
}
ThisThread::sleep_for(60s);
}
// If the user didn't manage to send a cloud-to-device message earlier,
// let's wait until we receive one
while (!message_received) {
// Continue to receive messages in the communication thread
// which is internally created and maintained by the Azure SDK.
sleep();
}
cleanup:
IoTHubDeviceClient_Destroy(client_handle);
IoTHub_Deinit();
}
int main() {
printf("Stating, print \n");
LogInfo("Connecting to the network");
_defaultSystemNetwork = NetworkInterface::get_default_instance();
if (_defaultSystemNetwork == nullptr) {
LogError("No network interface found");
return -1;
}
int ret = _defaultSystemNetwork->connect();
if (ret != 0) {
LogError("Connection error: %d", ret);
return -1;
}
LogInfo("Connection success, MAC: %s", _defaultSystemNetwork->get_mac_address());
LogInfo("Getting time from the NTP server");
NTPClient ntp(_defaultSystemNetwork);
ntp.set_server("time.google.com", 123);
time_t timestamp = ntp.get_timestamp();
if (timestamp < 0) {
LogError("Failed to get the current time, error: %u", timestamp);
return -1;
}
LogInfo("Time: %s", ctime(×tamp));
printf("Testing printing\n");
LogInfo("Testing Logging\n");
set_time(timestamp);
LogInfo("Starting the Demo");
demo();
LogInfo("The demo has ended");
return 0;
}
| 30.886364
| 173
| 0.598602
|
KTP20
|
160b52fdee3ec7528c05fcc28699e68bdcb9b449
| 1,569
|
cpp
|
C++
|
src/examples/echoer.cpp
|
Bormachine-Learning/embedded
|
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
src/examples/echoer.cpp
|
Bormachine-Learning/embedded
|
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
src/examples/echoer.cpp
|
Bormachine-Learning/embedded
|
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
/**
Copyright 2019 Bosch Engineering Center Cluj and BFMC organizers
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.
******************************************************************************
* @file Echoer.cpp
* @author RBRO/PJ-IU
* @version V1.0.0
* @date day-month-year
* @brief This file contains the class implementation for the serial echoer
* functionality.
******************************************************************************
*/
#include <examples/echoer.hpp>
namespace examples{
/** \brief Class constructor
*
* Constructor method
*
* \param f_period echoer execution period
* \param f_serialPort Serial communication object
*/
CEchoer::CEchoer(uint32_t f_period, Serial& f_serialPort)
: utils::task::CTask(f_period)
, m_serialPort(f_serialPort)
{
}
/** \brief Periodically applied method. It sends a simple message to other device.
*
*/
void CEchoer::_run()
{
m_serialPort.printf(".\n\r");
}
}; // namespace examples
| 32.020408
| 88
| 0.615041
|
Bormachine-Learning
|
160c1fe370c324b569fb164b83aa96cf6381c560
| 1,743
|
hpp
|
C++
|
src/models/BorderEntity.hpp
|
sergiofenoll/Gradius
|
5d904f87e6791c5c8ac8f4738f525c7ef3e04b7c
|
[
"CC-BY-4.0"
] | null | null | null |
src/models/BorderEntity.hpp
|
sergiofenoll/Gradius
|
5d904f87e6791c5c8ac8f4738f525c7ef3e04b7c
|
[
"CC-BY-4.0"
] | null | null | null |
src/models/BorderEntity.hpp
|
sergiofenoll/Gradius
|
5d904f87e6791c5c8ac8f4738f525c7ef3e04b7c
|
[
"CC-BY-4.0"
] | null | null | null |
#ifndef BORDER_ENTITY_HPP
#define BORDER_ENTITY_HPP
#include "Entity.hpp"
#include "../utils/Stopwatch.hpp"
namespace sff {
namespace game {
/**
* @brief Entity that represents the deadly borders of the game window
*/
class BorderEntity : public Entity {
public:
using shared = std::shared_ptr<BorderEntity>;
using unique = std::unique_ptr<BorderEntity>;
using weak = std::weak_ptr<BorderEntity>;
/**
* @brief Construct a new BorderEntity
* @param config_filename The name (and path) of the config file for the BorderEntity
* @param bottom True if this is the bottom border, false if is the upper border
*/
BorderEntity(std::string config_filename, bool bottom);
/**
* @brief No-op
* The border doesn't move, so move() is overridden to do nothing
*/
void move() override;
/**
* @brief Checks the collision between this and other
* Because the border is a rectangle, collision is detected
* using a different algorithm than between two circles
* For more information see: https://stackoverflow.com/a/402010/7258143
* @param other The other entity that will be used to check collision
* @return True if both entities collide, false otherwise
*/
bool collides(const Entity::shared other) const override;
/**
* @brief No-op
* The border shouldn't fade when hit by the player
*/
void fade() override;
/**
* @brief No-op
* The border loses health when the player collides with it,
* overriding is_dead() makes more sense than constantly
* checking for BorderEntities while detecting collision
* @return Always false
*/
bool is_dead() const override;
};
}
}
#endif //GRADIUS_BORDERENTITY_HPP
| 27.666667
| 88
| 0.689616
|
sergiofenoll
|
160c7b5063344dae7e25c1d0e36f2d1e38b06655
| 3,041
|
cpp
|
C++
|
core/tests/core.container.graph.test.cpp
|
toeb/cpp.core
|
84c782b1e0919dd598c3c19c8e5c71f27453ebf2
|
[
"MIT"
] | 2
|
2016-10-25T19:42:49.000Z
|
2017-03-25T22:26:03.000Z
|
core/tests/core.container.graph.test.cpp
|
toeb/cpp.core
|
84c782b1e0919dd598c3c19c8e5c71f27453ebf2
|
[
"MIT"
] | null | null | null |
core/tests/core.container.graph.test.cpp
|
toeb/cpp.core
|
84c782b1e0919dd598c3c19c8e5c71f27453ebf2
|
[
"MIT"
] | null | null | null |
#include <core.testing.h>
#include <core.graph.h>
NS_BEGIN(CORE_NAMESPACE)
namespace graph{
namespace test{
TEST(CreateNode, DataNode){
DataNode<int> uut(2);
CHECK(uut.data() == 2);
}
TEST(CreateNode2, DataNode){
DataNode<int> uut(2);
uut = 9;
CHECK(uut.data() == 9);
}
TEST(CreateNode3, DataNode){
DataNode<int> uut(2);
uut = 9;
int a = uut;
CHECK(a == 9);
}
TEST(Connect1, DataNode){
DataNode<int> uut1(1);
DataNode<int> uut2(2);
uut1 << uut2;
CHECK(uut1.predecessors().contains(&uut2));
CHECK(uut2.successors().contains(&uut1));
}
TEST(DisConnect1, DataNode){
DataNode<int> uut1(1);
DataNode<int> uut2(2);
uut1 << uut2;
uut2.successors() /= &uut1;
CHECK(!uut1.predecessors().contains(&uut2));
CHECK(!uut2.successors().contains(&uut1));
}
TEST(DisConnect2, DataNode){
DataNode<int> uut1(1);
DataNode<int> uut2(2);
uut1 << uut2;
uut2.remove(&uut1);
CHECK(!uut1.predecessors().contains(&uut2));
CHECK(!uut2.successors().contains(&uut1));
}
TEST(DFS1, DataNode){
DataNode<int> uut1 = 1;
DataNode<int> uut2 = 2;
DataNode<int> uut3 = 3;
DataNode<int> uut4 = 4;
DataNode<int> uut5 = 5;
DataNode<int> uut6 = 6;
DataNode<int> uut7 = 7;
uut1 >> uut2;
uut1 >> uut3;
uut2 >> uut4;
uut2 >> uut5;
uut3 >> uut6;
uut3 >> uut7;
Set<DataNode<int> *> order;
uut1.dfs([&order](bool & b, DataNode<int> * node){
order |= node;
}, [](Set<DataNode<int>* > & successors, const DataNode<int> & current){
successors |= current.successors();
});
int current = 0;
int actualorder[] = { 1, 2, 4, 5, 3, 6, 7 };
order.foreachElement([&](DataNode<int> * n){
int cv = n->data();
CHECK_EQUAL(actualorder[current++], cv);
});
}
TEST(BFS1, DataNode){
DataNode<int> uut1 = 1;
DataNode<int> uut2 = 2;
DataNode<int> uut3 = 3;
DataNode<int> uut4 = 4;
DataNode<int> uut5 = 5;
DataNode<int> uut6 = 6;
DataNode<int> uut7 = 7;
uut1 >> uut2;
uut1 >> uut3;
uut2 >> uut4;
uut2 >> uut5;
uut3 >> uut6;
uut3 >> uut7;
Set<DataNode<int> *> order;
uut1.bfs([&order](bool & b, DataNode<int> * node){
order |= node;
}, [](Set<DataNode<int>* > & successors, const DataNode<int> & current){
successors |= current.successors();
});
int current = 0;
int actualorder[] = { 1, 2, 3, 4, 5, 6, 7 };
order.foreachElement([&](DataNode<int> * n){
int cv = n->data();
CHECK_EQUAL(actualorder[current++], cv);
});
}
}
}
NS_END(CORE_NAMESPACE)
| 22.864662
| 80
| 0.494574
|
toeb
|
161032992d8d0127b400a01fc25f69e4152b3b5c
| 2,204
|
cpp
|
C++
|
reto1.cpp
|
Ignacio-Moral-22/TC1031_Reto
|
5a7fe2400e8235d0868bd33c80359f43dfc4b23f
|
[
"MIT"
] | null | null | null |
reto1.cpp
|
Ignacio-Moral-22/TC1031_Reto
|
5a7fe2400e8235d0868bd33c80359f43dfc4b23f
|
[
"MIT"
] | null | null | null |
reto1.cpp
|
Ignacio-Moral-22/TC1031_Reto
|
5a7fe2400e8235d0868bd33c80359f43dfc4b23f
|
[
"MIT"
] | null | null | null |
#include "read_csv.hpp"
#include "clase_archivo.hpp"
#include "sorter.hpp"
#include <vector>
#include <iostream>
#include <string>
/*
Para esta actividad, se nos encargó de generar un programa que leyera una carga de archivos,
y que pudiera responder ciertas preguntas, además de que implementamos métodos de búsqueda
y ordenamiento para poder manipular el archivo.
Para poder resolver este avance del reto, primero leímos el archivo,
y guardamos los valores en una clase llamada Registros.
Esta clase de Registros era estilo template, para que podamos utilizar
el estilo de variable que más creamos conveniente. En este caso, decidimos utilizar std::string,
pues así permite guardar tanto variables numéricas como de texto. Luego, hicimos un vector de clases,
para poder guardar y organizar los valores a nuestro parecer. Ya que teníamos el vector,
pudimos responder las diversas preguntas que se nos hizo.
Ignacio Joaquin Moral
A01028470
Fecha de creacion: 17 de septiembre de 2020
Fecha de modificacion final: 27 de septiembre de 2020
*/
bool compareHostNameFuente(Registros<std::string> &a, Registros<std::string> &b){
return a.fuenteHost()<b.fuenteHost();
};
bool compareIPFuente(Registros<std::string> &a, Registros<std::string> &b){
return a.fuenteIP()<b.fuenteIP();
};
bool comparePuertoDestino(Registros<std::string> &a, Registros<std::string> &b){
return a.destinoPuerto()<b.destinoPuerto();
};
bool compareHostNameDestino(Registros<std::string> &a, Registros<std::string> &b){
return a.destinoHost()<b.destinoHost();
};
int main(){
std::vector<class Registros<std::string>> registros;
registros=readRecords();
int dia2;
dia2=segundoDia(registros);
std::cout << "Hay " << dia2 << " registros en el segundo dia." << std::endl;
Sorter<Registros<std::string>> organizar;
organizar.ordenaQuick(registros, &compareHostNameFuente);
countNames(registros);
organizar.ordenaQuick(registros, &compareIPFuente);
direccionIP(registros);
organizar.ordenaQuick(registros, &compareHostNameDestino);
correos(registros);
organizar.ordenaQuick(registros, &comparePuertoDestino);
countPuertos(registros);
return 0;
}
| 34.4375
| 102
| 0.75
|
Ignacio-Moral-22
|
161486f8214ca94b8dff8441dbc585fbf2dfc8b4
| 232
|
hpp
|
C++
|
include/tolua/LuaUtils.hpp
|
TerensTare/tnt
|
916067a9bf697101afb1d0785112aa34014e8126
|
[
"MIT"
] | 29
|
2020-04-22T01:31:30.000Z
|
2022-02-03T12:21:29.000Z
|
include/tolua/LuaUtils.hpp
|
TerensTare/tnt
|
916067a9bf697101afb1d0785112aa34014e8126
|
[
"MIT"
] | 6
|
2020-04-17T10:31:56.000Z
|
2021-09-10T12:07:22.000Z
|
include/tolua/LuaUtils.hpp
|
TerensTare/tnt
|
916067a9bf697101afb1d0785112aa34014e8126
|
[
"MIT"
] | 7
|
2020-03-13T01:50:41.000Z
|
2022-03-06T23:44:29.000Z
|
#ifndef TNT_EXPORT_UTILS_TO_LUA
#define TNT_EXPORT_UTILS_TO_LUA
#include <sol/forward.hpp>
#include "core/Config.hpp"
namespace tnt::lua
{
TNT_API void loadSparseSet(sol::state_view lua_);
}
#endif // !TNT_EXPORT_UTILS_TO_LUA
| 19.333333
| 53
| 0.784483
|
TerensTare
|
1617900d52330f5f0a7a807eac7b535b6890d280
| 1,921
|
cpp
|
C++
|
AfxHookGoldSrc/hooks/hw/Mod_LeafPvs.cpp
|
hobokenn/advancedfx
|
4c695f94b9b1bbf1e326ebaf5434467ba087a97a
|
[
"MIT"
] | 339
|
2018-01-09T13:12:38.000Z
|
2022-03-22T21:25:59.000Z
|
AfxHookGoldSrc/hooks/hw/Mod_LeafPvs.cpp
|
hobokenn/advancedfx
|
4c695f94b9b1bbf1e326ebaf5434467ba087a97a
|
[
"MIT"
] | 474
|
2018-01-01T18:58:41.000Z
|
2022-03-27T11:09:44.000Z
|
AfxHookGoldSrc/hooks/hw/Mod_LeafPvs.cpp
|
hobokenn/advancedfx
|
4c695f94b9b1bbf1e326ebaf5434467ba087a97a
|
[
"MIT"
] | 77
|
2018-01-24T11:47:04.000Z
|
2022-03-30T12:25:59.000Z
|
#include "stdafx.h"
#include "Mod_LeafPvs.h"
#include <hl_addresses.h>
#include <hlsdk.h>
#include <Windows.h>
#include <deps/release/Detours/src/detours.h>
//
// Mod_LeafPVS WH related stuff:
//
// Hints:
// 01d51d90 R_RenderView (found by searching for "%3ifps %3i ms %4i wpoly %4i epoly\n")
//
// 01d51c60 R_RenderScene (modified) (usually has pretty static offset from R_RenderView)
//
// 01d51cb3 e8b8f0ffff call launcher!CreateInterface+0x94f981 (01d50d70)
// 01d51cb8 e883efffff call launcher!CreateInterface+0x94f851 (01d50c40)
// 01d51cbd e82ef5ffff call launcher!CreateInterface+0x94fe01 (01d511f0) R_SetupGL
// 01d51cc2 e8d9320000 call launcher!CreateInterface+0x953bb1 (01d54fa0) <-- R_MarkLeaves
//
// 01d54fa0 R_MarkLeafs (Valve modification):
//
// (see Q1 source for more help):
//
// 01edcdb4 --> r_novis.value
//
// R_MarkLeaves leads to Mod_LeafPVS
bool g_Mod_LeafPvs_NoVis = false;
typedef byte * (*Mod_LeafPVS_t)(mleaf_t *leaf, model_t *model);
Mod_LeafPVS_t g_Old_Mod_LeafPVS;
byte * New_Mod_LeafPVS (mleaf_t *leaf, model_t *model)
{
if(g_Mod_LeafPvs_NoVis)
return g_Old_Mod_LeafPVS( model->leafs, model);
return g_Old_Mod_LeafPVS( leaf, model);
}
bool Hook_Mod_LeafPvs()
{
static bool firstRun = true;
static bool firstResult = true;
if (!firstRun) return firstResult;
firstRun = false;
if (HL_ADDR_GET(Mod_LeafPVS) != NULL)
{
LONG error = NO_ERROR;
g_Old_Mod_LeafPVS = (Mod_LeafPVS_t)AFXADDR_GET(Mod_LeafPVS);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)g_Old_Mod_LeafPVS, New_Mod_LeafPVS);
error = DetourTransactionCommit();
if (NO_ERROR != error)
{
firstResult = false;
ErrorBox("Interception failed:\nHook_Mod_LeafPvs");
}
}
else
firstResult = false;
return firstResult;
}
//
| 24.0125
| 98
| 0.698594
|
hobokenn
|
161e91679977fa95a362ec56458bd2eaa142df02
| 5,063
|
hpp
|
C++
|
include/gapi/framebuffer.hpp
|
RamblingMadMan/gapi
|
29c2e70990c9097ee470159bfaad64f24bc90021
|
[
"BSD-3-Clause"
] | 1
|
2017-03-02T14:21:51.000Z
|
2017-03-02T14:21:51.000Z
|
include/gapi/framebuffer.hpp
|
RamblingMadMan/gapi
|
29c2e70990c9097ee470159bfaad64f24bc90021
|
[
"BSD-3-Clause"
] | null | null | null |
include/gapi/framebuffer.hpp
|
RamblingMadMan/gapi
|
29c2e70990c9097ee470159bfaad64f24bc90021
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef GAPI_FRAMEBUFFER_HPP
#define GAPI_FRAMEBUFFER_HPP 1
#include <cstddef>
#include <system_error>
#include "types.hpp"
#include "constants.hpp"
#include "functions.hpp"
#include "texture.hpp"
#include "utility.hpp"
namespace gapi{
//! framebuffer draw buffers category for std::system_error
class framebuffer_draw_buffers_category: public std::error_category{
public:
framebuffer_draw_buffers_category() = default;
virtual const char *name() const noexcept{ return "opengl|gapi-framebuffer-drawbuffers"; }
virtual std::string message(int condition) const{
switch(condition){
// these should make sense
case GL_INVALID_OPERATION:
return "[GL_INVALID_OPERATION] check passed buffers";
case GL_INVALID_ENUM:
return "[GL_INVALID_ENUM] check function arguments";
case GL_INVALID_VALUE:
return "[GL_INVALID_VALUE] n > GL_MAX_DRAW_BUFFERS";
default:
return "[UNKNOWN_ERROR] you'd like to know, wouldn't you?";
}
}
};
//! represents whether a framebuffer is used for reading or writing
enum class framebuffer_type: GLenum{
write = GL_DRAW_FRAMEBUFFER, read = GL_READ_FRAMEBUFFER,
readwrite = GL_FRAMEBUFFER
};
//! represents a single framebuffer object
class framebuffer_handle: public object{
public:
/**
* attach a texture to the framebuffer
*
* @param[in] attachment the attachment to attach the texture to
* @param[in] tex the texture to be attached
* @param[in] level the texture level to be attached
**/
void attach_texture(GLenum attachment, const texture_handle &tex, GLint level = 0){
functions::glNamedFramebufferTexture(handle, attachment, tex.get_handle(), level);
}
/**
* use the function for reading and/or writing
*
* @param[in] type the type of use the buffer will have
**/
void use(framebuffer_type type) noexcept{
functions::glBindFramebuffer(
static_cast<GLenum>(type),
handle
);
}
/**
* sets the draw buffer the frambuffer will use
*
* @param[in] buffer the draw buffer
**/
void draw_buffer(GLenum buffer){ functions::glNamedFramebufferDrawBuffer(handle, buffer); }
/**
* sets the draw buffers the framebuffer will use
*
* @param[in] head the first draw buffer
* @param[in] second the second draw buffer
* @param[in] tail the rest of the draw buffers
**/
template<typename ... Tail>
void draw_buffers(GLenum head, GLenum second, Tail ... tail){
std::vector<GLenum> bufs{head, second, static_cast<GLenum>(tail)...};
functions::glNamedFramebufferDrawBuffers(handle, bufs.size(), bufs.data());
GLenum err = functions::glGetError();
if(err != GL_NO_ERROR){
framebuffer_draw_buffers_category cat;
throw std::system_error{static_cast<int>(err), cat};
}
}
protected:
template<std::size_t>
friend class framebuffers;
};
//! base class for framebuffer array wrapper
class framebuffers_base{
public:
virtual std::size_t size() const noexcept = 0;
virtual const framebuffer_handle &operator [](std::size_t) const noexcept = 0;
virtual framebuffer_handle &operator [](std::size_t) noexcept = 0;
};
/**
* wrapper for an array of framebuffers
*
* @tparam N the number of framebuffers to store
**/
template<std::size_t N>
class framebuffers: public framebuffers_base{
public:
framebuffers(){
functions::glCreateFramebuffers(N, handles);
for(auto i = 0ul; i < N; i++)
usr_handles[i].handle = handles[i];
}
~framebuffers(){
functions::glDeleteFramebuffers(N, handles);
}
//! @returns the number of frambuffers stored
std::size_t size() const noexcept{ return N; }
//! implicit conversion to framebuffer_handle& when there is one element in the wrapped array
template<typename T = framebuffer_handle&>
operator std::enable_if_t<N == 1, T>() noexcept{ return usr_handles[0]; }
//! implicit conversion to const framebuffer_handle& when there is one element in the wrapped array
template<typename T = const framebuffer_handle&>
operator std::enable_if_t<N == 1, T>() const noexcept{ return usr_handles[0]; }
/**
* retrieve a reference to one of the elements of the wrapped array
*
* @param[in] idx the index into the array of the element
*
* @returns a constant reference to the indexed element
**/
const framebuffer_handle &operator [](std::size_t idx) const noexcept{ return usr_handles[idx]; }
/**
* retrieve a reference to one of the elements of the wrapped array
*
* @param[in] idx the index into the array of the element
*
* @returns a reference to the indexed element
**/
framebuffer_handle &operator [](std::size_t idx) noexcept{ return usr_handles[idx]; }
protected:
framebuffer_handle usr_handles[N];
GLuint handles[N];
};
//! convenienve type alias for when the array contains a single element
using framebuffer = framebuffers<1>;
template<>
class framebuffers<0>;
}
#endif // GAPI_FRAMEBUFFER_HPP
| 29.95858
| 102
| 0.694252
|
RamblingMadMan
|
161f39de0ffee44baf35d4c835140290c983fd27
| 2,677
|
cpp
|
C++
|
dbms/src/IO/tests/hashing_write_buffer.cpp
|
solotzg/tiflash
|
66f45c76692e941bc845c01349ea89de0f2cc210
|
[
"Apache-2.0"
] | 85
|
2022-03-25T09:03:16.000Z
|
2022-03-25T09:45:03.000Z
|
dbms/src/IO/tests/hashing_write_buffer.cpp
|
solotzg/tiflash
|
66f45c76692e941bc845c01349ea89de0f2cc210
|
[
"Apache-2.0"
] | 7
|
2022-03-25T08:59:10.000Z
|
2022-03-25T09:40:13.000Z
|
dbms/src/IO/tests/hashing_write_buffer.cpp
|
solotzg/tiflash
|
66f45c76692e941bc845c01349ea89de0f2cc210
|
[
"Apache-2.0"
] | 11
|
2022-03-25T09:15:36.000Z
|
2022-03-25T09:45:07.000Z
|
// Copyright 2022 PingCAP, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <IO/HashingWriteBuffer.h>
#include <IO/WriteBufferFromFile.h>
#include "hashing_buffer.h"
void test(size_t data_size)
{
std::vector<char> vec(data_size);
char * data = &vec[0];
for (size_t i = 0; i < data_size; ++i)
data[i] = rand() & 255;
CityHash_v1_0_2::uint128 reference = referenceHash(data, data_size);
DB::WriteBufferFromFile sink("/dev/null", 1 << 16);
{
DB::HashingWriteBuffer buf(sink);
for (size_t pos = 0; pos < data_size;)
{
size_t len = std::min(static_cast<size_t>(rand() % 10000 + 1), data_size - pos);
buf.write(data + pos, len);
buf.next();
pos += len;
}
if (buf.getHash() != reference)
FAIL("failed on data size " << data_size << " writing random chunks of up to 10000 bytes");
}
{
DB::HashingWriteBuffer buf(sink);
for (size_t pos = 0; pos < data_size;)
{
size_t len = std::min(static_cast<size_t>(rand() % 5 + 1), data_size - pos);
buf.write(data + pos, len);
buf.next();
pos += len;
}
if (buf.getHash() != reference)
FAIL("failed on data size " << data_size << " writing random chunks of up to 5 bytes");
}
{
DB::HashingWriteBuffer buf(sink);
for (size_t pos = 0; pos < data_size;)
{
size_t len = std::min(static_cast<size_t>(2048 + rand() % 3 - 1), data_size - pos);
buf.write(data + pos, len);
buf.next();
pos += len;
}
if (buf.getHash() != reference)
FAIL("failed on data size " << data_size << " writing random chunks of 2048 +-1 bytes");
}
{
DB::HashingWriteBuffer buf(sink);
buf.write(data, data_size);
if (buf.getHash() != reference)
FAIL("failed on data size " << data_size << " writing all at once");
}
}
int main()
{
test(5);
test(100);
test(2048);
test(2049);
test(100000);
test(1 << 17);
return 0;
}
| 27.316327
| 103
| 0.571909
|
solotzg
|
162292d41d7a05aeb487eba34e9f4d411a956fce
| 133
|
cpp
|
C++
|
Society2.0/Society2.0/HiveTest.cpp
|
simsim314/Society2.0
|
a95e42122e2541b7544dd641247681996f1e625a
|
[
"Unlicense"
] | 1
|
2019-07-11T13:10:43.000Z
|
2019-07-11T13:10:43.000Z
|
Society2.0/Society2.0/HiveTest.cpp
|
mdheller/Society2.0
|
a95e42122e2541b7544dd641247681996f1e625a
|
[
"Unlicense"
] | 1
|
2019-02-19T12:32:52.000Z
|
2019-03-07T20:49:50.000Z
|
Society2.0/Society2.0/HiveTest.cpp
|
mdheller/Society2.0
|
a95e42122e2541b7544dd641247681996f1e625a
|
[
"Unlicense"
] | 1
|
2020-01-10T12:37:30.000Z
|
2020-01-10T12:37:30.000Z
|
#include "HiveTest.h"
void HiveTest::EstimatesResults()
{
}
HiveTest::HiveTest()
{
}
HiveTest::~HiveTest()
{
}
| 7.823529
| 34
| 0.571429
|
simsim314
|
1623b195d9c82ef7d4c393502282699ef25d8da0
| 78
|
cpp
|
C++
|
test/testSerialization.cpp
|
martinmozi/jsonVariant
|
9c8fdf2f15b0c9b424bce4e87ffb6508979ac567
|
[
"MIT"
] | 3
|
2018-11-23T22:42:44.000Z
|
2021-02-11T11:00:22.000Z
|
test/testSerialization.cpp
|
martinmozi/jsonVariant
|
9c8fdf2f15b0c9b424bce4e87ffb6508979ac567
|
[
"MIT"
] | null | null | null |
test/testSerialization.cpp
|
martinmozi/jsonVariant
|
9c8fdf2f15b0c9b424bce4e87ffb6508979ac567
|
[
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
TEST(exampleTest, test1) {
EXPECT_EQ (0, 0);
}
| 13
| 26
| 0.628205
|
martinmozi
|
1625ae21ce33d359a7e33eab2367575d5b220dd8
| 1,864
|
cpp
|
C++
|
vkconfig/widget_setting_int_range.cpp
|
Puschel2020/VulkanTools
|
6698657af2291c8cba809069a77e8fc90ff70406
|
[
"Apache-2.0"
] | null | null | null |
vkconfig/widget_setting_int_range.cpp
|
Puschel2020/VulkanTools
|
6698657af2291c8cba809069a77e8fc90ff70406
|
[
"Apache-2.0"
] | null | null | null |
vkconfig/widget_setting_int_range.cpp
|
Puschel2020/VulkanTools
|
6698657af2291c8cba809069a77e8fc90ff70406
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2020 Valve Corporation
* Copyright (c) 2020 LunarG, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors:
* - Christophe Riccio <christophe@lunarg.com>
*/
#include "widget_setting_int_range.h"
#include <cassert>
WidgetSettingIntRange::WidgetSettingIntRange(QTreeWidgetItem* item, const SettingMetaIntRange& setting_meta,
SettingDataIntRange& setting_data)
: setting_meta(setting_meta), setting_data(setting_data) {
assert(item);
assert(&setting_meta);
assert(&setting_data);
item->setText(0, setting_meta.label.c_str());
item->setToolTip(0, setting_meta.description.c_str());
if (setting_data.min_value < setting_data.max_value) {
this->setText(format("%d-%d", setting_data.min_value, setting_data.max_value).c_str());
}
connect(this, SIGNAL(textEdited(const QString&)), this, SLOT(itemEdited(const QString&)));
}
void WidgetSettingIntRange::itemEdited(const QString& value) {
if (value.isEmpty()) {
this->setting_data.min_value = this->setting_meta.default_min_value;
this->setting_data.max_value = this->setting_meta.default_max_value;
} else {
std::sscanf(value.toStdString().c_str(), "%d-%d", &this->setting_data.min_value, &this->setting_data.max_value);
}
emit itemChanged();
}
| 38.040816
| 120
| 0.707082
|
Puschel2020
|
1626c2ff47974452a048dfe4ebf9b44b70351298
| 6,631
|
cpp
|
C++
|
src/http/routing.cpp
|
windoze/fibio-http
|
3c220a9467eda84b37aafa97364d47b28f1fc407
|
[
"BSD-2-Clause"
] | 1
|
2021-05-12T14:46:58.000Z
|
2021-05-12T14:46:58.000Z
|
src/http/routing.cpp
|
windoze/fibio-http
|
3c220a9467eda84b37aafa97364d47b28f1fc407
|
[
"BSD-2-Clause"
] | null | null | null |
src/http/routing.cpp
|
windoze/fibio-http
|
3c220a9467eda84b37aafa97364d47b28f1fc407
|
[
"BSD-2-Clause"
] | 2
|
2017-12-16T11:22:24.000Z
|
2021-05-13T01:06:01.000Z
|
//
// routing.cpp
// fibio-http
//
// Created by Chen Xu on 14/10/12.
// Copyright (c) 2014 0d0a.com. All rights reserved.
//
#include <fibio/http/server/routing.hpp>
#include "url_parser.hpp"
namespace fibio { namespace http {
match_type operator&&(const match_type &lhs, const match_type &rhs) {
struct matcher {
bool operator()(server::request &req) {
return lhs_(req) && rhs_(req);
}
match_type lhs_;
match_type rhs_;
};
return matcher{lhs, rhs};
}
match_type operator||(const match_type &lhs, const match_type &rhs) {
struct matcher {
bool operator()(server::request &req) {
return lhs_(req) || rhs_(req);
}
match_type lhs_;
match_type rhs_;
};
return matcher{lhs, rhs};
}
match_type operator!(const match_type &m) {
struct matcher {
bool operator()(server::request &req) { return !op_(req); }
match_type op_;
};
return matcher{m};
}
server::request_handler_type route(const routing_table_type &table,
server::request_handler_type default_handler)
{
struct handler {
bool operator()(server::request &req,
server::response &resp,
server::connection &conn)
{
parse_url(req.url, req.parsed_url);
for(auto &e : routing_table_) {
if(e.first(req)) {
return e.second(req, resp, conn);
}
}
return default_handler_(req, resp, conn);
}
routing_table_type routing_table_;
server::request_handler_type default_handler_;
};
return handler{table, default_handler};
}
server::request_handler_type subroute(const routing_table_type &table,
server::request_handler_type default_handler)
{
struct handler {
bool operator()(server::request &req,
server::response &resp,
server::connection &conn)
{
parse_url(req.url, req.parsed_url);
for(auto &e : routing_table_) {
if(e.first(req)) {
return e.second(req, resp, conn);
} else {
req.params.clear();
}
}
return default_handler_(req, resp, conn);
}
routing_table_type routing_table_;
server::request_handler_type default_handler_;
};
return handler{table, default_handler};
}
match_type match_any() {
struct matcher {
bool operator()(server::request &) const
{ return true; }
};
return matcher();
}
const match_type any;
match_type method_is(http_method m) {
struct matcher {
bool operator()(server::request &req) const {
return req.method==method_;
}
http_method method_;
};
return matcher{m};
}
match_type version_is(http_version v) {
struct matcher {
bool operator()(server::request &req) const {
return req.version==version_;
}
http_version version_;
};
return matcher{v};
}
match_type path_matches(const std::string &tmpl) {
struct matcher {
typedef std::list<std::string> components_type;
typedef components_type::const_iterator component_iterator;
bool operator()(server::request &req) {
std::map<std::string, std::string> m;
parse_url(req.url, req.parsed_url);
component_iterator p=pattern.cbegin();
for (auto &i : req.parsed_url.path_components) {
if (i.empty()) {
// Skip empty component
continue;
}
if (p==pattern.cend()) {
// End of pattern
return false;
} else if ((*p)[0]==':') {
// This pattern component is a parameter
m.insert({std::string(p->begin()+1, p->end()), i});
} else if ((*p)[0]=='*') {
if (p->length()==1) {
// Ignore anything remains if the wildcard doesn't have a name
return true;
}
std::string param_name(p->begin()+1, p->end());
auto mi=m.find(param_name);
if (mi==m.end()) {
// Not found
m.insert({param_name, i});
} else {
// Concat this component to existing parameter
mi->second.push_back('/');
mi->second.append(i);
}
// NOTE: Do not increment p
continue;
} else if (*p!=i) {
// Not match
return false;
}
++p;
}
// Either pattern consumed or ended with a wildcard
bool ret=(p==pattern.end() || (*p)[0]=='*');
if (ret) {
std::move(m.begin(), m.end(), std::inserter(req.params, req.params.end()));
}
return ret;
}
std::list<std::string> pattern;
common::iequal eq;
};
matcher m;
std::vector<std::string> c;
common::parse_path_components(tmpl, m.pattern);
return std::move(m);
}
match_type GET(const std::string &pattern) {
return method_is(http_method::GET) && path_matches(pattern);
}
match_type POST(const std::string &pattern) {
return method_is(http_method::POST) && path_matches(pattern);
}
match_type PUT(const std::string &pattern) {
return method_is(http_method::PUT) && path_matches(pattern);
}
}} // End of namespace fibio::http
| 33.659898
| 95
| 0.457397
|
windoze
|
162b1a7546e3f005825d9fa8678ceb0a1b8aca3e
| 826
|
cpp
|
C++
|
Console-Spinner/Spinners/SpinnerFactory.cpp
|
bargoldi/console-spinner
|
9809f55683d3fe9c517c77e2825f75ce4956014c
|
[
"MIT"
] | 5
|
2017-08-17T06:46:06.000Z
|
2020-05-29T13:27:40.000Z
|
Console-Spinner/Spinners/SpinnerFactory.cpp
|
bargoldi/console-spinner
|
9809f55683d3fe9c517c77e2825f75ce4956014c
|
[
"MIT"
] | null | null | null |
Console-Spinner/Spinners/SpinnerFactory.cpp
|
bargoldi/console-spinner
|
9809f55683d3fe9c517c77e2825f75ce4956014c
|
[
"MIT"
] | 3
|
2019-04-30T13:57:13.000Z
|
2020-02-25T19:45:08.000Z
|
#include <iostream>
#include <map>
#include <vector>
#include "SpinnerFactory.h"
#include "OneLineSpinner.h"
#include "TwoLinesSpinner.h"
#include "ThreeLinesSpinner.h"
SpinnerFactory::SpinnerFactory() {
this->spinnersMap["1 Lines Spinner"] = new OneLineSpinner();
this->spinnersMap["2 Lines Spinner"] = new TwoLinesSpinner();
this->spinnersMap["3 Lines Spinner"] = new ThreeLinesSpinner();
}
SpinnerFactory::~SpinnerFactory(){
for (auto const& key : this->spinnersMap) {
delete this->spinnersMap.at(key.first);
}
delete &(this->spinnersMap);
}
vector<string> SpinnerFactory::getAllNames() {
vector<string> keys;
for (auto const& key : this->spinnersMap) {
keys.push_back(key.first);
}
return keys;
}
Spinner SpinnerFactory::getSpinner(string spinnerType) {
return *this->spinnersMap.at(spinnerType);
}
| 22.944444
| 64
| 0.730024
|
bargoldi
|
162bf2fe14fe00258bbbac66d2e6cdbb38551fd8
| 968
|
hpp
|
C++
|
src/core/actions/change_categories_name_action.hpp
|
svendcsvendsen/judoassistant
|
453211bff86d940c2b2de6f9eea2aabcdab830fa
|
[
"MIT"
] | 3
|
2019-04-26T17:48:24.000Z
|
2021-11-08T20:21:51.000Z
|
src/core/actions/change_categories_name_action.hpp
|
svendcsvendsen/judoassistant
|
453211bff86d940c2b2de6f9eea2aabcdab830fa
|
[
"MIT"
] | 90
|
2019-04-25T17:23:10.000Z
|
2022-02-12T19:49:55.000Z
|
src/core/actions/change_categories_name_action.hpp
|
judoassistant/judoassistant
|
3b200d3e35d9aff16ba224e6071ee9d888a5a03c
|
[
"MIT"
] | null | null | null |
#pragma once
#include "core/actions/action.hpp"
class TournamentStore;
class CategoryId;
class ChangeCategoriesNameAction : public Action {
public:
ChangeCategoriesNameAction() = default;
ChangeCategoriesNameAction(std::vector<CategoryId> categoryIds, const std::string &value);
void redoImpl(TournamentStore & tournament) override;
void undoImpl(TournamentStore & tournament) override;
std::unique_ptr<Action> freshClone() const override;
std::string getDescription() const override;
template<typename Archive>
void serialize(Archive& ar, uint32_t const version) {
ar(mCategoryIds);
ar(mValue);
}
private:
std::vector<CategoryId> mCategoryIds;
std::string mValue;
// undo members
std::vector<CategoryId> mChangedCategories;
std::vector<std::string> mOldValues;
};
CEREAL_REGISTER_TYPE(ChangeCategoriesNameAction)
CEREAL_REGISTER_POLYMORPHIC_RELATION(Action, ChangeCategoriesNameAction)
| 26.888889
| 94
| 0.751033
|
svendcsvendsen
|
162def1847af69ce1a0d08ff242028b7b8901802
| 1,864
|
cpp
|
C++
|
Motor2D/j1Item.cpp
|
NontendoSL/Zelda-a-Link-to-the-Past-TRIBUTE
|
8676c7fc70b6dea54cd173b42c5006f34ab82404
|
[
"Apache-2.0"
] | 11
|
2017-02-16T18:30:43.000Z
|
2021-08-07T11:40:49.000Z
|
Motor2D/j1Item.cpp
|
NontendoSL/Zelda-a-Link-to-the-Past-TRIBUTE
|
8676c7fc70b6dea54cd173b42c5006f34ab82404
|
[
"Apache-2.0"
] | 81
|
2017-02-16T18:27:02.000Z
|
2017-06-07T20:23:40.000Z
|
Motor2D/j1Item.cpp
|
NontendoSL/Zelda-a-Link-to-the-Past-TRIBUTE
|
8676c7fc70b6dea54cd173b42c5006f34ab82404
|
[
"Apache-2.0"
] | 5
|
2017-03-01T14:49:24.000Z
|
2021-08-07T11:40:51.000Z
|
#include "j1Item.h"
#include "j1Textures.h"
#include "j1Render.h"
#include "j1App.h"
#include "j1Collision.h"
Item::Item() : SceneElement()
{
name = "items";
type = ITEM;
}
Item::~Item()
{
App->tex->UnLoad(texture);
}
bool Item::Awake(pugi::xml_node &conf, uint item_id, iPoint pos)
{
bool stop_search = false;
for (pugi::xml_node temp = conf.child("item"); stop_search == false; temp = temp.next_sibling())
{
if (temp.attribute("id").as_int(0) == item_id)
{
id = item_id;
name = temp.attribute("name").as_string("");
position.x = pos.x;
position.y = pos.y;
std::string es = temp.attribute("file").as_string("");
texture = App->tex->Load(es.c_str());
stop_search = true;
}
}
return true;
}
bool Item::Start()
{
int width = 0;
int height = 0;
//ITEM MANAGEMENT (1 -> RUPEE // 2 -> BOMB // 3-> HOOKSHOT // 4-> HEART // 5->BOW)
if (id == 1)
{
width = 8;
height = 14;
}
else if (id == 2)
{
width = 12;
height = 15;
}
else if (id == 3)
{
width = 7;
height = 16;
}
else if (id == 4)
{
width = 14;
height = 13;
}
else if (id == 5)
{
width = 7;
height = 16;
}
else if (id == 6)
{
width = 15;
height = 13;
}
else if (id == 7)
{
width = 10;
height = 16;
}
else if (id == 8)
{
width = 8;
height = 14;
}
else if (id == 9)
{
width = 8;
height = 14;
}
delay.Start();
collision = App->collision->AddCollider({ position.x, position.y, width, height }, COLLIDER_ITEM, this);
return true;
}
bool Item::Update(float dt)
{
BROFILER_CATEGORY("Update_Collision", Profiler::Color::Black);
if (delay.ReadSec() >= 0.5)
{
pickable = true;
}
return true;
}
void Item::Draw()
{
BROFILER_CATEGORY("Draw_Item", Profiler::Color::BlueViolet);
App->render->Blit(texture, position.x, position.y);
}
bool Item::CleanUp()
{
return true;
}
bool Item::Save()
{
return true;
}
| 15.533333
| 105
| 0.590129
|
NontendoSL
|
162e2a78bc0c912f4935e00e0c4fd148927bc860
| 3,147
|
cpp
|
C++
|
core/src/events/profileEvents.cpp
|
Zefiros-Software/CoreLib
|
646d544ac0877ab48aa375bd06141dfda83c37d5
|
[
"MIT"
] | 1
|
2016-09-27T08:18:10.000Z
|
2016-09-27T08:18:10.000Z
|
core/src/events/profileEvents.cpp
|
Zefiros-Software/CoreLib
|
646d544ac0877ab48aa375bd06141dfda83c37d5
|
[
"MIT"
] | null | null | null |
core/src/events/profileEvents.cpp
|
Zefiros-Software/CoreLib
|
646d544ac0877ab48aa375bd06141dfda83c37d5
|
[
"MIT"
] | null | null | null |
/**
* @cond ___LICENSE___
*
* Copyright (c) 2016-2018 Zefiros Software.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @endcond
*/
#include "events/profileEvents.h"
ProfileEvent::ProfileEvent(const std::string &name,
std::chrono::time_point< std::chrono::high_resolution_clock > time) noexcept
: mName(name),
mTime(time)
{
}
std::string ProfileEvent::GetName() const noexcept
{
return mName;
}
std::chrono::time_point< std::chrono::high_resolution_clock > ProfileEvent::GetTime() const noexcept
{
return mTime;
}
ProfileStartEvent::ProfileStartEvent(const std::string &name,
std::chrono::time_point< std::chrono::high_resolution_clock > time) noexcept
: ProfileEvent(name, time)
{
}
ProfileEndEvent::ProfileEndEvent(const std::string &name,
std::chrono::time_point< std::chrono::high_resolution_clock > time,
std::chrono::microseconds duration) noexcept
: ProfileEvent(name, time),
mDuration(duration)
{
}
std::chrono::microseconds ProfileEndEvent::GetDuration() const noexcept
{
return mDuration;
}
ProfileWaypointEvent::ProfileWaypointEvent(const std::string &name, const std::string &comment,
std::chrono::time_point< std::chrono::high_resolution_clock > time,
std::chrono::microseconds duration) noexcept
: ProfileEndEvent(name, time, duration),
mComment(comment)
{
}
std::string ProfileWaypointEvent::GetCommment() const noexcept
{
return mComment;
}
ProfileUpdateEvent::ProfileUpdateEvent(std::chrono::time_point< std::chrono::high_resolution_clock > time,
std::chrono::microseconds duration) noexcept
: mDuration(duration),
mTime(time)
{
}
std::chrono::time_point< std::chrono::high_resolution_clock > ProfileUpdateEvent::GetTime() const noexcept
{
return mTime;
}
std::chrono::microseconds ProfileUpdateEvent::GetDuration() const noexcept
{
return mDuration;
}
| 31.787879
| 113
| 0.68891
|
Zefiros-Software
|
163552b8e0247a3717f95c4239fbfdb86536fe09
| 8,011
|
cpp
|
C++
|
Actor/Characters/Enemy/GBoxEnemy_Long/GBoxEnemy_Long.cpp
|
Bornsoul/Revenger_JoyContinue
|
599716970ca87a493bf3a959b36de0b330b318f1
|
[
"MIT"
] | null | null | null |
Actor/Characters/Enemy/GBoxEnemy_Long/GBoxEnemy_Long.cpp
|
Bornsoul/Revenger_JoyContinue
|
599716970ca87a493bf3a959b36de0b330b318f1
|
[
"MIT"
] | null | null | null |
Actor/Characters/Enemy/GBoxEnemy_Long/GBoxEnemy_Long.cpp
|
Bornsoul/Revenger_JoyContinue
|
599716970ca87a493bf3a959b36de0b330b318f1
|
[
"MIT"
] | null | null | null |
// Fill out your copyright notice in the Description page of Project Settings.
#include "GBoxEnemy_Long.h"
#include "GBoxEnemyLong_Bullet.h"
#include "AIC_GBoxEnemy_Long.h"
#include "AnimInst_GBoxEnemy_Long.h"
#include "State/StateMng_GBELong.h"
#include "Libraries/Components/AnimationMng/Cpt_AnimationMng.h"
#include "Libraries/Components/ParticleMng/Cpt_ParticleMng.h"
#include "Libraries/Components/MaterialEffect/Cpt_MaterialEffect.h"
#include "Components/StaticMeshComponent.h"
#include "Kismet/KismetMathLibrary.h"
#include "Actor/Props/FootPush/Cpt_FootPushLine.h"
AGBoxEnemy_Long::AGBoxEnemy_Long()
{
PrimaryActorTick.bCanEverTick = true;
Tags.Add(FName("Enemy"));
SetGenericTeamId(FGenericTeamId(1));
bUseControllerRotationPitch = false;
bUseControllerRotationYaw = false;
bUseControllerRotationRoll = false;
GetCharacterMovement()->bOrientRotationToMovement = true;
GetCharacterMovement()->MaxWalkSpeed = 300.0f;
GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f);
m_pAnimationMng = CreateDefaultSubobject<UCpt_AnimationMng>(TEXT("AnimMngComponent"));
m_pAnimationMng->SetAnimList(TEXT("/Game/1_Project_Main/1_Blueprints/Actor/Characters/Enemy/GBoxEnemy_Long/BP_AnimList_GBoxEnemy_Long.BP_AnimList_GBoxEnemy_Long_C"));
m_pParticleMng = CreateDefaultSubobject<UCpt_ParticleMng>(TEXT("ParticleMng"));
m_pParticleMng->AddParticleInstance(TEXT("Laser"), TEXT("ParticleSystem'/Game/1_Project_Main/2_Contents/Effects/Laser/V_Laser.V_Laser'"));
m_pParticleMng->AddParticleInstance(TEXT("EyeLight"), TEXT("ParticleSystem'/Game/1_Project_Main/2_Contents/Effects/EyeLight/V_EyeLight.V_EyeLight'"));
static ConstructorHelpers::FClassFinder<UAnimInstance> Const_AnimInst(TEXT("/Game/1_Project_Main/2_Contents/Actors/Enemy/EnemyLong/Animation2/BP_Anim_LongEnemy.BP_Anim_LongEnemy_C"));
if (Const_AnimInst.Succeeded()) GetMesh()->SetAnimInstanceClass(Const_AnimInst.Class);
static ConstructorHelpers::FClassFinder<AGBoxEnemyLong_Bullet> Const_Bullet(TEXT("/Game/1_Project_Main/1_Blueprints/Actor/Characters/Enemy/GBoxEnemy_Long/BP_GBoxEnemyLong_Bullet.BP_GBoxEnemyLong_Bullet_C"));
if (Const_Bullet.Succeeded()) m_pInstance_Bullet = Const_Bullet.Class;
static ConstructorHelpers::FClassFinder<AAIC_GBoxEnemy_Long> Const_AIC(TEXT("/Game/1_Project_Main/1_Blueprints/Actor/Characters/Enemy/GBoxEnemy_Long/BP_AIC_GBoxEnemy_Long.BP_AIC_GBoxEnemy_Long_C"));
if (Const_AIC.Succeeded()) AIControllerClass = Const_AIC.Class;
m_pMaterialEffect = CreateDefaultSubobject<UCpt_MaterialEffect>(TEXT("MaterialEffect"));
m_pFootPushLine = CreateDefaultSubobject<UCpt_FootPushLine>(TEXT("FootPushLine"));
m_pFootPushLine->SetSKMesh(this);
m_pFootPushLine->AddBone(TEXT("Bip001-L-Foot"));
m_pFootPushLine->AddBone(TEXT("Bip001-R-Foot"));
}
void AGBoxEnemy_Long::PossessedBy(AController* NewController)
{
Super::PossessedBy(NewController);
}
void AGBoxEnemy_Long::PostInitializeComponents()
{
Super::PostInitializeComponents();
}
void AGBoxEnemy_Long::BeginPlay()
{
Super::BeginPlay();
GetController()->SetControlRotation(FRotator::ZeroRotator);
SetStartLoc(GetActorLocation());
m_pAnimInstance = Cast<UAnimInst_GBoxEnemy_Long>(GetMesh()->GetAnimInstance());
if (m_pAnimInstance == nullptr)
{
ULOG(TEXT("AnimInstance is Nullptr"));
return;
}
m_pAIController = Cast<AAIC_GBoxEnemy_Long>(GetController());
if (m_pAIController != nullptr)
{
m_pAIController->InitAI();
}
else
{
ULOG(TEXT("AIController is nullptr"));
return;
}
m_pStateMng = NewObject<UStateMng_GBELong>();
if (m_pStateMng != nullptr)
{
m_pStateMng->Init(this);
m_pStateMng->ChangeState(static_cast<int32>(E_State_GBELong::E_Idle));
}
else
{
ULOG(TEXT("StateMng is nullptr"));
return;
}
m_pMaterialEffect->Init(GetMesh());
m_pMaterialEffect->AddEffect(E_MaterialEffect::E_Hit2);
m_bLife = true;
}
void AGBoxEnemy_Long::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
Super::EndPlay(EndPlayReason);
if (m_pStateMng != nullptr)
m_pStateMng->Destroy();
m_pStateMng = nullptr;
}
void AGBoxEnemy_Long::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (m_pStateMng != nullptr)
m_pStateMng->Update(DeltaTime);
AnimInst_Tick();
HeadRotator_Tick(DeltaTime);
}
void AGBoxEnemy_Long::HeadRotator_Tick(float fDeltaTime)
{
if (m_bUseHeadRotator == false)
{
FRotator pControlRotation = FRotator::ZeroRotator;
FRotator pInterpRotator = UKismetMathLibrary::RInterpTo(m_rHeadRotator, pControlRotation, fDeltaTime, 3.0f);
m_rHeadRotator = pInterpRotator;
}
else
{
m_fHeadRotatorNoneTime += fDeltaTime;
if (m_fHeadRotatorNoneTime > m_fHeadRotatorNoneTime_Ago)
{
m_fHeadRotatorNoneTime = 0.0f;
m_bUseHeadRotator = false;
}
}
m_pAnimInstance->SetStat_HeadRotator(m_rHeadRotator);
}
void AGBoxEnemy_Long::HeadRotator_Use(FRotator rLookRotator, float fDeltaTime)
{
m_fHeadRotatorNoneTime = 0.0f;
m_bUseHeadRotator = true;
FRotator pControlRotation = rLookRotator;
// pControlRotation += GetActorRotation();
pControlRotation.Yaw -= GetActorRotation().Yaw;
FRotator pInterpRotator = UKismetMathLibrary::RInterpTo(m_rHeadRotator, pControlRotation, fDeltaTime, 18.0f);
m_rHeadRotator = pInterpRotator;
//m_pAnimInstance->SetStat_HeadRotator(m_rHeadRotator);
//UKismetSystemLibrary::PrintString(GetWorld(), m_rHeadRotator.ToString(), true, false, FLinearColor::Blue, 0.0f);
}
float AGBoxEnemy_Long::TakeDamage(float DamageAmount, struct FDamageEvent const & DamageEvent, class AController * EventInstigator, AActor * DamageCauser)
{
float fDamage = Super::TakeDamage(DamageAmount, DamageEvent, EventInstigator, DamageCauser);
if (GetLife() == false)
return 0.0f;
E_DamageEventClass eDamageEventClass = ULib_DamageEvent::GetDamageEventClass(DamageEvent.GetTypeID());
if (fDamage > 0.0f)
{
FDamageEvent_Hit* pBloodDamageEvent = (FDamageEvent_Hit*)&DamageEvent;
m_fCurrentHp -= fDamage;
bool bIsDead = m_fCurrentHp <= 0 ? true : false;
if (bIsDead == true)
{
SetLife(false);
UState_GBEL_Die* pState = Cast<UState_GBEL_Die>(m_pStateMng->GetStateClassRef(static_cast<int32>(E_State_GBELong::E_Die)));
if (pState != nullptr)
{
//SetRagdollPhysics(pDamageEvent->m_vHitPoint, 10.0f);
pState->SetHitDirection(pBloodDamageEvent->m_vAttackerLocaction);
m_pStateMng->ChangeState(static_cast<int32>(E_State_GBELong::E_Die));
return fDamage;
}
}
if (eDamageEventClass == E_DamageEventClass::E_Hit)
{
UState_GBEL_Hit* pState = Cast<UState_GBEL_Hit>(m_pStateMng->GetStateClassRef(static_cast<int32>(E_State_GBELong::E_Hit)));
if (pState != nullptr)
{
pState->SetHitDirection(pBloodDamageEvent->m_vAttackerLocaction);
m_pStateMng->ChangeState(static_cast<int32>(E_State_GBELong::E_Hit));
return fDamage;
}
}
}
return fDamage;
}
void AGBoxEnemy_Long::CharacterMessage(FString sMessage)
{
Super::CharacterMessage(sMessage);
if (m_pStateMng != nullptr)
m_pStateMng->StateMessage(sMessage);
}
void AGBoxEnemy_Long::Inter_Notify_Message_Implementation(FName sMessage)
{
CharacterMessage(sMessage.ToString());
}
void AGBoxEnemy_Long::AnimInst_Tick()
{
if (m_pAnimInstance == nullptr) return;
m_pAnimInstance->SetStat_Acceleration(GetVelocity().Size());
m_pAnimInstance->SetStat_MovementDirection(m_fMovementDir);
}
AGBoxEnemyLong_Bullet * AGBoxEnemy_Long::CreateBullet(FVector vShootLoc, FVector vTargetLoc)
{
if (m_pInstance_Bullet == nullptr) return nullptr;
AGBoxEnemyLong_Bullet* pBullet = GetWorld()->SpawnActor<AGBoxEnemyLong_Bullet>(m_pInstance_Bullet);
if (pBullet == nullptr) return nullptr;
pBullet->Shoot(this, vShootLoc, vTargetLoc);
return pBullet;
}
bool AGBoxEnemy_Long::Controll_Attack(class AActor* vTargetLoc)
{
UState_GBEL_Attack* pState = Cast<UState_GBEL_Attack>(m_pStateMng->GetStateClassRef(static_cast<int32>(E_State_GBELong::E_Attack)));
if (pState != nullptr)
{
pState->SetTarget(vTargetLoc);
m_pStateMng->ChangeState(static_cast<int32>(E_State_GBELong::E_Attack));
return true;
}
return false;
}
| 31.415686
| 208
| 0.785545
|
Bornsoul
|
163570725dd08077632aced90d3df16555532115
| 285
|
cpp
|
C++
|
audio_editor_core/audio_editor_core/ui/ae_ui_button_utils.cpp
|
objective-audio/audio_editor
|
649f74cdca3d7db3d618922a345ea158a0c03a1d
|
[
"MIT"
] | null | null | null |
audio_editor_core/audio_editor_core/ui/ae_ui_button_utils.cpp
|
objective-audio/audio_editor
|
649f74cdca3d7db3d618922a345ea158a0c03a1d
|
[
"MIT"
] | null | null | null |
audio_editor_core/audio_editor_core/ui/ae_ui_button_utils.cpp
|
objective-audio/audio_editor
|
649f74cdca3d7db3d618922a345ea158a0c03a1d
|
[
"MIT"
] | null | null | null |
//
// ae_ui_button_utils.cpp
//
#include "ae_ui_button_utils.h"
#include <type_traits>
using namespace yas;
using namespace yas::ae;
std::size_t ui_button_utils::to_state_idx(ui_button_state const state) {
return static_cast<std::underlying_type_t<ui_button_state>>(state);
}
| 19
| 72
| 0.768421
|
objective-audio
|
1638d5b01abe01de31f418703d6918cb50600cb3
| 6,812
|
cpp
|
C++
|
src/conversion_helpers/lexer.cpp
|
thecodedproject/json
|
989cbcd1a56fa043280e632a6ad14414de0ad429
|
[
"BSD-3-Clause"
] | null | null | null |
src/conversion_helpers/lexer.cpp
|
thecodedproject/json
|
989cbcd1a56fa043280e632a6ad14414de0ad429
|
[
"BSD-3-Clause"
] | null | null | null |
src/conversion_helpers/lexer.cpp
|
thecodedproject/json
|
989cbcd1a56fa043280e632a6ad14414de0ad429
|
[
"BSD-3-Clause"
] | null | null | null |
/* Copyright (c) 2018, Coded 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:
*
* * 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 the Coded Project 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.
*/
#include <json/conversion_helpers/lexer.hpp>
#include <functional>
#include <map>
#include <json/conversion_helpers/to_json_text.hpp>
#include <json/parse_error.hpp>
namespace CodedProject
{
namespace Json
{
namespace ConversionHelpers
{
Lexer::Lexer(std::string const& json_text)
: json_text_{json_text},
current_char_{std::begin(json_text_)}
{
}
Token Lexer::next()
{
skipWhitespace();
last_token_start_char_ = current_char_;
current_token_ = handleNextToken();
return current_token_;
}
Token Lexer::next(TokenType expected_token_type)
{
auto actual_token = next();
if(expected_token_type != actual_token.type)
{
if(!(expected_token_type == TokenType::Value &&
actual_token.type == TokenType::StringValue))
{
throw ParseError::expectedToken(
toJsonText(current_token_),
expected_token_type,
lineAndColumnOfChar(last_token_start_char_)
);
}
}
return actual_token;
}
Token Lexer::currentToken()
{
return current_token_;
}
TokenType Lexer::peekNextTokenType(int num_tokens_to_peek_forward)
{
auto current_char = current_char_;
auto last_token_start_char = last_token_start_char_;
auto current_token = current_token_;
auto next_token = Token{};
for(auto i=0; i<num_tokens_to_peek_forward; ++i)
next_token = next();
current_char_ = current_char;
last_token_start_char_ = last_token_start_char;
current_token_ = current_token;
return next_token.type;
}
void Lexer::skipWhitespace()
{
while(*current_char_ == ' ' || *current_char_ == '\n')
{
++current_char_;
}
}
Token Lexer::handleNextToken()
{
auto char_tokens_and_length = std::map<char,std::pair<Token, size_t>>{
{'[', {{TokenType::LeftArrayBrace},1}},
{']', {{TokenType::RightArrayBrace},1}},
{'{', {{TokenType::LeftDocumentBrace},1}},
{'}', {{TokenType::RightDocumentBrace},1}},
{':', {{TokenType::Colon},1}},
{',', {{TokenType::Comma},1}},
{'t', {{TokenType::Value, true},4}},
{'f', {{TokenType::Value, false},5}},
{'n', {{TokenType::Value, {}},4}}
};
if(current_char_ == std::end(json_text_))
{
return {TokenType::Eof};
}
else if(char_tokens_and_length.count(*current_char_))
{
return checkTokenStringIsValidAndAdvanceCurrentChar(
char_tokens_and_length[*current_char_]);
}
else if(*current_char_ == '"')
{
return handleStringValue();
}
else
{
return handleNumberValue();
}
}
Token Lexer::checkTokenStringIsValidAndAdvanceCurrentChar(
std::pair<Token, size_t> const& token_and_length)
{
auto token_start_char = current_char_;
advanceCurrentCharButNotBeyondEnd(token_and_length.second);
auto expected_token_string = toJsonText(token_and_length.first);
auto actual_token_string = std::string(token_start_char, current_char_);
if(expected_token_string != actual_token_string)
{
throw ParseError::invalidToken(
actual_token_string,
lineAndColumnOfChar(token_start_char)
);
}
return token_and_length.first;
}
Token Lexer::handleStringValue()
{
++current_char_;
auto string_start_char = current_char_;
advanceCurrentCharButNotBeyondEndWhile([](auto c){
return c!='"';
});
if(current_char_ == std::end(json_text_))
{
throw ParseError::unterminatedString(
{string_start_char, current_char_},
lineAndColumnOfChar(string_start_char)
);
}
auto value_string = std::string(string_start_char, current_char_);
std::advance(current_char_, 1);
return {TokenType::StringValue, value_string};
}
Token Lexer::handleNumberValue()
{
auto value_start = current_char_;
advanceCurrentCharButNotBeyondEndWhile([](auto c){
return std::string("-0123456789.").find(c)!=std::string::npos;
});
auto value_string = std::string(value_start, current_char_);
if(value_string.find(".") == std::string::npos)
{
return {TokenType::Value, std::stoi(value_string)};
}
else
{
return {TokenType::Value, std::stof(value_string)};
}
}
void Lexer::advanceCurrentCharButNotBeyondEnd(size_t amount_to_advance)
{
if(std::distance(current_char_, std::cend(json_text_)) < amount_to_advance)
{
current_char_=std::end(json_text_);
}
else
{
std::advance(current_char_, amount_to_advance);
}
}
void Lexer::advanceCurrentCharButNotBeyondEndWhile(
std::function<bool(char)> while_predicate)
{
while(while_predicate(*current_char_)
&¤t_char_!=std::end(json_text_))
{
++current_char_;
}
}
std::pair<int, int> Lexer::lineAndColumnOfChar(
std::string::const_iterator start_char) const
{
auto char_column = 1;
auto char_line = 1;
for(auto it=std::cbegin(json_text_);
it!=start_char;
++it)
{
if(*it == '\n')
{
char_column = 1;
++char_line;
}
else
{
++char_column;
}
}
return {char_line, char_column};
}
}
}
}
| 27.467742
| 81
| 0.670288
|
thecodedproject
|
163901f6e9214d86e265e0702c311b477fa6f8f5
| 1,421
|
hpp
|
C++
|
src/io.hpp
|
StanislavKlenin/httptth
|
370faea7b8c7614293402b9dfe8e6d3910068067
|
[
"BSD-2-Clause"
] | null | null | null |
src/io.hpp
|
StanislavKlenin/httptth
|
370faea7b8c7614293402b9dfe8e6d3910068067
|
[
"BSD-2-Clause"
] | null | null | null |
src/io.hpp
|
StanislavKlenin/httptth
|
370faea7b8c7614293402b9dfe8e6d3910068067
|
[
"BSD-2-Clause"
] | null | null | null |
#ifndef __IO_H__
#define __IO_H__
#include <stddef.h>
#include <functional>
#include <string>
namespace httptth
{
// some core concepts
class readable // abstract / interface
{
public:
enum class status
{
again = -1,
eof = 0,
ok = 1
};
public:
virtual ~readable() {}
using handler_type = std::function<void(const char *, size_t)>;
// read some chunk of data and pass it to the handler
virtual status read_line(handler_type &handler) = 0;
// stop reading (close)
virtual void enough() = 0;
};
class writable // abstract / interface
{
public:
virtual ~writable() {}
// consume some data, possibly storing some of it in a buffer
virtual void write(const char *data, size_t length) = 0;
// perform actual writing, commiting buffered data to the underlying system
virtual void flush() = 0;
// stop writing (close)
virtual void end() = 0;
// maybe:
// request status, "closed", "connected", "write_possible" "online"?
};
writable & operator << (writable &destination, unsigned n);
writable & operator << (writable &destination, char c);
writable & operator << (writable &destination, const char *s);
writable & operator << (writable &destination, const char *s);
writable & operator << (writable &destination, const std::string &s);
} // namespace httptth
#endif // __IO_H__
| 22.555556
| 79
| 0.638987
|
StanislavKlenin
|
163976d3c3d6240cecac379882913a3f82efefc9
| 3,704
|
cpp
|
C++
|
texmap/tmapflat_d2.cpp
|
Kreeblah/ChocolateDescent
|
ce575a8193c4fa560731203d9aea66355c41cc0d
|
[
"MIT"
] | 22
|
2019-08-19T21:09:29.000Z
|
2022-03-25T23:19:15.000Z
|
texmap/tmapflat_d2.cpp
|
Kreeblah/ChocolateDescent
|
ce575a8193c4fa560731203d9aea66355c41cc0d
|
[
"MIT"
] | 6
|
2019-11-08T22:17:03.000Z
|
2022-03-10T05:02:59.000Z
|
texmap/tmapflat_d2.cpp
|
Kreeblah/ChocolateDescent
|
ce575a8193c4fa560731203d9aea66355c41cc0d
|
[
"MIT"
] | 6
|
2019-08-24T08:03:14.000Z
|
2022-02-04T15:04:52.000Z
|
/*
THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
*/
#include <math.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
//#include "pa_enabl.h" //$$POLY_ACC
// #include "hack3df.h"
#include "fix/fix.h"
#include "platform/mono.h"
#include "2d/gr.h"
#include "2d/grdef.h"
// #include "ui.h"
#include "texmap.h"
#include "texmapl.h"
#include "scanline.h"
//#include "tmapext.h"
extern void texture_map_flat(g3ds_tmap *t);
extern void texture_map_flat_faded(g3ds_tmap *t);
#include "3d/3d.h"
#include "misc/error.h"
#if defined(POLY_ACC)
#include "poly_acc.h"
#endif
typedef struct pnt2d
{
fix x,y;
} pnt2d;
//this takes the same partms as draw_tmap, but draws a flat-shaded polygon
void draw_tmap_flat(grs_bitmap *bp,int nverts,g3s_point **vertbuf)
{
g3ds_tmap my_tmap;
int i;
fix average_light;
Assert(nverts < MAX_TMAP_VERTS);
average_light = vertbuf[0]->p3_l;
for (i=1; i<nverts; i++)
average_light += vertbuf[i]->p3_l;
if (nverts == 4)
average_light = f2i(average_light * NUM_LIGHTING_LEVELS/4);
else
average_light = f2i(average_light * NUM_LIGHTING_LEVELS/nverts);
if (average_light < 0)
average_light = 0;
else if (average_light > NUM_LIGHTING_LEVELS-1)
average_light = NUM_LIGHTING_LEVELS-1;
tmap_flat_color = gr_fade_table[average_light*256 + bp->avg_color];
my_tmap.nv = nverts;
for (i=0; i<nverts; i++)
{
my_tmap.verts[i].x2d = vertbuf[i]->p3_sx;
my_tmap.verts[i].y2d = vertbuf[i]->p3_sy;
}
#if defined(POLY_ACC)
if ( Gr_scanline_darkening_level >= GR_FADE_LEVELS )
i = 255;
else
i = 255.0 * (float)(GR_FADE_LEVELS - Gr_scanline_darkening_level)/(float)GR_FADE_LEVELS;
pa_draw_flat(&my_tmap, tmap_flat_color, i);
#else
if ( Gr_scanline_darkening_level >= GR_FADE_LEVELS )
texture_map_flat( &my_tmap );
else
{
tmap_flat_shade_value = Gr_scanline_darkening_level;
texture_map_flat_faded( &my_tmap );
}
#endif
}
// -----------------------------------------------------------------------------------------
// This is the gr_upoly-like interface to the texture mapper which uses texture-mapper compatible
// (ie, avoids cracking) edge/delta computation.
void gr_upoly_tmap(int nverts, int *vert )
{
g3ds_tmap my_tmap;
int i;
Assert(nverts < MAX_TMAP_VERTS);
my_tmap.nv = nverts;
for (i=0; i<nverts; i++)
{
my_tmap.verts[i].x2d = *vert++;
my_tmap.verts[i].y2d = *vert++;
}
tmap_flat_color = COLOR;
#ifdef _3DFX
_3dfx_DrawFlatShadedPoly( &my_tmap, _3dfx_PaletteToARGB( COLOR ) );
if ( _3dfx_skip_ddraw )
return;
#endif
#if defined(POLY_ACC)
if ( Gr_scanline_darkening_level >= GR_FADE_LEVELS )
i = 255;
else
i = 255.0 * (float)(GR_FADE_LEVELS - Gr_scanline_darkening_level)/(float)GR_FADE_LEVELS;
pa_draw_flat(&my_tmap, tmap_flat_color, i);
#else
if ( Gr_scanline_darkening_level >= GR_FADE_LEVELS )
texture_map_flat( &my_tmap );
else
{
tmap_flat_shade_value = Gr_scanline_darkening_level;
texture_map_flat_faded( &my_tmap );
}
#endif
}
| 26.269504
| 97
| 0.705454
|
Kreeblah
|
163aa1d1115c309029f8634f8ec96a72b8526b38
| 1,537
|
cpp
|
C++
|
nnforge/plain/dropout_layer_tester_plain.cpp
|
anshumang/nnForgeINST
|
1e9ea1b539cadbb03daa39f5d81025c1b17c21d8
|
[
"Apache-2.0"
] | 2
|
2015-08-19T08:02:59.000Z
|
2017-06-18T21:10:36.000Z
|
nnforge/plain/dropout_layer_tester_plain.cpp
|
anshumang/nnForgeINST
|
1e9ea1b539cadbb03daa39f5d81025c1b17c21d8
|
[
"Apache-2.0"
] | null | null | null |
nnforge/plain/dropout_layer_tester_plain.cpp
|
anshumang/nnForgeINST
|
1e9ea1b539cadbb03daa39f5d81025c1b17c21d8
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2011-2014 Maxim Milakov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dropout_layer_tester_plain.h"
#include "../dropout_layer.h"
namespace nnforge
{
namespace plain
{
dropout_layer_tester_plain::dropout_layer_tester_plain()
{
}
dropout_layer_tester_plain::~dropout_layer_tester_plain()
{
}
const boost::uuids::uuid& dropout_layer_tester_plain::get_uuid() const
{
return dropout_layer::layer_guid;
}
void dropout_layer_tester_plain::test(
additional_buffer_smart_ptr input_buffer,
additional_buffer_set& additional_buffers,
plain_running_configuration_const_smart_ptr plain_config,
const_layer_smart_ptr layer_schema,
const_layer_data_smart_ptr data,
const_layer_data_custom_smart_ptr data_custom,
const layer_configuration_specific& input_configuration_specific,
const layer_configuration_specific& output_configuration_specific,
unsigned int entry_count) const
{
}
}
}
| 29.557692
| 77
| 0.744958
|
anshumang
|
163bb8559126d8e488eee77faef1fe3b6e13880a
| 4,955
|
hpp
|
C++
|
SDK/ARKSurvivalEvolved_Buff_TekBowHelper_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 10
|
2020-02-17T19:08:46.000Z
|
2021-07-31T11:07:19.000Z
|
SDK/ARKSurvivalEvolved_Buff_TekBowHelper_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 9
|
2020-02-17T18:15:41.000Z
|
2021-06-06T19:17:34.000Z
|
SDK/ARKSurvivalEvolved_Buff_TekBowHelper_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 3
|
2020-07-22T17:42:07.000Z
|
2021-06-19T17:16:13.000Z
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Buff_TekBowHelper_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Buff_TekBowHelper.Buff_TekBowHelper_C
// 0x04BC (0x0E1C - 0x0960)
class ABuff_TekBowHelper_C : public APrimalBuff
{
public:
struct FHUDElement AmmoTypeHUDElement; // 0x0960(0x0150) (Edit, BlueprintVisible, DisableEditOnInstance)
struct FLinearColor FuelHUDBackgroundColor_Low; // 0x0AB0(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FLinearColor FuelHUDBackgroundColor_Critical; // 0x0AC0(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FLinearColor FuelHUDBackgroundColor_Default; // 0x0AD0(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FLinearColor HUDTextColor_Default; // 0x0AE0(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FLinearColor HUDTextColor_Critical; // 0x0AF0(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FLinearColor HUDTextColor_Low; // 0x0B00(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FHUDElement AmmoCostLabelHUDElement; // 0x0B10(0x0150) (Edit, BlueprintVisible, DisableEditOnInstance)
double LastAmmoSwitchTime; // 0x0C60(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FHUDElement ModeTextHUDElement; // 0x0C68(0x0150) (Edit, BlueprintVisible, DisableEditOnInstance)
struct FLinearColor HUDTextColor_Mode0; // 0x0DB8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FLinearColor HUDTextColor_Mode1; // 0x0DC8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FLinearColor HUDTextColor_Mode2; // 0x0DD8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FLinearColor HUDTextColor_Mode3; // 0x0DE8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
TArray<class UObject*> PreventedNotifySounds; // 0x0DF8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
double LastAccessorySwitchTime; // 0x0E08(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool PrevIsAccessoryActive; // 0x0E10(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData00[0x3]; // 0x0E11(0x0003) MISSED OFFSET
struct FName ConsolidatedMultiUse; // 0x0E14(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass Buff_TekBowHelper.Buff_TekBowHelper_C");
return ptr;
}
void BPClientDoMultiUse(class APlayerController** ForPC, int* ClientUseIndex);
TArray<struct FMultiUseEntry> BPGetMultiUseEntries(class APlayerController** ForPC, TArray<struct FMultiUseEntry>* MultiUseEntries);
bool BPPreventNotifySound(class USoundBase** SoundIn);
void STATIC_BPGetHUDElements(class APlayerController** ForPC, TArray<struct FHUDElement>* OutElements);
void UserConstructionScript();
void ExecuteUbergraph_Buff_TekBowHelper(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 78.650794
| 208
| 0.583451
|
2bite
|
f37ddeb5014c71beff8b86c15f12ca608717be1f
| 1,454
|
hpp
|
C++
|
utility/implicit-value.hpp
|
ExploreWilder/libutility
|
b3600d5bc77211c567674032ad1a7c65ff56cc1b
|
[
"BSD-2-Clause"
] | 2
|
2018-08-26T07:34:38.000Z
|
2019-02-25T07:27:57.000Z
|
utility/implicit-value.hpp
|
ExploreWilder/libutility
|
b3600d5bc77211c567674032ad1a7c65ff56cc1b
|
[
"BSD-2-Clause"
] | 1
|
2021-02-22T17:23:02.000Z
|
2021-04-08T15:18:57.000Z
|
utility/implicit-value.hpp
|
ExploreWilder/libutility
|
b3600d5bc77211c567674032ad1a7c65ff56cc1b
|
[
"BSD-2-Clause"
] | 3
|
2019-09-25T05:22:06.000Z
|
2022-03-29T09:18:42.000Z
|
#ifndef utility_implicit_value_hpp_included_
#define utility_implicit_value_hpp_included_
#include <boost/program_options.hpp>
/** Misbehaving implicit value workaround for Boost 1.59-1.64
*/
namespace utility {
#if (BOOST_VERSION >= 105900) && (BOOST_VERSION < 106500)
/** Special typed-value to overcome problem with implicit_value on boost
* v. [1.57, 1.64) where explicit value to option with implicit value must be
* passed in one token, i.e. via --option=value because --option value is
* treated as implicit value and positional argument.
*/
template <typename T>
struct greedy_implicit_value : public boost::program_options::typed_value<T>
{
greedy_implicit_value(T *value, const T &implicit)
: boost::program_options::typed_value<T>(value)
{
boost::program_options::typed_value<T>::implicit_value(implicit);
}
bool adjacent_tokens_only() const override { return false; }
unsigned max_tokens() const override { return 1; }
};
template <typename T>
boost::program_options::typed_value<T>*
implicit_value(T *value, const T &implicit)
{
return new greedy_implicit_value<T>(value, implicit);
}
#else
template <typename T>
boost::program_options::typed_value<T>*
implicit_value(T *value, const T &implicit)
{
auto tv(new boost::program_options::typed_value<T>(value));
tv->implicit_value(implicit);
return tv;
}
#endif
} // utility
#endif // utility_implicit_value_hpp_included_
| 26.925926
| 78
| 0.737964
|
ExploreWilder
|
f3801d9259efd31e5fabda51edce6b892e8e9293
| 2,999
|
cpp
|
C++
|
src/appleseed/renderer/utility/oiiomaketexture.cpp
|
Chargnn/appleseed
|
81ee2da5cec47f8fb85bd3c2470256de9c9ad146
|
[
"MIT"
] | null | null | null |
src/appleseed/renderer/utility/oiiomaketexture.cpp
|
Chargnn/appleseed
|
81ee2da5cec47f8fb85bd3c2470256de9c9ad146
|
[
"MIT"
] | null | null | null |
src/appleseed/renderer/utility/oiiomaketexture.cpp
|
Chargnn/appleseed
|
81ee2da5cec47f8fb85bd3c2470256de9c9ad146
|
[
"MIT"
] | null | null | null |
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2019 Jonathan Dent, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "oiiomaketexture.h"
// OIIO headers.
#include "foundation/platform/_beginoiioheaders.h"
#include "OpenImageIO/imagebufalgo.h"
#include "foundation/platform/_endoiioheaders.h"
// Standard headers.
#include <sstream>
#include <string>
#include <unordered_map>
using namespace foundation;
using namespace OIIO;
using namespace std;
namespace renderer
{
bool oiio_make_texture(
const char* in_filename,
const char* out_filename,
const char* in_colorspace,
const char* out_depth,
APIString& error_msg)
{
std::unordered_map<string, TypeDesc> out_depth_map;
out_depth_map["sint8"] = TypeDesc::INT8;
out_depth_map["uint8"] = TypeDesc::UINT8;
out_depth_map["uint16"] = TypeDesc::UINT16;
out_depth_map["sint16"] = TypeDesc::INT16;
out_depth_map["half"] = TypeDesc::HALF;
out_depth_map["float"] = TypeDesc::FLOAT;
ImageSpec spec;
if (strcmp(out_depth, "default") != 0)
spec.format = out_depth_map[out_depth];
spec.attribute("maketx:updatemode", 1);
spec.attribute("maketx:constant_color_detect", 1);
spec.attribute("maketx:monochrome detect", 1);
spec.attribute("maketx:opaque detect", 1);
spec.attribute("maketx:unpremult", 1);
spec.attribute("maketx:incolorspace", in_colorspace);
spec.attribute("maketx:outcolorspace", "linear");
spec.attribute("maketx:fixnan", "box3");
const ImageBufAlgo::MakeTextureMode mode = ImageBufAlgo::MakeTxTexture;
stringstream s;
const bool success = ImageBufAlgo::make_texture(mode, in_filename, out_filename, spec, &s);
if (!success)
error_msg = s.str().c_str();
return success;
}
}
| 33.322222
| 95
| 0.731911
|
Chargnn
|
f3828154aa8b7ac018e15623becc0e163a63fe74
| 508
|
cpp
|
C++
|
HackerRank/Challenges/time-conversion.cpp
|
Diggzinc/solutions-spoj
|
eb552311011e466039e059cce07894fea0817613
|
[
"MIT"
] | null | null | null |
HackerRank/Challenges/time-conversion.cpp
|
Diggzinc/solutions-spoj
|
eb552311011e466039e059cce07894fea0817613
|
[
"MIT"
] | null | null | null |
HackerRank/Challenges/time-conversion.cpp
|
Diggzinc/solutions-spoj
|
eb552311011e466039e059cce07894fea0817613
|
[
"MIT"
] | null | null | null |
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string str;
int v;
cin >> str;
v = (str[0]-48) * 10 + str[1] - 48;
if(str[8] == 'P') {
if(v != 12) {
v+=12;
}
}else{
if(v == 12) {
v=0;
}
}
str[0] = (v/10) + 48;
str[1] = (v%10) + 48;
for(int i=0;i<8;i++){
cout << str[i];
}
cout << endl;
return 0;
}
| 15.875
| 39
| 0.403543
|
Diggzinc
|
f386aff4291f7fdbf49864bea1f5b0fd39f6a836
| 513
|
cpp
|
C++
|
14 display full name in c++.cpp
|
pujanmahat/c-oop-programme
|
8f48bf409e27dbf9c03c8b3cb0a7a7dcdbc0ee46
|
[
"Apache-2.0"
] | null | null | null |
14 display full name in c++.cpp
|
pujanmahat/c-oop-programme
|
8f48bf409e27dbf9c03c8b3cb0a7a7dcdbc0ee46
|
[
"Apache-2.0"
] | null | null | null |
14 display full name in c++.cpp
|
pujanmahat/c-oop-programme
|
8f48bf409e27dbf9c03c8b3cb0a7a7dcdbc0ee46
|
[
"Apache-2.0"
] | null | null | null |
// wap to input your name and roll no. display your name if entered roll no is even using c++.
#include <iostream>
using namespace std;
int main()
{
string fullname;
cout<<"what is your full name "<<endl;
getline(cin,fullname);
cout<<"name :"<<fullname<<endl;
/* int roll;
string name;
cout<<"enter roll no and name "<<endl;
getline(cin,roll);
getline(cin, name);
if (roll%2 == 0)
{
cout<<"the name is "<<name<<endl;
}
else
{
cout<<"invalid "<<endl;
}
return 0; */
}
| 19.730769
| 95
| 0.608187
|
pujanmahat
|
f387ad09bad986d2b95bb1299ec63340fb647aee
| 5,309
|
hpp
|
C++
|
src/cpu/x64/jit_uni_binary_kernel.hpp
|
aletru01/oneDNN
|
ca6ca816faa92025a231f3ff1d110b73c5a460c1
|
[
"Apache-2.0"
] | null | null | null |
src/cpu/x64/jit_uni_binary_kernel.hpp
|
aletru01/oneDNN
|
ca6ca816faa92025a231f3ff1d110b73c5a460c1
|
[
"Apache-2.0"
] | null | null | null |
src/cpu/x64/jit_uni_binary_kernel.hpp
|
aletru01/oneDNN
|
ca6ca816faa92025a231f3ff1d110b73c5a460c1
|
[
"Apache-2.0"
] | null | null | null |
/*******************************************************************************
* Copyright 2021 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef CPU_X64_UNI_BINARY_KERNEL_HPP
#define CPU_X64_UNI_BINARY_KERNEL_HPP
#include <cassert>
#include "common/c_types_map.hpp"
#include "common/type_helpers.hpp"
#include "common/utils.hpp"
#include "cpu/x64/cpu_isa_traits.hpp"
#include "cpu/x64/injectors/jit_uni_postops_injector.hpp"
#include "cpu/x64/jit_generator.hpp"
#include "cpu/x64/jit_primitive_conf.hpp"
#include "cpu/x64/utils/jit_io_helper.hpp"
#include "cpu/cpu_binary_pd.hpp"
namespace dnnl {
namespace impl {
namespace cpu {
namespace x64 {
using namespace Xbyak;
struct binary_kernel_t : public jit_generator {
using op_t = binary_op_t;
using bcast_t = binary_bcast_t;
binary_kernel_t(const size_t vlen, const binary_pd_t *pd,
const jit_binary_conf_t conf, bool tail_kernel = false);
~binary_kernel_t() override = default;
void operator()(jit_binary_call_s *p) { jit_generator::operator()(p); }
size_t simd_w() const noexcept { return simd_w_; }
size_t vlen() const noexcept { return vlen_; }
protected:
size_t get_tail_size() const;
const size_t vlen_;
const size_t simd_w_;
constexpr static int vmm_start_idx_ = 1;
const binary_pd_t *pd_;
const jit_binary_conf_t conf_;
const bool is_tail_kernel_;
const size_t tail_size_;
};
template <cpu_isa_t isa>
struct jit_uni_binary_kernel_t : public binary_kernel_t {
DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_uni_binary_kernel_t)
using Vmm = typename cpu_isa_traits<isa>::Vmm;
const AddressFrame &vmmword
= (isa == sse41) ? xword : ((isa == avx2) ? yword : zword);
static constexpr bool is_avx512
= utils::one_of(isa, avx512_common, avx512_core, avx512_core_bf16);
static constexpr bool is_avx512_core
= utils::one_of(isa, avx512_core, avx512_core_bf16);
static constexpr bool is_avx512_common = isa == avx512_common;
const Reg64 ®_param_ = abi_param1;
const Reg64 ®_src0_ = r8;
const Reg64 ®_src1_ = r9;
const Reg64 ®_dst_ = r10;
const Reg64 ®_offt_src0_ = r11;
const Reg64 ®_offt_src0_count_ = r12;
const Reg64 ®_offt_src1_ = rax;
const Reg64 ®_reverse_spat_offt_ = r13;
const Reg64 ®_tmp_ = r14;
const Reg64 ®_elt_inj_table_ = r15;
const Reg64 ®_off_rhs_postops_ = rdx;
const Reg64 ®_scales_src0_ = rbx;
const Reg64 ®_scales_src1_ = rbp;
const Reg64 ®_offt_dst_ = rdx;
const Opmask &tail_opmask_ = k2;
const Opmask &cmp_mask = k3;
const Vmm vmm_tail_vmask_ = Vmm(0);
const Vmm vreg_sum_scale_ = Vmm(is_avx512 ? 17 : 9);
const Xmm xreg_sum_scale_ = Xmm(9);
const Vmm vreg_zero_ = Vmm(is_avx512 ? 18 : 10);
const Vmm vreg_one_ = Vmm(is_avx512 ? 19 : 11);
const Vmm vreg_saturation_ubound_ = Vmm(is_avx512 ? 20 : 12);
const Vmm vreg_bcast_src1_ = Vmm(
is_avx512_core || (is_avx512_common && !conf_.is_i8) ? 21 : 13);
const Xmm xreg_bcast_src1_ = Xmm(13);
const Vmm vreg_scales_src0_ = Vmm(is_avx512 ? 22 : 14);
const Vmm vreg_scales_src1_ = Vmm(is_avx512 ? 23 : 15);
const Zmm vreg_bf16_emu_1_ = Zmm(26);
const Zmm vreg_bf16_emu_2_ = Zmm(27);
const Zmm vreg_bf16_emu_3_ = Zmm(28);
const Zmm vreg_bf16_emu_4_ = Zmm(29);
static constexpr size_t unroll_regs_ = is_avx512 ? 8 : 4;
const size_t offt_src0_;
const size_t offt_src1_;
static constexpr cpu_isa_t inject_isa
= isa == avx512_core_bf16 ? avx512_core : isa;
io::jit_io_multi_dt_helper_t<Vmm> io_;
std::unique_ptr<injector::jit_uni_postops_injector_t<inject_isa>>
postops_injector_;
const Opmask &elt_inj_opmask_ = k1;
void init();
void init_post_ops_injector();
void apply_postops(int unroll, bool tail);
void load_kernel_params();
Address src0_ptr(size_t offt = 0);
Address src1_ptr(size_t offt = 0);
Address dst_ptr(size_t offt = 0);
unsigned int cmp_predicate(alg_kind_t alg);
void perform_op(
const Vmm &v0, const Vmm &v1, const Vmm &s_src0, const Vmm &s_src1);
void prepare_isa_kernel();
void compute_bcast(bool tail);
void compute_dst(int unroll, bool tail);
void forward();
void generate() override;
jit_uni_binary_kernel_t(const binary_pd_t *pd, const jit_binary_conf_t conf,
bool tail_kernel = false);
~jit_uni_binary_kernel_t() override = default;
std::map<data_type_t, io::io_saturation_conf_t>
create_saturation_vmm_map() const;
};
} // namespace x64
} // namespace cpu
} // namespace impl
} // namespace dnnl
#endif
| 34.699346
| 80
| 0.690526
|
aletru01
|
f38ace99e026d5413a56efb61d5a7e61c6535322
| 13,169
|
cc
|
C++
|
src/OpenMesh/Core/IO/reader/STLReader.cc
|
rzoller/OpenMesh
|
f84bca0b26c61eab5f9335b2191962ca8545c5f6
|
[
"BSD-3-Clause"
] | null | null | null |
src/OpenMesh/Core/IO/reader/STLReader.cc
|
rzoller/OpenMesh
|
f84bca0b26c61eab5f9335b2191962ca8545c5f6
|
[
"BSD-3-Clause"
] | null | null | null |
src/OpenMesh/Core/IO/reader/STLReader.cc
|
rzoller/OpenMesh
|
f84bca0b26c61eab5f9335b2191962ca8545c5f6
|
[
"BSD-3-Clause"
] | null | null | null |
/* ========================================================================= *
* *
* OpenMesh *
* Copyright (c) 2001-2015, RWTH-Aachen University *
* Department of Computer Graphics and Multimedia *
* All rights reserved. *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
*---------------------------------------------------------------------------*
* *
* 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. *
* *
* ========================================================================= */
/*===========================================================================*\
* *
* $Revision: 1258 $ *
* $Date: 2015-04-28 15:07:46 +0200 (Di, 28 Apr 2015) $ *
* *
\*===========================================================================*/
//== INCLUDES =================================================================
// STL
#include <map>
#include <float.h>
#include <fstream>
// OpenMesh
#include <OpenMesh/Core/System/config.h>
#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/IO/reader/STLReader.hh>
#include <OpenMesh/Core/IO/IOManager.hh>
#include <OpenMesh/Core/System/omstream.hh>
#include <OpenMesh/Core/IO/importer/BaseImporter.hh>
//=== NAMESPACES ==============================================================
namespace OpenMesh {
namespace IO {
//=== INSTANCIATE =============================================================
// register the STLReader singleton with MeshReader
_STLReader_ __STLReaderInstance;
_STLReader_& STLReader() { return __STLReaderInstance; }
//=== IMPLEMENTATION ==========================================================
_STLReader_::
_STLReader_()
: eps_(FLT_MIN)
{
IOManager().register_module(this);
}
//-----------------------------------------------------------------------------
bool
_STLReader_::
read(const std::string& _filename, BaseImporter& _bi, Options& _opt)
{
bool result = false;
STL_Type file_type = NONE;
if ( check_extension( _filename, "stla" ) )
{
file_type = STLA;
}
else if ( check_extension( _filename, "stlb" ) )
{
file_type = STLB;
}
else if ( check_extension( _filename, "stl" ) )
{
file_type = check_stl_type(_filename);
}
switch (file_type)
{
case STLA:
{
_opt -= Options::Binary;
result = read_stla(_filename, _bi, _opt);
break;
}
case STLB:
{
_opt += Options::Binary;
result = read_stlb(_filename, _bi, _opt);
break;
}
default:
{
result = false;
break;
}
}
return result;
}
bool
_STLReader_::read(std::istream& _is,
BaseImporter& _bi,
Options& _opt)
{
bool result = false;
if (_opt & Options::Binary)
result = read_stlb(_is, _bi, _opt);
else
result = read_stla(_is, _bi, _opt);
return result;
}
//-----------------------------------------------------------------------------
#ifndef DOXY_IGNORE_THIS
class CmpVec
{
public:
CmpVec(float _eps=FLT_MIN) : eps_(_eps) {}
bool operator()( const Vec3f& _v0, const Vec3f& _v1 ) const
{
if (fabs(_v0[0] - _v1[0]) <= eps_)
{
if (fabs(_v0[1] - _v1[1]) <= eps_)
{
return (_v0[2] < _v1[2] - eps_);
}
else return (_v0[1] < _v1[1] - eps_);
}
else return (_v0[0] < _v1[0] - eps_);
}
private:
float eps_;
};
#endif
//-----------------------------------------------------------------------------
void trimStdString( std::string& _string) {
// Trim Both leading and trailing spaces
size_t start = _string.find_first_not_of(" \t\r\n");
size_t end = _string.find_last_not_of(" \t\r\n");
if(( std::string::npos == start ) || ( std::string::npos == end))
_string = "";
else
_string = _string.substr( start, end-start+1 );
}
//-----------------------------------------------------------------------------
bool
_STLReader_::
read_stla(const std::string& _filename, BaseImporter& _bi, Options& _opt) const
{
std::ifstream in;
openRead(_filename, _opt, in);
if (!in)
{
omerr() << "[STLReader] : cannot not open file "
<< _filename
<< std::endl;
return false;
}
bool res = read_stla(in, _bi, _opt);
if (in)
in.close();
return res;
}
//-----------------------------------------------------------------------------
bool
_STLReader_::
read_stla(std::istream& _in, BaseImporter& _bi, Options& _opt) const
{
unsigned int i;
OpenMesh::Vec3f v;
OpenMesh::Vec3f n;
BaseImporter::VHandles vhandles;
CmpVec comp(eps_);
std::map<Vec3f, VertexHandle, CmpVec> vMap(comp);
std::map<Vec3f, VertexHandle, CmpVec>::iterator vMapIt;
std::string line;
bool facet_normal(false);
while( _in && !_in.eof() ) {
// Get one line
std::getline(_in, line);
if ( _in.bad() ){
omerr() << " Warning! Could not read stream properly!\n";
return false;
}
// Trim Both leading and trailing spaces
trimStdString(line);
// Normal found?
if (line.find("facet normal") != std::string::npos) {
std::stringstream strstream(line);
std::string garbage;
// facet
strstream >> garbage;
// normal
strstream >> garbage;
strstream >> n[0];
strstream >> n[1];
strstream >> n[2];
facet_normal = true;
}
// Detected a triangle
if ( (line.find("outer") != std::string::npos) || (line.find("OUTER") != std::string::npos ) ) {
vhandles.clear();
for (i=0; i<3; ++i) {
// Get one vertex
std::getline(_in, line);
trimStdString(line);
std::stringstream strstream(line);
std::string garbage;
strstream >> garbage;
strstream >> v[0];
strstream >> v[1];
strstream >> v[2];
// has vector been referenced before?
if ((vMapIt=vMap.find(v)) == vMap.end())
{
// No : add vertex and remember idx/vector mapping
VertexHandle handle = _bi.add_vertex(v);
vhandles.push_back(handle);
vMap[v] = handle;
}
else
// Yes : get index from map
vhandles.push_back(vMapIt->second);
}
// Add face only if it is not degenerated
if ((vhandles[0] != vhandles[1]) &&
(vhandles[0] != vhandles[2]) &&
(vhandles[1] != vhandles[2])) {
FaceHandle fh = _bi.add_face(vhandles);
// set the normal if requested
// if a normal was requested but could not be found we unset the option
if (facet_normal) {
if (fh.is_valid() && _opt.face_has_normal())
_bi.set_normal(fh, n);
} else
_opt -= Options::FaceNormal;
}
facet_normal = false;
}
}
return true;
}
//-----------------------------------------------------------------------------
bool
_STLReader_::
read_stlb(const std::string& _filename, BaseImporter& _bi, Options& _opt) const
{
std::ifstream in;
openRead(_filename, _opt, in);
if (!in)
{
omerr() << "[STLReader] : cannot not open file "
<< _filename
<< std::endl;
return false;
}
bool res = read_stlb(in, _bi, _opt);
if (in)
in.close();
return res;
}
//-----------------------------------------------------------------------------
bool
_STLReader_::
read_stlb(std::istream& _in, BaseImporter& _bi, Options& _opt) const
{
char dummy[100];
bool swapFlag;
unsigned int i, nT;
OpenMesh::Vec3f v, n;
BaseImporter::VHandles vhandles;
std::map<Vec3f, VertexHandle, CmpVec> vMap;
std::map<Vec3f, VertexHandle, CmpVec>::iterator vMapIt;
// check size of types
if ((sizeof(float) != 4) || (sizeof(int) != 4)) {
omerr() << "[STLReader] : wrong type size\n";
return false;
}
// determine endian mode
union { unsigned int i; unsigned char c[4]; } endian_test;
endian_test.i = 1;
swapFlag = (endian_test.c[3] == 1);
// read number of triangles
_in.read(dummy, 80);
nT = read_int(_in, swapFlag);
// read triangles
while (nT)
{
vhandles.clear();
// read triangle normal
n[0] = read_float(_in, swapFlag);
n[1] = read_float(_in, swapFlag);
n[2] = read_float(_in, swapFlag);
// triangle's vertices
for (i=0; i<3; ++i)
{
v[0] = read_float(_in, swapFlag);
v[1] = read_float(_in, swapFlag);
v[2] = read_float(_in, swapFlag);
// has vector been referenced before?
if ((vMapIt=vMap.find(v)) == vMap.end())
{
// No : add vertex and remember idx/vector mapping
VertexHandle handle = _bi.add_vertex(v);
vhandles.push_back(handle);
vMap[v] = handle;
}
else
// Yes : get index from map
vhandles.push_back(vMapIt->second);
}
// Add face only if it is not degenerated
if ((vhandles[0] != vhandles[1]) &&
(vhandles[0] != vhandles[2]) &&
(vhandles[1] != vhandles[2])) {
FaceHandle fh = _bi.add_face(vhandles);
if (fh.is_valid() && _opt.face_has_normal())
_bi.set_normal(fh, n);
}
_in.read(dummy, 2);
--nT;
}
return true;
}
//-----------------------------------------------------------------------------
_STLReader_::STL_Type
_STLReader_::
check_stl_type(const std::string& _filename) const
{
// assume it's binary stl, then file size is known from #triangles
// if size matches, it's really binary
// open file
FILE* in = fopen(_filename.c_str(), "rb");
if (!in) return NONE;
// determine endian mode
union { unsigned int i; unsigned char c[4]; } endian_test;
endian_test.i = 1;
bool swapFlag = (endian_test.c[3] == 1);
// read number of triangles
char dummy[100];
size_t dummy2 = fread(dummy, 1, 80, in);
size_t nT = read_int(in, swapFlag);
// compute file size from nT
size_t binary_size = 84 + nT*50;
// get actual file size
size_t file_size(0);
rewind(in);
while (!feof(in))
file_size += fread(dummy, 1, 100, in);
fclose(in);
// if sizes match -> it's STLB
return (binary_size == file_size ? STLB : STLA);
}
//=============================================================================
} // namespace IO
} // namespace OpenMesh
//=============================================================================
| 26.60404
| 101
| 0.482573
|
rzoller
|
f38c410ade3295a654d01a54804e470cdbe2fccc
| 924
|
hpp
|
C++
|
src/libs/crypto/include/keto/crypto/HashGenerator.hpp
|
burntjam/keto
|
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
|
[
"MIT"
] | 1
|
2020-03-04T10:38:00.000Z
|
2020-03-04T10:38:00.000Z
|
src/libs/crypto/include/keto/crypto/HashGenerator.hpp
|
burntjam/keto
|
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
|
[
"MIT"
] | null | null | null |
src/libs/crypto/include/keto/crypto/HashGenerator.hpp
|
burntjam/keto
|
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
|
[
"MIT"
] | 1
|
2020-03-04T10:38:01.000Z
|
2020-03-04T10:38:01.000Z
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: HashGenerator.hpp
* Author: ubuntu
*
* Created on February 6, 2018, 2:32 PM
*/
#ifndef HASHGENERATOR_HPP
#define HASHGENERATOR_HPP
#include <botan/hash.h>
#include "keto/crypto/Containers.hpp"
namespace keto {
namespace crypto {
class HashGenerator {
public:
HashGenerator();
HashGenerator(const HashGenerator& orig) = default;
virtual ~HashGenerator();
keto::crypto::SecureVector generateHash(const keto::crypto::SecureVector& bytes);
keto::crypto::SecureVector generateHash(const std::vector<uint8_t>& bytes);
keto::crypto::SecureVector generateHash(const std::string& stringValue);
private:
std::shared_ptr<Botan::HashFunction> hash256;
};
}
}
#endif /* HASHGENERATOR_HPP */
| 22
| 85
| 0.721861
|
burntjam
|
f395411512597720cceef7d6d546f47287667025
| 9,765
|
cc
|
C++
|
src/kudu/util/process_memory.cc
|
xiaokai-wang/kudu
|
83629487dac71104e1d4854c49507450f9fa8008
|
[
"Apache-2.0"
] | 1
|
2020-01-18T03:52:46.000Z
|
2020-01-18T03:52:46.000Z
|
src/kudu/util/process_memory.cc
|
xiaokai-wang/kudu
|
83629487dac71104e1d4854c49507450f9fa8008
|
[
"Apache-2.0"
] | null | null | null |
src/kudu/util/process_memory.cc
|
xiaokai-wang/kudu
|
83629487dac71104e1d4854c49507450f9fa8008
|
[
"Apache-2.0"
] | null | null | null |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <cstddef>
#include <ostream>
#include <string>
#include <gflags/gflags.h>
#include <glog/logging.h>
#ifdef TCMALLOC_ENABLED
#include <gperftools/malloc_extension.h> // IWYU pragma: keep
#endif
#include "kudu/gutil/atomicops.h"
#include "kudu/gutil/macros.h"
#include "kudu/gutil/once.h"
#include "kudu/gutil/port.h"
#include "kudu/gutil/stringprintf.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/gutil/walltime.h" // IWYU pragma: keep
#include "kudu/util/debug/trace_event.h" // IWYU pragma: keep
#include "kudu/util/env.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/locks.h"
#include "kudu/util/mem_tracker.h" // IWYU pragma: keep
#include "kudu/util/process_memory.h"
#include "kudu/util/random.h"
#include "kudu/util/status.h"
DEFINE_int64(memory_limit_hard_bytes, 0,
"Maximum amount of memory this daemon should use, in bytes. "
"A value of 0 autosizes based on the total system memory. "
"A value of -1 disables all memory limiting.");
TAG_FLAG(memory_limit_hard_bytes, stable);
DEFINE_int32(memory_pressure_percentage, 60,
"Percentage of the hard memory limit that this daemon may "
"consume before flushing of in-memory data becomes prioritized.");
TAG_FLAG(memory_pressure_percentage, advanced);
DEFINE_int32(memory_limit_soft_percentage, 80,
"Percentage of the hard memory limit that this daemon may "
"consume before memory throttling of writes begins. The greater "
"the excess, the higher the chance of throttling. In general, a "
"lower soft limit leads to smoother write latencies but "
"decreased throughput, and vice versa for a higher soft limit.");
TAG_FLAG(memory_limit_soft_percentage, advanced);
DEFINE_int32(memory_limit_warn_threshold_percentage, 98,
"Percentage of the hard memory limit that this daemon may "
"consume before WARNING level messages are periodically logged.");
TAG_FLAG(memory_limit_warn_threshold_percentage, advanced);
#ifdef TCMALLOC_ENABLED
DEFINE_int32(tcmalloc_max_free_bytes_percentage, 10,
"Maximum percentage of the RSS that tcmalloc is allowed to use for "
"reserved but unallocated memory.");
TAG_FLAG(tcmalloc_max_free_bytes_percentage, advanced);
#endif
using strings::Substitute;
namespace kudu {
namespace process_memory {
namespace {
int64_t g_hard_limit;
int64_t g_soft_limit;
int64_t g_pressure_threshold;
ThreadSafeRandom* g_rand = nullptr;
#ifdef TCMALLOC_ENABLED
// Total amount of memory released since the last GC. If this
// is greater than kGcReleaseSize, this will trigger a tcmalloc gc.
Atomic64 g_released_memory_since_gc;
// Size, in bytes, that is considered a large value for Release() (or Consume() with
// a negative value). If tcmalloc is used, this can trigger it to GC.
// A higher value will make us call into tcmalloc less often (and therefore more
// efficient). A lower value will mean our memory overhead is lower.
// TODO(todd): this is a stopgap.
const int64_t kGcReleaseSize = 128 * 1024L * 1024L;
#endif // TCMALLOC_ENABLED
} // anonymous namespace
// Flag validation
// ------------------------------------------------------------
// Validate that various flags are percentages.
static bool ValidatePercentage(const char* flagname, int value) {
if (value >= 0 && value <= 100) {
return true;
}
LOG(ERROR) << Substitute("$0 must be a percentage, value $1 is invalid",
flagname, value);
return false;
}
static bool dummy[] = {
google::RegisterFlagValidator(&FLAGS_memory_limit_soft_percentage, &ValidatePercentage),
google::RegisterFlagValidator(&FLAGS_memory_limit_warn_threshold_percentage, &ValidatePercentage)
#ifdef TCMALLOC_ENABLED
,google::RegisterFlagValidator(&FLAGS_tcmalloc_max_free_bytes_percentage, &ValidatePercentage)
#endif
};
// Wrappers around tcmalloc functionality
// ------------------------------------------------------------
#ifdef TCMALLOC_ENABLED
static int64_t GetTCMallocProperty(const char* prop) {
size_t value;
if (!MallocExtension::instance()->GetNumericProperty(prop, &value)) {
LOG(DFATAL) << "Failed to get tcmalloc property " << prop;
}
return value;
}
int64_t GetTCMallocCurrentAllocatedBytes() {
return GetTCMallocProperty("generic.current_allocated_bytes");
}
void GcTcmalloc() {
TRACE_EVENT0("process", "GcTcmalloc");
// Number of bytes in the 'NORMAL' free list (i.e reserved by tcmalloc but
// not in use).
int64_t bytes_overhead = GetTCMallocProperty("tcmalloc.pageheap_free_bytes");
// Bytes allocated by the application.
int64_t bytes_used = GetTCMallocCurrentAllocatedBytes();
int64_t max_overhead = bytes_used * FLAGS_tcmalloc_max_free_bytes_percentage / 100.0;
if (bytes_overhead > max_overhead) {
int64_t extra = bytes_overhead - max_overhead;
while (extra > 0) {
// Release 1MB at a time, so that tcmalloc releases its page heap lock
// allowing other threads to make progress. This still disrupts the current
// thread, but is better than disrupting all.
MallocExtension::instance()->ReleaseToSystem(1024 * 1024);
extra -= 1024 * 1024;
}
}
}
#endif // TCMALLOC_ENABLED
// Consumption and soft memory limit behavior
// ------------------------------------------------------------
namespace {
void DoInitLimits() {
int64_t limit = FLAGS_memory_limit_hard_bytes;
if (limit == 0) {
// If no limit is provided, we'll use 80% of system RAM.
int64_t total_ram;
CHECK_OK(Env::Default()->GetTotalRAMBytes(&total_ram));
limit = total_ram * 4;
limit /= 5;
}
g_hard_limit = limit;
g_soft_limit = FLAGS_memory_limit_soft_percentage * g_hard_limit / 100;
g_pressure_threshold = FLAGS_memory_pressure_percentage * g_hard_limit / 100;
g_rand = new ThreadSafeRandom(1);
}
void InitLimits() {
static GoogleOnceType once;
GoogleOnceInit(&once, &DoInitLimits);
}
} // anonymous namespace
int64_t CurrentConsumption() {
#ifdef TCMALLOC_ENABLED
const int64_t kReadIntervalMicros = 50000;
static Atomic64 last_read_time = 0;
static simple_spinlock read_lock;
static Atomic64 consumption = 0;
uint64_t time = GetMonoTimeMicros();
if (time > last_read_time + kReadIntervalMicros && read_lock.try_lock()) {
base::subtle::NoBarrier_Store(&consumption, GetTCMallocCurrentAllocatedBytes());
// Re-fetch the time after getting the consumption. This way, in case fetching
// consumption is extremely slow for some reason (eg due to lots of contention
// in tcmalloc) we at least ensure that we wait at least another full interval
// before fetching the information again.
time = GetMonoTimeMicros();
base::subtle::NoBarrier_Store(&last_read_time, time);
read_lock.unlock();
}
return base::subtle::NoBarrier_Load(&consumption);
#else
// Without tcmalloc, we have no reliable way of determining our own heap
// size (e.g. mallinfo doesn't work in ASAN builds). So, we'll fall back
// to just looking at the sum of our tracked memory.
return MemTracker::GetRootTracker()->consumption();
#endif
}
int64_t HardLimit() {
InitLimits();
return g_hard_limit;
}
int64_t SoftLimit() {
InitLimits();
return g_soft_limit;
}
int64_t MemoryPressureThreshold() {
InitLimits();
return g_pressure_threshold;
}
bool UnderMemoryPressure(double* current_capacity_pct) {
InitLimits();
int64_t consumption = CurrentConsumption();
if (consumption < g_pressure_threshold) {
return false;
}
if (current_capacity_pct) {
*current_capacity_pct = static_cast<double>(consumption) / g_hard_limit * 100;
}
return true;
}
bool SoftLimitExceeded(double* current_capacity_pct) {
InitLimits();
int64_t consumption = CurrentConsumption();
// Did we exceed the actual limit?
if (consumption > g_hard_limit) {
if (current_capacity_pct) {
*current_capacity_pct = static_cast<double>(consumption) / g_hard_limit * 100;
}
return true;
}
// No soft limit defined.
if (g_hard_limit == g_soft_limit) {
return false;
}
// Are we under the soft limit threshold?
if (consumption < g_soft_limit) {
return false;
}
// We're over the threshold; were we randomly chosen to be over the soft limit?
if (consumption + g_rand->Uniform64(g_hard_limit - g_soft_limit) > g_hard_limit) {
if (current_capacity_pct) {
*current_capacity_pct = static_cast<double>(consumption) / g_hard_limit * 100;
}
return true;
}
return false;
}
void MaybeGCAfterRelease(int64_t released_bytes) {
#ifdef TCMALLOC_ENABLED
int64_t now_released = base::subtle::NoBarrier_AtomicIncrement(
&g_released_memory_since_gc, released_bytes);
if (PREDICT_FALSE(now_released > kGcReleaseSize)) {
base::subtle::NoBarrier_Store(&g_released_memory_since_gc, 0);
GcTcmalloc();
}
#endif
}
} // namespace process_memory
} // namespace kudu
| 33.90625
| 99
| 0.717665
|
xiaokai-wang
|
f39935251ac443b83e277bd7f182d12a8dd88b9f
| 870
|
cpp
|
C++
|
cpp/metaproggramming/task_dsl_v2/main.cpp
|
haohua-li/code-snippet
|
c36f979333a6b7214ac7ef05d4f319bf5323bfc2
|
[
"MIT"
] | 66
|
2020-08-24T06:02:25.000Z
|
2022-03-09T21:17:09.000Z
|
cpp/metaproggramming/task_dsl_v2/main.cpp
|
haohua-li/code-snippet
|
c36f979333a6b7214ac7ef05d4f319bf5323bfc2
|
[
"MIT"
] | 1
|
2020-11-21T01:43:53.000Z
|
2020-11-21T01:43:53.000Z
|
cpp/metaproggramming/task_dsl_v2/main.cpp
|
haohua-li/code-snippet
|
c36f979333a6b7214ac7ef05d4f319bf5323bfc2
|
[
"MIT"
] | 13
|
2020-10-16T03:23:30.000Z
|
2022-03-21T02:27:50.000Z
|
/*************************************************************************
> File Name: TaskDSLv2.cpp
> Author: Netcan
> Descripton: TaskDSLv2
> Blog: https://netcan.github.io/
> Mail: 1469709759@qq.com
> Created Time: 2020-08-27 22:38
************************************************************************/
#include <cstdio>
#include <memory>
#include "TaskDsl.hpp"
int main(int argc, char** argv) {
__def_task(A, { return Job("TaskA"); });
__def_task(B, { return Job("TaskB"); });
__def_task(C, { return Job("TaskC"); });
__def_task(D, { return Job("TaskD"); });
__def_task(E, { return Job("TaskE"); });
__def_task(F, { return Job("TaskF"); });
__taskbuild(
__job(A) -> __job(B) -> __job(C),
__fork(B, E) -> __merge(F, E) -> __job(A),
__some_job(B, E) -> __job(C)
);
return 0;
}
| 30
| 74
| 0.468966
|
haohua-li
|
f39dddc66980b9cfc70cabfb3422b0c5ae1e937b
| 9,021
|
cpp
|
C++
|
Source/IO/Checkpoint.cpp
|
asalmgren/ERF
|
b3112b709dbc1febde0b224ea26d2ce10ff73d25
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
Source/IO/Checkpoint.cpp
|
asalmgren/ERF
|
b3112b709dbc1febde0b224ea26d2ce10ff73d25
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
Source/IO/Checkpoint.cpp
|
asalmgren/ERF
|
b3112b709dbc1febde0b224ea26d2ce10ff73d25
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
#include <ERF.H>
// utility to skip to next line in Header
void
ERF::GotoNextLine (std::istream& is)
{
constexpr std::streamsize bl_ignore_max { 100000 };
is.ignore(bl_ignore_max, '\n');
}
void
ERF::WriteCheckpointFile () const
{
// chk00010 write a checkpoint file with this root directory
// chk00010/Header this contains information you need to save (e.g., finest_level, t_new, etc.) and also
// the BoxArrays at each level
// chk00010/Level_0/
// chk00010/Level_1/
// etc. these subdirectories will hold the MultiFab data at each level of refinement
// checkpoint file name, e.g., chk00010
const std::string& checkpointname = amrex::Concatenate(check_file,istep[0],5);
amrex::Print() << "Writing checkpoint " << checkpointname << "\n";
const int nlevels = finest_level+1;
// ---- prebuild a hierarchy of directories
// ---- dirName is built first. if dirName exists, it is renamed. then build
// ---- dirName/subDirPrefix_0 .. dirName/subDirPrefix_nlevels-1
// ---- if callBarrier is true, call ParallelDescriptor::Barrier()
// ---- after all directories are built
// ---- ParallelDescriptor::IOProcessor() creates the directories
amrex::PreBuildDirectorHierarchy(checkpointname, "Level_", nlevels, true);
// write Header file
if (ParallelDescriptor::IOProcessor()) {
std::string HeaderFileName(checkpointname + "/Header");
VisMF::IO_Buffer io_buffer(VisMF::IO_Buffer_Size);
std::ofstream HeaderFile;
HeaderFile.rdbuf()->pubsetbuf(io_buffer.dataPtr(), io_buffer.size());
HeaderFile.open(HeaderFileName.c_str(), std::ofstream::out |
std::ofstream::trunc |
std::ofstream::binary);
if( ! HeaderFile.good()) {
amrex::FileOpenFailed(HeaderFileName);
}
HeaderFile.precision(17);
// write out title line
HeaderFile << "Checkpoint file for ERF\n";
// write out finest_level
HeaderFile << finest_level << "\n";
// write the number of components
// for each variable we store
// conservative, cell-centered vars
HeaderFile << Cons::NumVars << "\n";
// x-velocity on faces
HeaderFile << 1 << "\n";
// y-velocity on faces
HeaderFile << 1 << "\n";
// z-velocity on faces
HeaderFile << 1 << "\n";
// write out array of istep
for (int i = 0; i < istep.size(); ++i) {
HeaderFile << istep[i] << " ";
}
HeaderFile << "\n";
// write out array of dt
for (int i = 0; i < dt.size(); ++i) {
HeaderFile << dt[i] << " ";
}
HeaderFile << "\n";
// write out array of t_new
for (int i = 0; i < t_new.size(); ++i) {
HeaderFile << t_new[i] << " ";
}
HeaderFile << "\n";
// write the BoxArray at each level
for (int lev = 0; lev <= finest_level; ++lev) {
boxArray(lev).writeOn(HeaderFile);
HeaderFile << '\n';
}
}
// write the MultiFab data to, e.g., chk00010/Level_0/
// Here we make copies of the MultiFab with no ghost cells
for (int lev = 0; lev <= finest_level; ++lev) {
MultiFab cons(grids[lev],dmap[lev],Cons::NumVars,0);
MultiFab::Copy(cons,vars_new[lev][Vars::cons],0,0,NVAR,0);
VisMF::Write(cons, amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "Cell"));
MultiFab xvel(convert(grids[lev],IntVect(1,0,0)),dmap[lev],1,0);
MultiFab::Copy(xvel,vars_new[lev][Vars::xvel],0,0,1,0);
VisMF::Write(xvel, amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "XFace"));
MultiFab yvel(convert(grids[lev],IntVect(0,1,0)),dmap[lev],1,0);
MultiFab::Copy(yvel,vars_new[lev][Vars::yvel],0,0,1,0);
VisMF::Write(yvel, amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "YFace"));
MultiFab zvel(convert(grids[lev],IntVect(0,0,1)),dmap[lev],1,0);
MultiFab::Copy(zvel,vars_new[lev][Vars::zvel],0,0,1,0);
VisMF::Write(zvel, amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "ZFace"));
}
}
void
ERF::ReadCheckpointFile ()
{
amrex::Print() << "Restart from checkpoint " << restart_chkfile << "\n";
// Header
std::string File(restart_chkfile + "/Header");
VisMF::IO_Buffer io_buffer(VisMF::GetIOBufferSize());
Vector<char> fileCharPtr;
ParallelDescriptor::ReadAndBcastFile(File, fileCharPtr);
std::string fileCharPtrString(fileCharPtr.dataPtr());
std::istringstream is(fileCharPtrString, std::istringstream::in);
std::string line, word;
int chk_ncomp;
// read in title line
std::getline(is, line);
// read in finest_level
is >> finest_level;
GotoNextLine(is);
// read the number of components
// for each variable we store
// conservative, cell-centered vars
is >> chk_ncomp;
GotoNextLine(is);
AMREX_ASSERT(chk_ncomp == Cons::NumVars);
// x-velocity on faces
is >> chk_ncomp;
GotoNextLine(is);
AMREX_ASSERT(chk_ncomp == 1);
// y-velocity on faces
is >> chk_ncomp;
GotoNextLine(is);
AMREX_ASSERT(chk_ncomp == 1);
// z-velocity on faces
is >> chk_ncomp;
GotoNextLine(is);
AMREX_ASSERT(chk_ncomp == 1);
// read in array of istep
std::getline(is, line);
{
std::istringstream lis(line);
int i = 0;
while (lis >> word) {
istep[i++] = std::stoi(word);
}
}
// read in array of dt
std::getline(is, line);
{
std::istringstream lis(line);
int i = 0;
while (lis >> word) {
dt[i++] = std::stod(word);
}
}
// read in array of t_new
std::getline(is, line);
{
std::istringstream lis(line);
int i = 0;
while (lis >> word) {
t_new[i++] = std::stod(word);
}
}
int ngrow_state = ComputeGhostCells(solverChoice.spatial_order)+1;
int ngrow_vels = ComputeGhostCells(solverChoice.spatial_order);
for (int lev = 0; lev <= finest_level; ++lev) {
// read in level 'lev' BoxArray from Header
BoxArray ba;
ba.readFrom(is);
GotoNextLine(is);
// create a distribution mapping
DistributionMapping dm { ba, ParallelDescriptor::NProcs() };
// set BoxArray grids and DistributionMapping dmap in AMReX_AmrMesh.H class
SetBoxArray(lev, ba);
SetDistributionMap(lev, dm);
// build MultiFab data
int ncomp = Cons::NumVars;
auto& lev_old = vars_old[lev];
auto& lev_new = vars_new[lev];
lev_new[Vars::cons].define(grids[lev], dmap[lev], ncomp, ngrow_state);
lev_old[Vars::cons].define(grids[lev], dmap[lev], ncomp, ngrow_state);
//!don: get the ghost cells right here
lev_new[Vars::xvel].define(convert(grids[lev], IntVect(1,0,0)), dmap[lev], 1, ngrow_vels);
lev_old[Vars::xvel].define(convert(grids[lev], IntVect(1,0,0)), dmap[lev], 1, ngrow_vels);
lev_new[Vars::yvel].define(convert(grids[lev], IntVect(0,1,0)), dmap[lev], 1, ngrow_vels);
lev_old[Vars::yvel].define(convert(grids[lev], IntVect(0,1,0)), dmap[lev], 1, ngrow_vels);
lev_new[Vars::zvel].define(convert(grids[lev], IntVect(0,0,1)), dmap[lev], 1, ngrow_vels);
lev_old[Vars::zvel].define(convert(grids[lev], IntVect(0,0,1)), dmap[lev], 1, ngrow_vels);
}
// read in the MultiFab data
for (int lev = 0; lev <= finest_level; ++lev)
{
MultiFab cons(grids[lev],dmap[lev],Cons::NumVars,0);
VisMF::Read(cons, amrex::MultiFabFileFullPrefix(lev, restart_chkfile, "Level_", "Cell"));
MultiFab::Copy(vars_new[lev][Vars::cons],cons,0,0,Cons::NumVars,0);
MultiFab xvel(convert(grids[lev],IntVect(1,0,0)),dmap[lev],1,0);
VisMF::Read(xvel, amrex::MultiFabFileFullPrefix(lev, restart_chkfile, "Level_", "XFace"));
MultiFab::Copy(vars_new[lev][Vars::xvel],xvel,0,0,1,0);
MultiFab yvel(convert(grids[lev],IntVect(0,1,0)),dmap[lev],1,0);
VisMF::Read(yvel, amrex::MultiFabFileFullPrefix(lev, restart_chkfile, "Level_", "YFace"));
MultiFab::Copy(vars_new[lev][Vars::yvel],yvel,0,0,1,0);
MultiFab zvel(convert(grids[lev],IntVect(0,0,1)),dmap[lev],1,0);
VisMF::Read(zvel, amrex::MultiFabFileFullPrefix(lev, restart_chkfile, "Level_", "ZFace"));
MultiFab::Copy(vars_new[lev][Vars::zvel],zvel,0,0,1,0);
// Copy from new into old just in case
MultiFab::Copy(vars_old[lev][Vars::cons],vars_new[lev][Vars::cons],0,0,NVAR,0);
MultiFab::Copy(vars_old[lev][Vars::xvel],vars_new[lev][Vars::xvel],0,0,1,0);
MultiFab::Copy(vars_old[lev][Vars::yvel],vars_new[lev][Vars::yvel],0,0,1,0);
MultiFab::Copy(vars_old[lev][Vars::zvel],vars_new[lev][Vars::zvel],0,0,1,0);
}
}
| 34.30038
| 112
| 0.602816
|
asalmgren
|
f3a10c2af5ec838042c1d09918cfde9464690074
| 1,707
|
cpp
|
C++
|
test/Datadog.Trace.ClrProfiler.Native.Tests/version_struct_test.cpp
|
anuragvajpayee/opentelemetry-dotnet-instrumentation
|
a7f8482df233e2b3c6fc43566de174ed30864cf6
|
[
"Apache-2.0"
] | null | null | null |
test/Datadog.Trace.ClrProfiler.Native.Tests/version_struct_test.cpp
|
anuragvajpayee/opentelemetry-dotnet-instrumentation
|
a7f8482df233e2b3c6fc43566de174ed30864cf6
|
[
"Apache-2.0"
] | null | null | null |
test/Datadog.Trace.ClrProfiler.Native.Tests/version_struct_test.cpp
|
anuragvajpayee/opentelemetry-dotnet-instrumentation
|
a7f8482df233e2b3c6fc43566de174ed30864cf6
|
[
"Apache-2.0"
] | null | null | null |
#include "pch.h"
#include "../../src/OpenTelemetry.AutoInstrumentation.ClrProfiler.Native/integration.h"
using namespace trace;
TEST(VersionStructTest, Major2GreaterThanMajor1) {
const auto v1 = Version(1, 0, 0, 0);
const auto v2 = Version(2, 0, 0, 0);
ASSERT_TRUE(v2 > v1) << "Expected v2 to be greater than v1.";
}
TEST(VersionStructTest, Minor2GreaterThanMinor1) {
const auto v0_1 = Version(0, 1, 0, 0);
const auto v0_2 = Version(0, 2, 0, 0);
ASSERT_TRUE(v0_2 > v0_1) << "Expected v0_2 to be greater than v0_1.";
}
TEST(VersionStructTest, Build1GreaterThanBuild0) {
const auto v0_0_0 = Version(0, 0, 0, 0);
const auto v0_0_1 = Version(0, 0, 1, 0);
ASSERT_TRUE(v0_0_1 > v0_0_0) << "Expected v0_0_1 to be greater than v0_0_0.";
}
TEST(VersionStructTest, Major1LessThanMajor2) {
const auto v1 = Version(1, 0, 0, 0);
const auto v2 = Version(2, 0, 0, 0);
ASSERT_TRUE(v1 < v2) << "Expected v1 to be less than v2.";
}
TEST(VersionStructTest, Minor1LessThanMinor2) {
const auto v0_1 = Version(0, 1, 0, 0);
const auto v0_2 = Version(0, 2, 0, 0);
ASSERT_TRUE(v0_1 < v0_2) << "Expected v0_1 to be less than v0_2.";
}
TEST(VersionStructTest, Build0LessThanBuild1) {
const auto v0_0_0 = Version(0, 0, 0, 0);
const auto v0_0_1 = Version(0, 0, 1, 0);
ASSERT_TRUE(v0_0_0 < v0_0_1) << "Expected v0_0_0 to be less than v0_0_1.";
}
TEST(VersionStructTest, RevisionDoesNotAffectComparison) {
const auto v1_2_3_4 = Version(1, 2, 3, 4);
const auto v1_2_3_5 = Version(1, 2, 3, 5);
ASSERT_FALSE(v1_2_3_5 > v1_2_3_4)
<< "Expected v1_2_3_5 to not be greater than v1_2_3_4.";
ASSERT_FALSE(v1_2_3_4 < v1_2_3_5)
<< "Expected v1_2_3_4 to not be less than v1_2_3_5.";
}
| 33.470588
| 87
| 0.691271
|
anuragvajpayee
|
f3a8ba829efb610504d4580408ac795b5ec2220b
| 1,754
|
cpp
|
C++
|
src/Prevalence.cpp
|
gstonge/schon
|
3c02a9780ef3e1136dd61921c0cdb8124b80b01a
|
[
"MIT"
] | null | null | null |
src/Prevalence.cpp
|
gstonge/schon
|
3c02a9780ef3e1136dd61921c0cdb8124b80b01a
|
[
"MIT"
] | null | null | null |
src/Prevalence.cpp
|
gstonge/schon
|
3c02a9780ef3e1136dd61921c0cdb8124b80b01a
|
[
"MIT"
] | null | null | null |
/*
* MIT License
*
* Copyright (c) 2020 Guillaume St-Onge
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "Prevalence.hpp"
#include <iostream>
using namespace std;
namespace schon
{//start of namespace schon
//constructor
Prevalence::Prevalence(size_t network_size): name_("prevalence"),
network_size_(network_size), prevalence_vector_()
{
}
//return the prevalence
vector<double> Prevalence::get_result() const
{
return prevalence_vector_;
}
//perform a measure on the contagion process
void Prevalence::measure(
ContagionProcess const * const ptr)
{
double I = (1.*ptr->get_number_of_infected_nodes())/network_size_;
prevalence_vector_.push_back(I);
}
}//end of namespace schon
| 32.481481
| 81
| 0.754846
|
gstonge
|
f3aabb5f4185831e199f7cce1f1d1e8efec8bc21
| 9,002
|
cpp
|
C++
|
math/ntt_1e9.cpp
|
prince776/CodeBook
|
874fc7f94011ad1d25a55bcd91fecd2a11eb5a9b
|
[
"CC0-1.0"
] | 17
|
2021-01-25T12:07:17.000Z
|
2022-02-26T17:20:31.000Z
|
math/ntt_1e9.cpp
|
NavneelSinghal/CodeBook
|
ff60ace9107dd19ef8ba81e175003f567d2a9070
|
[
"CC0-1.0"
] | null | null | null |
math/ntt_1e9.cpp
|
NavneelSinghal/CodeBook
|
ff60ace9107dd19ef8ba81e175003f567d2a9070
|
[
"CC0-1.0"
] | 4
|
2021-02-28T11:13:44.000Z
|
2021-11-20T12:56:20.000Z
|
struct modinfo {
uint32_t mod, root;
};
template <modinfo const& ref>
struct modular {
static constexpr uint32_t const& mod = ref.mod;
static modular root() { return modular(ref.root); }
uint32_t v;
modular(int64_t vv = 0) { s(vv % mod + mod); }
modular& s(uint32_t vv) {
v = vv < mod ? vv : vv - mod;
return *this;
}
modular operator-() const { return modular() - *this; }
modular& operator+=(const modular& rhs) { return s(v + rhs.v); }
modular& operator-=(const modular& rhs) { return s(v + mod - rhs.v); }
modular& operator*=(const modular& rhs) {
v = uint64_t(v) * rhs.v % mod;
return *this;
}
modular& operator/=(const modular& rhs) { return *this *= rhs.inv(); }
modular operator+(const modular& rhs) const {
return modular(*this) += rhs;
}
modular operator-(const modular& rhs) const {
return modular(*this) -= rhs;
}
modular operator*(const modular& rhs) const {
return modular(*this) *= rhs;
}
modular operator/(const modular& rhs) const {
return modular(*this) /= rhs;
}
modular pow(int n) const {
modular res(1), x(*this);
while (n) {
if (n & 1) res *= x;
x *= x;
n >>= 1;
}
return res;
}
modular inv() const { return pow(mod - 2); }
friend modular operator+(int x, const modular& y) { return modular(x) + y; }
friend modular operator-(int x, const modular& y) { return modular(x) - y; }
friend modular operator*(int x, const modular& y) { return modular(x) * y; }
friend modular operator/(int x, const modular& y) { return modular(x) / y; }
friend ostream& operator<<(ostream& os, const modular& m) {
return os << m.v;
}
friend istream& operator>>(istream& is, modular& m) {
int64_t x;
is >> x;
m = modular(x);
return is;
}
bool operator<(const modular& r) const { return v < r.v; }
bool operator==(const modular& r) const { return v == r.v; }
bool operator!=(const modular& r) const { return v != r.v; }
explicit operator bool() const { return v; }
};
template <class mint>
void inplace_fmt(vector<mint>& f, bool inv) {
const int n = int(f.size());
static vector<mint> g, ig, p2;
if (int(g.size()) == 0) {
for (int i = int(0); i < int(30); i++) {
mint w = -mint::root().pow(((mint::mod - 1) >> (i + 2)) * 3);
g.push_back(w);
ig.push_back(w.inv());
p2.push_back(mint(1 << i).inv());
}
}
static constexpr uint32_t mod2 = mint::mod * 2;
if (!inv) {
int second = n;
if (second >>= 1) {
for (int i = int(0); i < int(second); i++) {
uint32_t x = f[i + second].v;
f[i + second].v = f[i].v + mint::mod - x;
f[i].v += x;
}
}
if (second >>= 1) {
mint p = 1;
for (int i = 0, k = 0; i < n; i += second * 2) {
for (int j = int(i); j < int(i + second); j++) {
uint32_t x = (f[j + second] * p).v;
f[j + second].v = f[j].v + mint::mod - x;
f[j].v += x;
}
p *= g[__builtin_ctz(++k)];
}
}
while (second) {
if (second >>= 1) {
mint p = 1;
for (int i = 0, k = 0; i < n; i += second * 2) {
for (int j = int(i); j < int(i + second); j++) {
uint32_t x = (f[j + second] * p).v;
f[j + second].v = f[j].v + mint::mod - x;
f[j].v += x;
}
p *= g[__builtin_ctz(++k)];
}
}
if (second >>= 1) {
mint p = 1;
for (int i = 0, k = 0; i < n; i += second * 2) {
for (int j = int(i); j < int(i + second); j++) {
uint32_t x = (f[j + second] * p).v;
f[j].v = (f[j].v < mod2 ? f[j].v : f[j].v - mod2);
f[j + second].v = f[j].v + mint::mod - x;
f[j].v += x;
}
p *= g[__builtin_ctz(++k)];
}
}
}
} else {
int second = 1;
if (second < n / 2) {
mint p = 1;
for (int i = 0, k = 0; i < n; i += second * 2) {
for (int j = int(i); j < int(i + second); j++) {
uint64_t x = f[j].v + mint::mod - f[j + second].v;
f[j].v += f[j + second].v;
f[j + second].v = x * p.v % mint::mod;
}
p *= ig[__builtin_ctz(++k)];
}
second <<= 1;
}
for (; second < n / 2; second <<= 1) {
mint p = 1;
for (int i = 0, k = 0; i < n; i += second * 2) {
for (int j = int(i); j < int(i + second / 2); j++) {
uint64_t x = f[j].v + mod2 - f[j + second].v;
f[j].v += f[j + second].v;
f[j].v = (f[j].v) < mod2 ? f[j].v : f[j].v - mod2;
f[j + second].v = x * p.v % mint::mod;
}
for (int j = int(i + second / 2); j < int(i + second); j++) {
uint64_t x = f[j].v + mint::mod - f[j + second].v;
f[j].v += f[j + second].v;
f[j + second].v = x * p.v % mint::mod;
}
p *= ig[__builtin_ctz(++k)];
}
}
if (second < n) {
for (int i = int(0); i < int(second); i++) {
uint32_t x = f[i + second].v;
f[i + second].v = f[i].v + mod2 - x;
f[i].v += x;
}
}
mint z = p2[__lg(n)];
for (int i = int(0); i < int(n); i++) f[i] *= z;
}
}
namespace arbitrary_convolution {
constexpr modinfo base0{1045430273, 3};
constexpr modinfo base1{1051721729, 6};
constexpr modinfo base2{1053818881, 7};
using mint0 = modular<base0>;
using mint1 = modular<base1>;
using mint2 = modular<base2>;
template <class t, class mint>
vector<t> sub(const vector<mint>& x, const vector<mint>& y,
bool same = false) {
int n = int(x.size()) + int(y.size()) - 1;
int s = 1;
while (s < n) s *= 2;
vector<t> z(s);
for (int i = int(0); i < int(int(x.size())); i++) z[i] = x[i].v;
inplace_fmt(z, false);
if (!same) {
vector<t> w(s);
for (int i = int(0); i < int(int(y.size())); i++) w[i] = y[i].v;
inplace_fmt(w, false);
for (int i = int(0); i < int(s); i++) z[i] *= w[i];
} else {
for (int i = int(0); i < int(s); i++) z[i] *= z[i];
}
inplace_fmt(z, true);
z.resize(n);
return z;
}
template <class mint>
vector<mint> multiply(const vector<mint>& x, const vector<mint>& y,
bool same = false) {
auto d0 = sub<mint0>(x, y, same);
auto d1 = sub<mint1>(x, y, same);
auto d2 = sub<mint2>(x, y, same);
int n = int(d0.size());
vector<mint> res(n);
static const mint1 r01 = mint1(mint0::mod).inv();
static const mint2 r02 = mint2(mint0::mod).inv();
static const mint2 r12 = mint2(mint1::mod).inv();
static const mint2 r02r12 = r02 * r12;
static const mint w1 = mint(mint0::mod);
static const mint w2 = w1 * mint(mint1::mod);
for (int i = int(0); i < int(n); i++) {
uint64_t first = d0[i].v;
uint64_t second =
(d1[i].v + mint1::mod - first) * r01.v % mint1::mod;
uint64_t c = ((d2[i].v + mint2::mod - first) * r02r12.v +
(mint2::mod - second) * r12.v) %
mint2::mod;
res[i].v = (first + second * w1.v + c * w2.v) % mint::mod;
}
return res;
}
template <class mint>
vector<mint> inv(const vector<mint>& a, int n) { // compute inverse mod x^n
assert(a[0] != 0);
vector<mint> r{mint(1) / a[0]};
int sz = 1;
while (sz < n) {
auto other = multiply(multiply(r, r), a);
for (int i = 0; i < (int)other.size(); ++i) {
if (i < (int)r.size())
other[i] = 2 * r[i] - other[i];
else
other[i] *= -1;
}
r = other;
sz *= 2;
while (r.size() > sz) r.pop_back();
}
while (r.size() > n) r.pop_back();
return r;
}
} // namespace arbitrary_convolution
using arbitrary_convolution::inv;
using arbitrary_convolution::multiply;
constexpr modinfo base{1000000007, 0};
using mint = modular<base>;
| 36.15261
| 80
| 0.429349
|
prince776
|
f3ad9a23dbf188dff12722736f6addf46beaa072
| 1,255
|
cpp
|
C++
|
sources/DOF.cpp
|
LauraLuvisotto/FemCourseEigenClass2021
|
2237003a1f8e99369e9602259adfd0f446a6a3e4
|
[
"MIT"
] | null | null | null |
sources/DOF.cpp
|
LauraLuvisotto/FemCourseEigenClass2021
|
2237003a1f8e99369e9602259adfd0f446a6a3e4
|
[
"MIT"
] | null | null | null |
sources/DOF.cpp
|
LauraLuvisotto/FemCourseEigenClass2021
|
2237003a1f8e99369e9602259adfd0f446a6a3e4
|
[
"MIT"
] | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
#include "DOF.h"
DOF::DOF() {
}
DOF::DOF(const DOF& copy) {
firstequation = copy.firstequation;
nshape = copy.nshape;
nstate = copy.nstate;
order = copy.order;
}
DOF& DOF::operator=(const DOF& copy) {
firstequation = copy.firstequation;
nshape = copy.nshape;
nstate = copy.nstate;
order = copy.order;
return *this;
}
DOF::~DOF() {
}
int64_t DOF::GetFirstEquation() const {
return firstequation;
}
void DOF::SetFirstEquation(int64_t first) {
firstequation = first;
}
void DOF::SetNShapeStateOrder(int NShape, int NState, int Order) {
nshape = NShape;
nstate = NState;
order = Order;
}
int DOF::GetNShape() const {
return nshape;
}
int DOF::GetNState() const {
return nstate;
}
int DOF::GetOrder() const {
return order;
}
void DOF::Print(const CompMesh& mesh, std::ostream& out) const {
int order = this->GetOrder();
int nstate = this->GetNState();
int nshape = this->GetNShape();
out << "Order: " << order << " NState: " << nstate << " NShape: " << nshape << std::endl;
}
| 19.920635
| 95
| 0.640637
|
LauraLuvisotto
|
f3b6b92f0b9704e1f35ae18a961dcb733ab2f86d
| 618
|
hh
|
C++
|
vm/vm/main/cached/GRedToUnstable-implem-decl-after.hh
|
Ahzed11/mozart2
|
4806504b103e11be723e7813be8f69e4d85875cf
|
[
"BSD-2-Clause"
] | 379
|
2015-01-02T20:27:33.000Z
|
2022-03-26T23:18:17.000Z
|
vm/vm/main/cached/GRedToUnstable-implem-decl-after.hh
|
Ahzed11/mozart2
|
4806504b103e11be723e7813be8f69e4d85875cf
|
[
"BSD-2-Clause"
] | 81
|
2015-01-08T13:18:52.000Z
|
2021-12-21T14:02:21.000Z
|
vm/vm/main/cached/GRedToUnstable-implem-decl-after.hh
|
Ahzed11/mozart2
|
4806504b103e11be723e7813be8f69e4d85875cf
|
[
"BSD-2-Clause"
] | 75
|
2015-01-06T09:08:20.000Z
|
2021-12-17T09:40:18.000Z
|
template <>
class TypeInfoOf<GRedToUnstable>: public GRedToUnstableBase {
static constexpr UUID uuid() {
return UUID();
}
public:
TypeInfoOf() : GRedToUnstableBase("GRedToUnstable", uuid(), false, false, false, sbTokenEq, 0) {}
static const TypeInfoOf<GRedToUnstable>* const instance() {
return &RawType<GRedToUnstable>::rawType;
}
static Type type() {
return Type(instance());
}
};
template <>
class TypedRichNode<GRedToUnstable>: public BaseTypedRichNode {
public:
explicit TypedRichNode(RichNode self) : BaseTypedRichNode(self) {}
inline
class mozart::UnstableNode * dest();
};
| 22.888889
| 99
| 0.713592
|
Ahzed11
|
f3b72903a2ab96d28d631299ff0d683bd1b21e8a
| 7,038
|
cpp
|
C++
|
test/storage/b_plus_tree_insert_test.cpp
|
tigert1998/bustub
|
4b98b06457b85b109eb6267d208d913ab1ae28e0
|
[
"MIT"
] | null | null | null |
test/storage/b_plus_tree_insert_test.cpp
|
tigert1998/bustub
|
4b98b06457b85b109eb6267d208d913ab1ae28e0
|
[
"MIT"
] | null | null | null |
test/storage/b_plus_tree_insert_test.cpp
|
tigert1998/bustub
|
4b98b06457b85b109eb6267d208d913ab1ae28e0
|
[
"MIT"
] | null | null | null |
/**
* b_plus_tree_insert_test.cpp
*/
#include <algorithm>
#include <cstdio>
#include <memory>
#include <random>
#include "b_plus_tree_test_util.h" // NOLINT
#include "buffer/buffer_pool_manager.h"
#include "gtest/gtest.h"
#include "storage/index/b_plus_tree.h"
namespace bustub {
TEST(BPlusTreeTests, InsertTest1) {
// create KeyComparator and index schema
Schema *key_schema = ParseCreateStatement("a bigint");
GenericComparator<8> comparator(key_schema);
DiskManager *disk_manager = new DiskManager("test.db");
BufferPoolManager *bpm = new BufferPoolManager(50, disk_manager);
// create b+ tree
BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator, 2, 3);
GenericKey<8> index_key;
RID rid;
// create transaction
Transaction *transaction = new Transaction(0);
// create and fetch header_page
page_id_t page_id;
auto header_page = bpm->NewPage(&page_id);
(void)header_page;
std::vector<int64_t> keys = {1, 2, 3, 4, 5};
for (auto key : keys) {
int64_t value = key & 0xFFFFFFFF;
rid.Set(static_cast<int32_t>(key >> 32), value);
index_key.SetFromInteger(key);
tree.Insert(index_key, rid, transaction);
}
std::vector<RID> rids;
for (auto key : keys) {
rids.clear();
index_key.SetFromInteger(key);
tree.GetValue(index_key, &rids);
EXPECT_EQ(rids.size(), 1);
int64_t value = key & 0xFFFFFFFF;
EXPECT_EQ(rids[0].GetSlotNum(), value);
}
int64_t start_key = 1;
int64_t current_key = start_key;
index_key.SetFromInteger(start_key);
for (auto iterator = tree.Begin(index_key); iterator != tree.end(); ++iterator) {
auto location = (*iterator).second;
EXPECT_EQ(location.GetPageId(), 0);
EXPECT_EQ(location.GetSlotNum(), current_key);
current_key = current_key + 1;
}
EXPECT_EQ(current_key, keys.size() + 1);
bpm->UnpinPage(HEADER_PAGE_ID, true);
delete key_schema;
delete transaction;
delete disk_manager;
delete bpm;
remove("test.db");
remove("test.log");
}
TEST(BPlusTreeTests, InsertTest2) {
// create KeyComparator and index schema
Schema *key_schema = ParseCreateStatement("a bigint");
GenericComparator<8> comparator(key_schema);
DiskManager *disk_manager = new DiskManager("test.db");
BufferPoolManager *bpm = new BufferPoolManager(50, disk_manager);
// create b+ tree
BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator);
GenericKey<8> index_key;
RID rid;
// create transaction
Transaction *transaction = new Transaction(0);
// create and fetch header_page
page_id_t page_id;
auto header_page = bpm->NewPage(&page_id);
(void)header_page;
std::vector<int64_t> keys = {5, 4, 3, 2, 1};
for (auto key : keys) {
int64_t value = key & 0xFFFFFFFF;
rid.Set(static_cast<int32_t>(key >> 32), value);
index_key.SetFromInteger(key);
tree.Insert(index_key, rid, transaction);
}
std::vector<RID> rids;
for (auto key : keys) {
rids.clear();
index_key.SetFromInteger(key);
tree.GetValue(index_key, &rids);
EXPECT_EQ(rids.size(), 1);
int64_t value = key & 0xFFFFFFFF;
EXPECT_EQ(rids[0].GetSlotNum(), value);
}
int64_t start_key = 1;
int64_t current_key = start_key;
index_key.SetFromInteger(start_key);
for (auto iterator = tree.Begin(index_key); iterator != tree.end(); ++iterator) {
auto location = (*iterator).second;
EXPECT_EQ(location.GetPageId(), 0);
EXPECT_EQ(location.GetSlotNum(), current_key);
current_key = current_key + 1;
}
EXPECT_EQ(current_key, keys.size() + 1);
start_key = 3;
current_key = start_key;
index_key.SetFromInteger(start_key);
for (auto iterator = tree.Begin(index_key); iterator != tree.end(); ++iterator) {
auto location = (*iterator).second;
EXPECT_EQ(location.GetPageId(), 0);
EXPECT_EQ(location.GetSlotNum(), current_key);
current_key = current_key + 1;
}
bpm->UnpinPage(HEADER_PAGE_ID, true);
delete key_schema;
delete transaction;
delete disk_manager;
delete bpm;
remove("test.db");
remove("test.log");
}
TEST(BPlusTreeTests, ConcurrentInsertTest) {
const int N_THREADS = 8;
const int KEYS_PER_THREAD = 1 << 14;
const int SEED = 10086;
// create KeyComparator and index schema
Schema *key_schema = ParseCreateStatement("a bigint");
GenericComparator<8> comparator(key_schema);
DiskManager *disk_manager = new DiskManager("test.db");
BufferPoolManager *bpm = new BufferPoolManager(50 * N_THREADS, disk_manager);
// create b+ tree
BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator);
// create and fetch header_page
page_id_t page_id;
auto header_page = bpm->NewPage(&page_id);
(void)header_page;
std::thread threads[N_THREADS];
for (int i = 0; i < N_THREADS; i++) {
threads[i] = std::thread(
[&](int id) {
int base = id * KEYS_PER_THREAD;
std::vector<int> keys(KEYS_PER_THREAD);
for (int i = 0; i < KEYS_PER_THREAD; i++) {
keys[i] = base + i;
}
std::shuffle(keys.begin(), keys.end(), std::default_random_engine(SEED + id));
RID rid;
GenericKey<8> index_key;
// create transaction
auto transaction = std::make_unique<Transaction>(0);
for (int i = 0; i < KEYS_PER_THREAD; i++) {
int key = keys[i];
int64_t value = key & 0xFFFFFFFF;
rid.Set(0, value);
index_key.SetFromInteger(key);
tree.Insert(index_key, rid, transaction.get());
}
},
i);
}
for (auto &thread : threads) {
thread.join();
}
GenericKey<8> index_key;
std::vector<RID> rids;
for (int key = 0; key < N_THREADS * KEYS_PER_THREAD; key++) {
rids.clear();
index_key.SetFromInteger(key);
EXPECT_TRUE(tree.GetValue(index_key, &rids));
EXPECT_EQ(rids.size(), 1);
int64_t value = key & 0xFFFFFFFF;
EXPECT_EQ(rids[0].GetSlotNum(), value);
}
for (int i = 0; i < N_THREADS; i++) {
threads[i] = std::thread(
[&](int id) {
GenericKey<8> index_key;
auto rd = std::default_random_engine(SEED + id);
int64_t start_key = std::uniform_int_distribution<>(0, N_THREADS * KEYS_PER_THREAD - 1)(rd);
int64_t current_key = start_key;
index_key.SetFromInteger(start_key);
for (auto iterator = tree.Begin(index_key); iterator != tree.end(); ++iterator) {
auto location = (*iterator).second;
EXPECT_EQ(location.GetPageId(), 0);
int64_t value = current_key & 0xFFFFFFFF;
EXPECT_EQ(location.GetSlotNum(), value);
current_key = current_key + 1;
}
EXPECT_EQ(current_key, N_THREADS * KEYS_PER_THREAD);
},
i);
}
for (auto &thread : threads) {
thread.join();
}
bpm->UnpinPage(HEADER_PAGE_ID, true);
delete key_schema;
delete disk_manager;
delete bpm;
remove("test.db");
remove("test.log");
}
} // namespace bustub
| 29.082645
| 102
| 0.654447
|
tigert1998
|
f3b736eecf664d018ba1c9c0b7930ee23618b9f2
| 760
|
cpp
|
C++
|
Paladin/Templates/Sample FileDialog/Main.cpp
|
humdingerb/Paladin
|
ef42b060656833f2887241c809690b263ddf2852
|
[
"MIT"
] | 45
|
2018-10-05T21:50:17.000Z
|
2022-01-31T11:52:59.000Z
|
Paladin/Templates/Sample FileDialog/Main.cpp
|
humdingerb/Paladin
|
ef42b060656833f2887241c809690b263ddf2852
|
[
"MIT"
] | 163
|
2018-10-01T23:52:12.000Z
|
2022-02-15T18:05:58.000Z
|
Paladin/Templates/Sample FileDialog/Main.cpp
|
humdingerb/Paladin
|
ef42b060656833f2887241c809690b263ddf2852
|
[
"MIT"
] | 9
|
2018-10-01T23:48:02.000Z
|
2022-01-23T21:28:52.000Z
|
#include <Application.h>
#include <FilePanel.h>
#include <stdio.h>
class App : public BApplication
{
public:
App(void)
: BApplication("application/x-vnd.OpenFileDemo")
{
/* Empty */
}
void MessageReceived(BMessage *msg)
{
switch (msg->what)
{
case B_REFS_RECEIVED:
/* User selected "Open" */
/* CONTINUE DOWN... */
case B_SAVE_REQUESTED:
/* User selected "Save" */
/* CONTINUE DOWN... */
case B_CANCEL:
/* User selected "Cancel" */
/* CONTINUE DOWN... */
default:
/* No matter what message what received, just quit the demo. */
be_app->Quit();
break;
}
}
};
int
main(void)
{
App *app = new App();
BFilePanel panel(B_OPEN_PANEL);
panel.Show();
app->Run();
delete app;
return 0;
}
| 14.339623
| 67
| 0.606579
|
humdingerb
|
f3bd5b20ec0446fb8015597cde1648b4658eb18d
| 1,428
|
hh
|
C++
|
unix/iumlapi/include/iumlapi/Session.hh
|
skind30/iuml-dumper
|
258bf82f3d00f502e52fdee325f06a8637bc9842
|
[
"Apache-2.0"
] | null | null | null |
unix/iumlapi/include/iumlapi/Session.hh
|
skind30/iuml-dumper
|
258bf82f3d00f502e52fdee325f06a8637bc9842
|
[
"Apache-2.0"
] | null | null | null |
unix/iumlapi/include/iumlapi/Session.hh
|
skind30/iuml-dumper
|
258bf82f3d00f502e52fdee325f06a8637bc9842
|
[
"Apache-2.0"
] | 4
|
2019-03-20T15:13:23.000Z
|
2020-09-03T20:46:04.000Z
|
//
// Filename : Session.hh
//
// UK Crown Copyright (c) 2005. All Rights Reserved
//
#ifndef iUMLAPI_Session_HH
#define iUMLAPI_Session_HH
#include "iumlapi/ORG_Database.hh"
#include <map>
namespace iUMLAPI
{
class Session
{
public:
Session ( const std::string& name, bool writeable = false );
void abortOnExit() { databaseSession.abortOnExit(); }
void commitOnExit() { databaseSession.commitOnExit(); }
const ORG::Database& getDatabase() const;
private:
class DatabaseSession
{
public:
DatabaseSession();
~DatabaseSession();
Entity logon(const std::string& name, bool writeable);
void commitOnExit() { if ( status == UpdateAbort ) status = UpdateCommit; }
void abortOnExit() { if ( status == UpdateCommit ) status = UpdateAbort; }
private:
enum Status { LoggedOff, ReadOnly, UpdateCommit, UpdateAbort };
Status status;
};
private:
// Don't allow copying of sessions, or it will cause havoc
// with the database sessions
Session(const Session& session);
Session& operator= (const Session& session);
private:
// Database Session must be first member to ensure it is
// initialised first and destructed last
DatabaseSession databaseSession;
ORG::Database database;
bool lockAcquired;
};
};
#endif
| 23.032258
| 85
| 0.630952
|
skind30
|
f3bd691beabd9f220d18f3e23ef7a42eaebcdfd6
| 3,551
|
cpp
|
C++
|
src/network/ssl_cert.cpp
|
skunkforce/kitchensink
|
7e453ac65182691af32aa3e8b19f72ceac0e2329
|
[
"BSD-2-Clause"
] | null | null | null |
src/network/ssl_cert.cpp
|
skunkforce/kitchensink
|
7e453ac65182691af32aa3e8b19f72ceac0e2329
|
[
"BSD-2-Clause"
] | null | null | null |
src/network/ssl_cert.cpp
|
skunkforce/kitchensink
|
7e453ac65182691af32aa3e8b19f72ceac0e2329
|
[
"BSD-2-Clause"
] | null | null | null |
/***********************************************************************
*
* Copyright (c) 2012-2022 Barbara Geller
* Copyright (c) 2012-2022 Ansel Sermersheim
* Copyright (c) 2015 The Qt Company Ltd.
*
* This file is part of KitchenSink.
*
* KitchenSink is free software, released under the BSD 2-Clause license.
* For license details refer to LICENSE provided with this project.
*
* CopperSpice 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.
*
* https://opensource.org/licenses/BSD-2-Clause
*
***********************************************************************/
#ifdef QT_SSL
#include "ssl_cert.h"
#include <QComboBox>
#include <QStringList>
Ssl_Cert::Ssl_Cert(QWidget *parent)
: QDialog(parent), ui(new Ui::Ssl_Cert)
{
ui->setupUi(this);
connect(ui->closePB, &QPushButton::clicked, this, &Ssl_Cert::accept);
// cs_mp_cast is required since this signal is overloaded
connect(ui->certificationPathView, cs_mp_cast<int>(&QComboBox::currentIndexChanged),
this, &Ssl_Cert::updateCertificateInfo);
}
Ssl_Cert::~Ssl_Cert()
{
}
void Ssl_Cert::setCertificateChain(const QList<QSslCertificate> &chain)
{
this->chain = chain;
ui->certificationPathView->clear();
for (int i = 0; i < chain.size(); ++i) {
const QSslCertificate &cert = chain.at(i);
ui->certificationPathView->addItem(tr("%1%2 (%3)").formatArg(! i ? QString() : tr("Issued by: "))
.formatArg(cert.subjectInfo(QSslCertificate::Organization).join(" "))
.formatArg(cert.subjectInfo(QSslCertificate::CommonName).join(" ")));
}
ui->certificationPathView->setCurrentIndex(0);
}
void Ssl_Cert::updateCertificateInfo(int index)
{
ui->certificateInfoView->clear();
if (index >= 0 && index < chain.size()) {
const QSslCertificate &cert = chain.at(index);
QStringList lines;
lines << tr("Organization: %1").formatArg(cert.subjectInfo(QSslCertificate::Organization).join(" "))
<< tr("Subunit: %1").formatArg(cert.subjectInfo(QSslCertificate::OrganizationalUnitName).join(" "))
<< tr("Country: %1").formatArg(cert.subjectInfo(QSslCertificate::CountryName).join(" "))
<< tr("Locality: %1").formatArg(cert.subjectInfo(QSslCertificate::LocalityName).join(" "))
<< tr("State/Province: %1").formatArg(cert.subjectInfo(QSslCertificate::StateOrProvinceName).join(" "))
<< tr("Common Name: %1").formatArg(cert.subjectInfo(QSslCertificate::CommonName).join(" "))
<< QString()
<< tr("Issuer Organization: %1").formatArg(cert.issuerInfo(QSslCertificate::Organization).join(" "))
<< tr("Issuer Unit Name: %1").formatArg(cert.issuerInfo(QSslCertificate::OrganizationalUnitName).join(" "))
<< tr("Issuer Country: %1").formatArg(cert.issuerInfo(QSslCertificate::CountryName).join(" "))
<< tr("Issuer Locality: %1").formatArg(cert.issuerInfo(QSslCertificate::LocalityName).join(" "))
<< tr("Issuer State/Province: %1").formatArg(cert.issuerInfo(QSslCertificate::StateOrProvinceName).join(" "))
<< tr("Issuer Common Name: %1").formatArg(cert.issuerInfo(QSslCertificate::CommonName).join(" "));
for (QString line : lines) {
ui->certificateInfoView->addItem(line);
}
} else {
ui->certificateInfoView->clear();
}
}
#endif
| 38.182796
| 123
| 0.630245
|
skunkforce
|
f3bf6bc7129942759c07e6d1ac18277ca7e95c9c
| 2,851
|
hpp
|
C++
|
include/musicpp/generators/mix.hpp
|
lebel-louisjacob/musicpp
|
4cfd40afa529025e303fe20bff0ed44fec57acc7
|
[
"MIT"
] | 2
|
2022-02-14T13:02:47.000Z
|
2022-02-14T13:02:49.000Z
|
include/musicpp/generators/mix.hpp
|
lebel-louisjacob/musicpp
|
4cfd40afa529025e303fe20bff0ed44fec57acc7
|
[
"MIT"
] | 1
|
2022-02-02T22:24:16.000Z
|
2022-02-02T22:24:16.000Z
|
include/musicpp/generators/mix.hpp
|
lebel-louisjacob/musicpp
|
4cfd40afa529025e303fe20bff0ed44fec57acc7
|
[
"MIT"
] | null | null | null |
#ifndef MPP_GENERATORS_MIX_HPP
#define MPP_GENERATORS_MIX_HPP
#include <musicpp/generator.hpp>
#include <musicpp/mixer.hpp>
#include <musicpp/utils/tuple_foreach.hpp>
#include <vector>
#include <tuple>
namespace mpp
{
template <typename... Inputs>
struct Mix : public std::tuple<Inputs...>
{
constexpr Mix(Inputs const&... inputs):
std::tuple<Inputs...> { inputs... }
{}
};
template <typename Output, typename... Inputs>
struct Generator<Output, Mix<Inputs...>>
{
constexpr Output generate_at(TimePoint const& time, Config const& config) const&
{
if constexpr (sizeof...(Inputs) == 1)
{
return generator<Output>(std::get<0>(inputs)).generate_at(time, config);
}
else
{
std::vector<Output> results_to_mix;
for_each(static_cast<std::tuple<Inputs...>&>(inputs), [&results_to_mix, &time, &config](auto& input)
{
Output const& result { generator<Output>(input).generate_at(time, config) };
results_to_mix.emplace_back(result);
});
return mix<Output>(results_to_mix);
}
}
constexpr uint64_t size() const&
{
if constexpr (sizeof...(Inputs) == 1)
{
return generator<Output>(std::get<0>(inputs)).size();
}
else
{
uint64_t max_size_with_offset { 0 };
for_each(static_cast<std::tuple<Inputs...>&>(inputs), [&max_size_with_offset](auto& input)
{
auto const& current_generator { generator<Output>(input) };
uint64_t const& current_size { current_generator.offset() + current_generator.size() };
max_size_with_offset = std::max(max_size_with_offset, current_size);
});
return max_size_with_offset - offset();
}
}
constexpr uint64_t offset() const&
{
if constexpr (sizeof...(Inputs) == 1)
{
return generator<Output>(std::get<0>(inputs)).offset();
}
else
{
uint64_t min_offset { std::numeric_limits<uint64_t>::max() };
for_each(static_cast<std::tuple<Inputs...>&>(inputs), [&min_offset](auto& input)
{
auto const& current_generator { generator<Output>(input) };
uint64_t const& current_offset { current_generator.offset() };
min_offset = std::min<uint64_t>(min_offset, current_offset);
});
return min_offset;
}
}
Mix<Inputs...>& inputs;
};
}
#endif
| 31.32967
| 116
| 0.52087
|
lebel-louisjacob
|
f3bfa71ad4157d98f53bb0def2a46de9ee3abe48
| 1,276
|
cc
|
C++
|
lib/tcp_helpers/tcp_segment.cc
|
MUCZ/Starfish
|
4960b7f6001264731c1aea0b8171d187f5ec8ed8
|
[
"Apache-2.0"
] | 8
|
2021-02-22T01:10:06.000Z
|
2022-02-28T13:30:26.000Z
|
lib/tcp_helpers/tcp_segment.cc
|
MUCZ/Starfish
|
4960b7f6001264731c1aea0b8171d187f5ec8ed8
|
[
"Apache-2.0"
] | null | null | null |
lib/tcp_helpers/tcp_segment.cc
|
MUCZ/Starfish
|
4960b7f6001264731c1aea0b8171d187f5ec8ed8
|
[
"Apache-2.0"
] | 7
|
2021-02-22T01:10:16.000Z
|
2022-02-18T11:49:15.000Z
|
#include "tcp_segment.hh"
#include "parser.hh"
#include "util.hh"
#include <variant>
using namespace std;
//! \param[in] buffer string/Buffer to be parsed
//! \param[in] datagram_layer_checksum pseudo-checksum from the lower-layer protocol
ParseResult TCPSegment::parse(const Buffer buffer, const uint32_t datagram_layer_checksum) {
InternetChecksum check(datagram_layer_checksum);
check.add(buffer);
if (check.value()) {
return ParseResult::BadChecksum;
}
NetParser p{buffer};
_header.parse(p);
_payload = p.buffer();
return p.get_error();
}
size_t TCPSegment::length_in_sequence_space() const {
return payload().str().size() + (header().syn ? 1 : 0) + (header().fin ? 1 : 0);
}
//! \param[in] datagram_layer_checksum pseudo-checksum from the lower-layer protocol
BufferList TCPSegment::serialize(const uint32_t datagram_layer_checksum) const {
TCPHeader header_out = _header;
header_out.cksum = 0;
// calculate checksum -- taken over entire segment
InternetChecksum check(datagram_layer_checksum);
check.add(header_out.serialize());
check.add(_payload);
header_out.cksum = check.value();
BufferList ret;
ret.append(header_out.serialize());
ret.append(_payload);
return ret;
}
| 27.73913
| 92
| 0.710031
|
MUCZ
|
f3c1c85363d60cf28635e203f7dcde4bd2e30cd7
| 628
|
hpp
|
C++
|
src/include/guinsoodb/common/enums/index_type.hpp
|
GuinsooLab/guinsoodb
|
f200538868738ae460f62fb89211deec946cefff
|
[
"MIT"
] | 1
|
2021-04-22T05:41:54.000Z
|
2021-04-22T05:41:54.000Z
|
src/include/guinsoodb/common/enums/index_type.hpp
|
GuinsooLab/guinsoodb
|
f200538868738ae460f62fb89211deec946cefff
|
[
"MIT"
] | null | null | null |
src/include/guinsoodb/common/enums/index_type.hpp
|
GuinsooLab/guinsoodb
|
f200538868738ae460f62fb89211deec946cefff
|
[
"MIT"
] | 1
|
2021-12-12T10:24:57.000Z
|
2021-12-12T10:24:57.000Z
|
//===----------------------------------------------------------------------===//
// GuinsooDB
//
// guinsoodb/common/enums/index_type.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "guinsoodb/common/constants.hpp"
namespace guinsoodb {
//===--------------------------------------------------------------------===//
// Index Types
//===--------------------------------------------------------------------===//
enum class IndexType {
INVALID = 0, // invalid index type
ART = 1 // Adaptive Radix Tree
};
} // namespace guinsoodb
| 26.166667
| 80
| 0.31051
|
GuinsooLab
|
f3c3e632fda892b50534f30c82e10c0f5ac7dc46
| 4,185
|
hpp
|
C++
|
Doxa/Algorithm.hpp
|
paulbauriegel/Doxa
|
58abb90173c4ab12b0b4c1ad7a675e116cda615d
|
[
"CC0-1.0"
] | 109
|
2017-02-24T18:26:35.000Z
|
2022-03-23T02:42:45.000Z
|
Doxa/Algorithm.hpp
|
paulbauriegel/Doxa
|
58abb90173c4ab12b0b4c1ad7a675e116cda615d
|
[
"CC0-1.0"
] | 14
|
2018-10-02T08:35:09.000Z
|
2021-10-10T05:13:11.000Z
|
Doxa/Algorithm.hpp
|
paulbauriegel/Doxa
|
58abb90173c4ab12b0b4c1ad7a675e116cda615d
|
[
"CC0-1.0"
] | 28
|
2018-05-08T09:08:57.000Z
|
2022-01-21T07:04:29.000Z
|
// Δoxa Binarization Framework
// License: CC0 2018, "Freely you have received; freely give." - Matt 10:8
#ifndef ALGORITHMS_HPP
#define ALGORITHMS_HPP
#include "Image.hpp"
#include "Parameters.hpp"
#include "Palette.hpp"
namespace Doxa
{
/// <summary>
/// Algorithm Interface - Useful if you want to dynamically instantiate an algorithm.
/// </summary>
class IAlgorithm
{
public:
virtual ~IAlgorithm() { /* Virtual DTOR */ };
/// <summary>
/// Sets the Gray Scale image that will later be used to generate a binary image.
/// This allows the derived class to also initialize the image with any one time calculations.
/// </summary>
/// <param name="grayScaleImageIn">An Image object containing gray scale content</param>
virtual void Initialize(const Image& grayScaleImageIn) = 0;
/// <summary>
/// Takes the initialized Gray Scale image and returns back a Binary image by reference.
/// The Binary image memory should already be allocated before being passed by reference.
/// This method was designed to be called repeatedly with different parameters.
/// </summary>
/// <param name="binaryImageOut">An Image object with preallocated memory which will store the output</param>
/// <param name="parameters">Any parameters the algorithm may need</param>
virtual void ToBinary(Image& binaryImageOut, const Parameters& parameters = Parameters()) = 0;
};
/// <summary>
/// This is a base class for all of our binarization algorithms.
/// It uses the Curiously Recurring Template Pattern for compile time inheritance.
/// </summary>
template<typename BinaryAlgorithm>
class Algorithm : public IAlgorithm
{
public:
/// <summary>
/// Sets the Gray Scale image that will later be used to generate a binary image.
/// This allows the derived class to also initialize the image with any one time calculations.
/// </summary>
/// <param name="grayScaleImageIn">An Image object containing gray scale content</param>
virtual void Initialize(const Image& grayScaleImageIn)
{
this->grayScaleImageIn = grayScaleImageIn.Reference();
}
/// <summary>
/// A conveniance method for taking in a Gray Scale image /w params and returning a Binary image.
/// </summary>
static Image ToBinaryImage(const Image& grayScaleImageIn, const Parameters& parameters = Parameters())
{
// Generate space for the binary image
Image binaryImageOut(grayScaleImageIn.width, grayScaleImageIn.height);
// Run Binarization Algorithm
BinaryAlgorithm algorithm;
algorithm.Initialize(grayScaleImageIn);
algorithm.ToBinary(binaryImageOut, parameters);
// The Move semantics allow this our underlying image to move without being copied
return binaryImageOut;
}
/// <summary>
/// A conveniance method for safely converting a Gray Scale image to Binary.
/// Note: You may need to create a temp image and copy it, depending on your algorithm.
/// </summary>
static void UpdateToBinary(Image& image, const Parameters& parameters = Parameters())
{
BinaryAlgorithm algorithm;
algorithm.Initialize(image);
algorithm.ToBinary(image, parameters);
}
protected:
Image grayScaleImageIn;
};
/// <summary>
/// The base class for all Global Thresholding algorithms.
/// </summary>
template<typename BinaryAlgorithm>
class GlobalThreshold : public Algorithm<BinaryAlgorithm>
{
public:
/// <summary>
/// Calculates and returns the global threshold of the image.
/// </summary>
/// <returns>A global binarization threshold value</returns>
virtual Pixel8 Threshold(const Image& grayScaleImage, const Parameters& parameters = Parameters()) = 0;
/// <summary>
/// Global binarization based on a single threshold
/// </summary>
void ToBinary(Image& binaryImageOut, const Parameters& parameters = Parameters())
{
const Pixel8 threshold = Threshold(Algorithm<BinaryAlgorithm>::grayScaleImageIn, parameters);
for (int idx = 0; idx < Algorithm<BinaryAlgorithm>::grayScaleImageIn.size; ++idx)
{
binaryImageOut.data[idx] =
Algorithm<BinaryAlgorithm>::grayScaleImageIn.data[idx] <= threshold ?
Palette::Black : Palette::White;
}
}
};
}
#endif //ALGORITHMS_HPP
| 34.586777
| 111
| 0.726165
|
paulbauriegel
|
f3cb8db287fb044b73e5979f6c2347b042d81ceb
| 1,679
|
hpp
|
C++
|
impl/jamtemplate/common/game_base.hpp
|
runvs/Gemga
|
91cd5d6d60ae8369a5a5674efebc6eb84c510a10
|
[
"CC0-1.0"
] | null | null | null |
impl/jamtemplate/common/game_base.hpp
|
runvs/Gemga
|
91cd5d6d60ae8369a5a5674efebc6eb84c510a10
|
[
"CC0-1.0"
] | null | null | null |
impl/jamtemplate/common/game_base.hpp
|
runvs/Gemga
|
91cd5d6d60ae8369a5a5674efebc6eb84c510a10
|
[
"CC0-1.0"
] | null | null | null |
#ifndef GUARD_JAMTEMPLATE_GAMEBASE_HPP_GUARD
#define GUARD_JAMTEMPLATE_GAMEBASE_HPP_GUARD
#include "color.hpp"
#include "game_interface.hpp"
#include "game_loop_interface.hpp"
#include "game_object.hpp"
#include "music_player_interface.hpp"
#include "render_target.hpp"
#include "vector.hpp"
#include <chrono>
#include <memory>
namespace jt {
class GameState;
class GameBase : public GameInterface,
public GameObject,
public std::enable_shared_from_this<GameBase> {
public:
GameBase(std::shared_ptr<CamInterface> camera = nullptr);
// this function will likely be called by the user from within update().
// To ensure consisten behavior within one frame, the actual switching will take place in
// doSwitchState() which will happen at the beginning of the next update loop.
void switchState(std::shared_ptr<GameState> newState) override;
std::shared_ptr<GameState> getCurrentState() override;
void run() override;
virtual std::shared_ptr<CamInterface> getCamera() override;
virtual std::shared_ptr<CamInterface> getCamera() const override;
protected:
std::shared_ptr<GameState> m_state { nullptr };
std::shared_ptr<GameState> m_nextState { nullptr };
std::shared_ptr<CamInterface> mutable m_camera { nullptr };
std::chrono::steady_clock::time_point m_timeLast {};
jt::Color m_backgroundColor { jt::colors::Black };
std::weak_ptr<GameInterface> getPtr() override;
// overwritten functions from GameObject
virtual void doUpdate(float const elapsed) override = 0;
virtual void doDraw() const override = 0;
void doSwitchState();
};
} // namespace jt
#endif
| 29.982143
| 93
| 0.732579
|
runvs
|
f3cdd23ddff19cf38783a893f9c60a6bc311af9f
| 1,378
|
cc
|
C++
|
elements/ip6/getip6address.cc
|
MacWR/Click-changed-for-ParaGraph
|
18285e5da578fbb7285d10380836146e738dee6e
|
[
"Apache-2.0"
] | 129
|
2015-10-08T14:38:35.000Z
|
2022-03-06T14:54:44.000Z
|
elements/ip6/getip6address.cc
|
MacWR/Click-changed-for-ParaGraph
|
18285e5da578fbb7285d10380836146e738dee6e
|
[
"Apache-2.0"
] | 241
|
2016-02-17T16:17:58.000Z
|
2022-03-15T09:08:33.000Z
|
elements/ip6/getip6address.cc
|
MacWR/Click-changed-for-ParaGraph
|
18285e5da578fbb7285d10380836146e738dee6e
|
[
"Apache-2.0"
] | 61
|
2015-12-17T01:46:58.000Z
|
2022-02-07T22:25:19.000Z
|
/*
* getip6address.{cc,hh} -- element sets IP6 destination annotation from
* packet header
* Peilei Fan
*
* Copyright (c) 1999-2000 Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, subject to the conditions
* listed in the Click LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Click LICENSE file; the license in that file is
* legally binding.
*/
#include <click/config.h>
#include "getip6address.hh"
#include <click/args.hh>
#include <click/error.hh>
#include <clicknet/ip6.h>
CLICK_DECLS
GetIP6Address::GetIP6Address()
{
}
GetIP6Address::~GetIP6Address()
{
}
int
GetIP6Address::configure(Vector<String> &conf, ErrorHandler *errh)
{
return Args(conf, this, errh).read_mp("OFFSET", _offset).complete();
}
Packet *
GetIP6Address::simple_action(Packet *p)
{
IP6Address dst=IP6Address((unsigned char *)(p->data()+ _offset));
SET_DST_IP6_ANNO(p, dst);
return p;
}
CLICK_ENDDECLS
EXPORT_ELEMENT(GetIP6Address)
| 26.5
| 77
| 0.751089
|
MacWR
|
f3d185e8dfd0eb73ce6bf1575b8799d28004fc9d
| 1,654
|
cpp
|
C++
|
Practice/2018/2018.8.6/BZOJ1078.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | 4
|
2017-10-31T14:25:18.000Z
|
2018-06-10T16:10:17.000Z
|
Practice/2018/2018.8.6/BZOJ1078.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
Practice/2018/2018.8.6/BZOJ1078.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=100;
const int inf=2147483647;
int n,id;
int Size[maxN],Depth[maxN];
int Ls[maxN],Rs[maxN],Fa[maxN];
int Seq[maxN];
void dfs_init(int u);
void dfs_min(int u);
int main(){
scanf("%d",&n);
for (int i=1;i<=n;i++){
int d;scanf("%d",&d);
if (d<100) Ls[d]=i,Fa[i]=d;
else Rs[d-100]=i,Fa[i]=d-100;
}
Depth[0]=1;
dfs_init(0);
//for (int i=0;i<=n;i++) cout<<Ls[i]<<" "<<Rs[i]<<endl;
//for (int i=0;i<=n;i++) cout<<Size[i]<<" ";cout<<endl<<endl;
int root=0;Depth[n+1]=inf;
for (int i=1;i<=n+1;i++){
id=n+1;
dfs_min(root);
if ((Ls[id])&&(Size[Ls[id]]==1)) id=Ls[id];
Seq[i]=id;
if (id==root){
root=Ls[root];Depth[root]=1;Fa[root]=-1;
}
else{
if (Ls[id]) Fa[Ls[id]]=Fa[id],Ls[Fa[id]]=Ls[id];
else Ls[Fa[id]]=0;
for (int now=Fa[id];now!=root;now=Fa[now]) swap(Ls[now],Rs[now]);
swap(Ls[root],Rs[root]);
}
dfs_init(root);
//cout<<root<<" "<<id<<endl;
//for (int j=0;j<=n;j++) cout<<Ls[j]<<" "<<Rs[j]<<endl;
//for (int j=0;j<=n;j++) cout<<Fa[j]<<" ";cout<<endl;
//for (int j=0;j<=n;j++) cout<<Size[j]<<" ";cout<<endl<<endl;
}
for (int i=n+1;i>=1;i--) printf("%d ",Seq[i]);
return 0;
}
void dfs_init(int u){
Size[u]=1;
if (Ls[u]){
Depth[Ls[u]]=Depth[u]+1;
dfs_init(Ls[u]);Size[u]+=Size[Ls[u]];
}
if (Rs[u]){
Depth[Rs[u]]=Depth[u]+1;
dfs_init(Rs[u]);Size[u]+=Size[Rs[u]];
}
return;
}
void dfs_min(int u){
if ((Rs[u]==0)&&(Depth[u]<Depth[id])) id=u;
if (Ls[u]) dfs_min(Ls[u]);
return;
}
| 20.170732
| 68
| 0.555623
|
SYCstudio
|
f3d3471508bd076a26e68a38f816e3978ae489e2
| 408
|
cpp
|
C++
|
35.Search_Insert_Position/solution_linearSearch.cpp
|
bngit/leetcode-practices
|
5324aceac708d9b214a7d98d489b8d5dc55c89e9
|
[
"MIT"
] | null | null | null |
35.Search_Insert_Position/solution_linearSearch.cpp
|
bngit/leetcode-practices
|
5324aceac708d9b214a7d98d489b8d5dc55c89e9
|
[
"MIT"
] | null | null | null |
35.Search_Insert_Position/solution_linearSearch.cpp
|
bngit/leetcode-practices
|
5324aceac708d9b214a7d98d489b8d5dc55c89e9
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
#include <cassert>
#include <algorithm>
#include <sstream>
using namespace std;
class Solution {
public:
int searchInsert(vector<int> &nums, int target) {
for (auto i = 0; i < nums.size(); ++i) {
if (nums[i] >= target) {
return i;
}
}
return nums.size();
}
};
| 19.428571
| 53
| 0.551471
|
bngit
|
f3d842f65819ab985106ec3b5d281537b2d34590
| 246
|
hpp
|
C++
|
tlab/include/tlab/tlab.hpp
|
gwonhyeong/tlab
|
f84963f2636fdb830ab300b92ec1d8395ce2da58
|
[
"MIT"
] | null | null | null |
tlab/include/tlab/tlab.hpp
|
gwonhyeong/tlab
|
f84963f2636fdb830ab300b92ec1d8395ce2da58
|
[
"MIT"
] | null | null | null |
tlab/include/tlab/tlab.hpp
|
gwonhyeong/tlab
|
f84963f2636fdb830ab300b92ec1d8395ce2da58
|
[
"MIT"
] | null | null | null |
/**
* @file tlab.hpp
* @author ghtak (gwonhyeong.tak@gmail.com)
* @brief
* @version 0.1
* @date 2019-07-23
*
* @copyright Copyright (c) 2019
*
*/
#ifndef __tlab_h__
#define __tlab_h__
namespace tlab{
int interest(void);
}
#endif
| 13.666667
| 43
| 0.638211
|
gwonhyeong
|
f3db294d7ebf19a0c0ee6d430ae44ca910983695
| 6,709
|
cpp
|
C++
|
ecm/src/v20190719/model/TaskOutput.cpp
|
sinjoywong/tencentcloud-sdk-cpp
|
1b931d20956a90b15a6720f924e5c69f8786f9f4
|
[
"Apache-2.0"
] | null | null | null |
ecm/src/v20190719/model/TaskOutput.cpp
|
sinjoywong/tencentcloud-sdk-cpp
|
1b931d20956a90b15a6720f924e5c69f8786f9f4
|
[
"Apache-2.0"
] | null | null | null |
ecm/src/v20190719/model/TaskOutput.cpp
|
sinjoywong/tencentcloud-sdk-cpp
|
1b931d20956a90b15a6720f924e5c69f8786f9f4
|
[
"Apache-2.0"
] | null | null | null |
/*
* 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.
*/
#include <tencentcloud/ecm/v20190719/model/TaskOutput.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ecm::V20190719::Model;
using namespace std;
TaskOutput::TaskOutput() :
m_taskIdHasBeenSet(false),
m_messageHasBeenSet(false),
m_statusHasBeenSet(false),
m_addTimeHasBeenSet(false),
m_endTimeHasBeenSet(false),
m_operationHasBeenSet(false)
{
}
CoreInternalOutcome TaskOutput::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("TaskId") && !value["TaskId"].IsNull())
{
if (!value["TaskId"].IsString())
{
return CoreInternalOutcome(Error("response `TaskOutput.TaskId` IsString=false incorrectly").SetRequestId(requestId));
}
m_taskId = string(value["TaskId"].GetString());
m_taskIdHasBeenSet = true;
}
if (value.HasMember("Message") && !value["Message"].IsNull())
{
if (!value["Message"].IsString())
{
return CoreInternalOutcome(Error("response `TaskOutput.Message` IsString=false incorrectly").SetRequestId(requestId));
}
m_message = string(value["Message"].GetString());
m_messageHasBeenSet = true;
}
if (value.HasMember("Status") && !value["Status"].IsNull())
{
if (!value["Status"].IsString())
{
return CoreInternalOutcome(Error("response `TaskOutput.Status` IsString=false incorrectly").SetRequestId(requestId));
}
m_status = string(value["Status"].GetString());
m_statusHasBeenSet = true;
}
if (value.HasMember("AddTime") && !value["AddTime"].IsNull())
{
if (!value["AddTime"].IsString())
{
return CoreInternalOutcome(Error("response `TaskOutput.AddTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_addTime = string(value["AddTime"].GetString());
m_addTimeHasBeenSet = true;
}
if (value.HasMember("EndTime") && !value["EndTime"].IsNull())
{
if (!value["EndTime"].IsString())
{
return CoreInternalOutcome(Error("response `TaskOutput.EndTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_endTime = string(value["EndTime"].GetString());
m_endTimeHasBeenSet = true;
}
if (value.HasMember("Operation") && !value["Operation"].IsNull())
{
if (!value["Operation"].IsString())
{
return CoreInternalOutcome(Error("response `TaskOutput.Operation` IsString=false incorrectly").SetRequestId(requestId));
}
m_operation = string(value["Operation"].GetString());
m_operationHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void TaskOutput::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_taskIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TaskId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_taskId.c_str(), allocator).Move(), allocator);
}
if (m_messageHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Message";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_message.c_str(), allocator).Move(), allocator);
}
if (m_statusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Status";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_status.c_str(), allocator).Move(), allocator);
}
if (m_addTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AddTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_addTime.c_str(), allocator).Move(), allocator);
}
if (m_endTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EndTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_endTime.c_str(), allocator).Move(), allocator);
}
if (m_operationHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Operation";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_operation.c_str(), allocator).Move(), allocator);
}
}
string TaskOutput::GetTaskId() const
{
return m_taskId;
}
void TaskOutput::SetTaskId(const string& _taskId)
{
m_taskId = _taskId;
m_taskIdHasBeenSet = true;
}
bool TaskOutput::TaskIdHasBeenSet() const
{
return m_taskIdHasBeenSet;
}
string TaskOutput::GetMessage() const
{
return m_message;
}
void TaskOutput::SetMessage(const string& _message)
{
m_message = _message;
m_messageHasBeenSet = true;
}
bool TaskOutput::MessageHasBeenSet() const
{
return m_messageHasBeenSet;
}
string TaskOutput::GetStatus() const
{
return m_status;
}
void TaskOutput::SetStatus(const string& _status)
{
m_status = _status;
m_statusHasBeenSet = true;
}
bool TaskOutput::StatusHasBeenSet() const
{
return m_statusHasBeenSet;
}
string TaskOutput::GetAddTime() const
{
return m_addTime;
}
void TaskOutput::SetAddTime(const string& _addTime)
{
m_addTime = _addTime;
m_addTimeHasBeenSet = true;
}
bool TaskOutput::AddTimeHasBeenSet() const
{
return m_addTimeHasBeenSet;
}
string TaskOutput::GetEndTime() const
{
return m_endTime;
}
void TaskOutput::SetEndTime(const string& _endTime)
{
m_endTime = _endTime;
m_endTimeHasBeenSet = true;
}
bool TaskOutput::EndTimeHasBeenSet() const
{
return m_endTimeHasBeenSet;
}
string TaskOutput::GetOperation() const
{
return m_operation;
}
void TaskOutput::SetOperation(const string& _operation)
{
m_operation = _operation;
m_operationHasBeenSet = true;
}
bool TaskOutput::OperationHasBeenSet() const
{
return m_operationHasBeenSet;
}
| 26.623016
| 132
| 0.669697
|
sinjoywong
|
f3dcab407e224e528b67592f3703bc07b2d5e31c
| 673
|
cpp
|
C++
|
csf_workspace/css/src/core/system/attribute/csf_attribute_exception_critical.cpp
|
Kitty-Kitty/csf_library
|
011e56fb8b687818d20b9998a0cdb72332375534
|
[
"BSD-2-Clause"
] | 2
|
2019-12-17T13:16:48.000Z
|
2019-12-17T13:16:51.000Z
|
csf_workspace/css/src/core/system/attribute/csf_attribute_exception_critical.cpp
|
Kitty-Kitty/csf_library
|
011e56fb8b687818d20b9998a0cdb72332375534
|
[
"BSD-2-Clause"
] | null | null | null |
csf_workspace/css/src/core/system/attribute/csf_attribute_exception_critical.cpp
|
Kitty-Kitty/csf_library
|
011e56fb8b687818d20b9998a0cdb72332375534
|
[
"BSD-2-Clause"
] | null | null | null |
/*******************************************************************************
*
*Copyright: armuxinxian@aliyun.com
*
*File name: csf_attribute_exception_critical.hpp
*
*Author: Administrator
*
*Version: 1.0
*
*Date: 05-7月-2018 20:09:27
*
*Description: Class(csf_attribute_exception_critical)
*
*Others:
*
*History:
*******************************************************************************/
#include "csf_attribute_exception_critical.hpp"
using csf::core::system::configure::csf_attribute_exception_critical;
csf_attribute_exception_critical::csf_attribute_exception_critical() {
}
csf_attribute_exception_critical::~csf_attribute_exception_critical() {
}
| 20.393939
| 81
| 0.606241
|
Kitty-Kitty
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.