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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ffdd43ba4229406425d2e3a80e059cf7bbfec4b7 | 3,314 | hpp | C++ | include/obzerver/circular_buffer.hpp | AutonomyLab/obzerver | 71d95f82946f76119b8b8fe9c34be6976477504d | [
"Apache-2.0"
] | 6 | 2016-10-15T04:34:47.000Z | 2019-03-06T19:05:49.000Z | include/obzerver/circular_buffer.hpp | AutonomyLab/obzerver | 71d95f82946f76119b8b8fe9c34be6976477504d | [
"Apache-2.0"
] | null | null | null | include/obzerver/circular_buffer.hpp | AutonomyLab/obzerver | 71d95f82946f76119b8b8fe9c34be6976477504d | [
"Apache-2.0"
] | 8 | 2016-01-25T08:10:35.000Z | 2018-08-14T14:36:36.000Z | #ifndef CIRCULAR_BUFFER
#define CIRCULAR_BUFFER
#include <deque>
#include <cassert>
#include <stdexcept>
template<typename T>
class CircularBuffer {
private:
std::size_t max_sz;
std::deque<T> buffer;
T dummy;
public:
typedef typename std::deque<T>::iterator iterator;
typedef typename std::deque<T>::const_iterator const_iterator;
typedef typename std::deque<T>::reverse_iterator reverse_iterator;
typedef typename std::deque<T>::const_reverse_iterator const_reverse_iterator;
typedef typename std::deque<T>::reference reference;
typedef typename std::deque<T>::const_reference const_reference;
// This constructor does not fill the buffer, so the buffer size is 0
CircularBuffer(const std::size_t max_size): max_sz(max_size) {;}
// This fills the buffer with fill, so the buffer size will be sz
CircularBuffer(const std::size_t sz, const T& fill): max_sz(sz), buffer(sz, fill) {;}
const CircularBuffer& operator=(const CircularBuffer& rhs) {
max_sz = rhs.max_sz;
buffer = rhs.buffer;
return *this;
}
void push_front(const T& val) {
if (buffer.size() == max_sz) buffer.pop_back();
buffer.push_front(val);
assert(buffer.size() <= max_sz);
}
void push_back(const T& val) {
if (buffer.size() == max_sz) buffer.pop_front();
buffer.push_back(val);
assert(buffer.size() <= max_sz);
}
void pop_front() {
buffer.pop_front();
}
void pop_back() {
buffer.pop_back();
}
T& at(std::size_t index) {
return buffer.at(index);
}
const T& at(std::size_t index) const {
return buffer.at(index);
}
T& operator[](std::size_t index) {
return buffer[index];
}
const T& operator[](std::size_t index) const {
return buffer[index];
}
bool empty() const {
return (buffer.size() == 0);
}
std::size_t size() const {
return buffer.size();
}
std::size_t max_size() const {
return max_sz;
}
void resize(const std::size_t sz, const T& val) {
max_sz = sz;
buffer.resize(sz, val);
}
void clear() {
buffer.clear();
}
reference front() {
return buffer.front();
}
const_reference front() const {
return buffer.front();
}
reference back() {
return buffer.back();
}
const_reference back() const {
return buffer.back();
}
iterator begin() {
return buffer.begin();
}
const_iterator begin() const {
return buffer.begin();
}
iterator end() {
return buffer.end();
}
const_iterator end() const {
return buffer.end();
}
reverse_iterator rbegin() {
return buffer.rbegin();
}
const_reverse_iterator rbegin() const {
return buffer.rbegin();
}
reverse_iterator rend() {
return buffer.rend();
}
const_reverse_iterator rend() const {
return buffer.rend();
}
// These are two special functions
// if index i corresponds to time t-i
// prev(offset) is object at time t-offset
// You should always use push_front() to benefit from this
// throws std::out_of_range on failure
const_reference prev(const std::size_t offset = 1) const {
return buffer.at(offset);
}
const_reference latest() const {
if (!buffer.size()) {
throw std::out_of_range("Cannot access latest, Circular Buffer is empty.");
}
return buffer.front();
}
};
#endif
| 20.842767 | 87 | 0.655401 | AutonomyLab |
ffdf843818650242f9ad83c8930e2f1463e83753 | 8,350 | cpp | C++ | CLR/Libraries/SPOT/spot_native.cpp | PervasiveDigital/netmf-interpreter | 03d84fe76e0b666ebec62d17d69c55c45940bc40 | [
"Apache-2.0"
] | 529 | 2015-03-10T00:17:45.000Z | 2022-03-17T02:21:19.000Z | CLR/Libraries/SPOT/spot_native.cpp | PervasiveDigital/netmf-interpreter | 03d84fe76e0b666ebec62d17d69c55c45940bc40 | [
"Apache-2.0"
] | 495 | 2015-03-10T22:02:46.000Z | 2019-05-16T13:05:00.000Z | CLR/Libraries/SPOT/spot_native.cpp | PervasiveDigital/netmf-interpreter | 03d84fe76e0b666ebec62d17d69c55c45940bc40 | [
"Apache-2.0"
] | 332 | 2015-03-10T08:04:36.000Z | 2022-03-29T04:18:36.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "spot.h"
static const CLR_RT_MethodHandler method_lookup[] =
{
Library_spot_native_Microsoft_SPOT_Reflection::GetTypesImplementingInterface___STATIC__SZARRAY_mscorlibSystemType__mscorlibSystemType,
Library_spot_native_Microsoft_SPOT_Reflection::IsTypeLoaded___STATIC__BOOLEAN__mscorlibSystemType,
Library_spot_native_Microsoft_SPOT_Reflection::GetTypeHash___STATIC__U4__mscorlibSystemType,
Library_spot_native_Microsoft_SPOT_Reflection::GetAssemblyHash___STATIC__U4__mscorlibSystemReflectionAssembly,
Library_spot_native_Microsoft_SPOT_Reflection::GetAssemblies___STATIC__SZARRAY_mscorlibSystemReflectionAssembly,
Library_spot_native_Microsoft_SPOT_Reflection::GetAssemblyInfo___STATIC__BOOLEAN__SZARRAY_U1__MicrosoftSPOTReflectionAssemblyInfo,
Library_spot_native_Microsoft_SPOT_Reflection::GetAssemblyMemoryInfo___STATIC__BOOLEAN__mscorlibSystemReflectionAssembly__MicrosoftSPOTReflectionAssemblyMemoryInfo,
Library_spot_native_Microsoft_SPOT_Reflection::GetTypeFromHash___STATIC__mscorlibSystemType__U4,
Library_spot_native_Microsoft_SPOT_Reflection::GetAssemblyFromHash___STATIC__mscorlibSystemReflectionAssembly__U4,
Library_spot_native_Microsoft_SPOT_Reflection::Serialize___STATIC__SZARRAY_U1__OBJECT__mscorlibSystemType,
Library_spot_native_Microsoft_SPOT_Reflection::Deserialize___STATIC__OBJECT__SZARRAY_U1__mscorlibSystemType,
NULL,
NULL,
NULL,
NULL,
Library_spot_native_Microsoft_SPOT_Debug::Print___STATIC__VOID__STRING,
Library_spot_native_Microsoft_SPOT_Debug::GC___STATIC__U4__BOOLEAN,
Library_spot_native_Microsoft_SPOT_Debug::EnableGCMessages___STATIC__VOID__BOOLEAN,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_spot_native_Microsoft_SPOT_ExecutionConstraint::Install___STATIC__VOID__I4__I4,
Library_spot_native_Microsoft_SPOT_ExtendedTimer::Dispose___VOID,
Library_spot_native_Microsoft_SPOT_ExtendedTimer::_ctor___VOID__mscorlibSystemThreadingTimerCallback__OBJECT__I4__I4,
Library_spot_native_Microsoft_SPOT_ExtendedTimer::_ctor___VOID__mscorlibSystemThreadingTimerCallback__OBJECT__mscorlibSystemTimeSpan__mscorlibSystemTimeSpan,
Library_spot_native_Microsoft_SPOT_ExtendedTimer::_ctor___VOID__mscorlibSystemThreadingTimerCallback__OBJECT__mscorlibSystemDateTime__mscorlibSystemTimeSpan,
Library_spot_native_Microsoft_SPOT_ExtendedTimer::_ctor___VOID__mscorlibSystemThreadingTimerCallback__OBJECT__MicrosoftSPOTExtendedTimerTimeEvents,
Library_spot_native_Microsoft_SPOT_ExtendedTimer::Change___VOID__I4__I4,
Library_spot_native_Microsoft_SPOT_ExtendedTimer::Change___VOID__mscorlibSystemTimeSpan__mscorlibSystemTimeSpan,
Library_spot_native_Microsoft_SPOT_ExtendedTimer::Change___VOID__mscorlibSystemDateTime__mscorlibSystemTimeSpan,
Library_spot_native_Microsoft_SPOT_ExtendedTimer::get_LastExpiration___mscorlibSystemTimeSpan,
Library_spot_native_Microsoft_SPOT_ExtendedWeakReference::_ctor___VOID__OBJECT__mscorlibSystemType__U4__U4,
Library_spot_native_Microsoft_SPOT_ExtendedWeakReference::get_Selector___mscorlibSystemType,
Library_spot_native_Microsoft_SPOT_ExtendedWeakReference::get_Id___U4,
Library_spot_native_Microsoft_SPOT_ExtendedWeakReference::get_Flags___U4,
Library_spot_native_Microsoft_SPOT_ExtendedWeakReference::get_Priority___I4,
Library_spot_native_Microsoft_SPOT_ExtendedWeakReference::set_Priority___VOID__I4,
Library_spot_native_Microsoft_SPOT_ExtendedWeakReference::PushBackIntoRecoverList___VOID,
NULL,
Library_spot_native_Microsoft_SPOT_ExtendedWeakReference::Recover___STATIC__MicrosoftSPOTExtendedWeakReference__mscorlibSystemType__U4,
Library_spot_native_Microsoft_SPOT_ExtendedWeakReference::FlushAll___STATIC__VOID,
NULL,
NULL,
Library_spot_native_Microsoft_SPOT_Hardware_SystemInfo::GetSystemVersion___STATIC__VOID__BYREF_I4__BYREF_I4__BYREF_I4__BYREF_I4,
NULL,
Library_spot_native_Microsoft_SPOT_Hardware_SystemInfo::get_OEMString___STATIC__STRING,
Library_spot_native_Microsoft_SPOT_Hardware_SystemInfo::get_IsBigEndian___STATIC__BOOLEAN,
NULL,
Library_spot_native_Microsoft_SPOT_Hardware_Utility::ComputeCRC___STATIC__U4__SZARRAY_U1__I4__I4__U4,
Library_spot_native_Microsoft_SPOT_Hardware_Utility::ExtractValueFromArray___STATIC__U4__SZARRAY_U1__I4__I4,
Library_spot_native_Microsoft_SPOT_Hardware_Utility::InsertValueIntoArray___STATIC__VOID__SZARRAY_U1__I4__I4__U4,
Library_spot_native_Microsoft_SPOT_Hardware_Utility::ExtractRangeFromArray___STATIC__SZARRAY_U1__SZARRAY_U1__I4__I4,
Library_spot_native_Microsoft_SPOT_Hardware_Utility::CombineArrays___STATIC__SZARRAY_U1__SZARRAY_U1__SZARRAY_U1,
Library_spot_native_Microsoft_SPOT_Hardware_Utility::CombineArrays___STATIC__SZARRAY_U1__SZARRAY_U1__I4__I4__SZARRAY_U1__I4__I4,
Library_spot_native_Microsoft_SPOT_Hardware_Utility::SetLocalTime___STATIC__VOID__mscorlibSystemDateTime,
Library_spot_native_Microsoft_SPOT_Hardware_Utility::GetMachineTime___STATIC__mscorlibSystemTimeSpan,
Library_spot_native_Microsoft_SPOT_Hardware_Utility::Piezo___STATIC__VOID__U4__U4,
Library_spot_native_Microsoft_SPOT_Hardware_Utility::Backlight___STATIC__VOID__BOOLEAN,
NULL,
NULL,
NULL,
NULL,
Library_spot_native_Microsoft_SPOT_Math::Cos___STATIC__I4__I4,
Library_spot_native_Microsoft_SPOT_Math::Sin___STATIC__I4__I4,
Library_spot_native_Microsoft_SPOT_Messaging_EndPoint::_ctor___VOID__mscorlibSystemType__U4,
Library_spot_native_Microsoft_SPOT_Messaging_EndPoint::Check___BOOLEAN__mscorlibSystemType__U4__I4,
Library_spot_native_Microsoft_SPOT_Messaging_EndPoint::GetMessage___MicrosoftSPOTMessagingMessage__I4,
NULL,
Library_spot_native_Microsoft_SPOT_Messaging_EndPoint::SendMessageRaw___SZARRAY_U1__mscorlibSystemType__U4__I4__SZARRAY_U1,
Library_spot_native_Microsoft_SPOT_Messaging_EndPoint::ReplyRaw___VOID__MicrosoftSPOTMessagingMessage__SZARRAY_U1,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_spot_native_Microsoft_SPOT_ResourceUtility::GetObject___STATIC__OBJECT__mscorlibSystemResourcesResourceManager__mscorlibSystemEnum,
Library_spot_native_Microsoft_SPOT_ResourceUtility::GetObject___STATIC__OBJECT__mscorlibSystemResourcesResourceManager__mscorlibSystemEnum__I4__I4,
Library_spot_native_Microsoft_SPOT_ResourceUtility::set_CurrentUICultureInternal___STATIC__VOID__mscorlibSystemGlobalizationCultureInfo,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_spot_native_Microsoft_SPOT_WeakDelegate::Combine___STATIC__mscorlibSystemDelegate__mscorlibSystemDelegate__mscorlibSystemDelegate,
Library_spot_native_Microsoft_SPOT_WeakDelegate::Remove___STATIC__mscorlibSystemDelegate__mscorlibSystemDelegate__mscorlibSystemDelegate,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_spot_native_System_Security_Cryptography_X509Certificates_X509Certificate::ParseCertificate___STATIC__VOID__SZARRAY_U1__STRING__BYREF_STRING__BYREF_STRING__BYREF_mscorlibSystemDateTime__BYREF_mscorlibSystemDateTime,
Library_spot_native_Microsoft_SPOT_Hardware_SystemInfo__SystemID::get_OEM___STATIC__U1,
Library_spot_native_Microsoft_SPOT_Hardware_SystemInfo__SystemID::get_Model___STATIC__U1,
Library_spot_native_Microsoft_SPOT_Hardware_SystemInfo__SystemID::get_SKU___STATIC__U2,
};
const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_Microsoft_SPOT_Native =
{
"Microsoft.SPOT.Native",
0x4BF34DF8,
method_lookup
};
| 59.219858 | 228 | 0.823593 | PervasiveDigital |
ffe6215f6158e9e5feee0db60bcb07f9a633d762 | 5,073 | cpp | C++ | src/settings/tabtexteditor.cpp | nameisalreadytakenexception/PairStormIDE | 7c41dc91611f9a9db62c8c9ac0373e0fe33fec59 | [
"MIT"
] | 4 | 2019-07-23T13:00:58.000Z | 2021-09-24T19:03:01.000Z | src/settings/tabtexteditor.cpp | nameisalreadytakenexception/PairStormIDE | 7c41dc91611f9a9db62c8c9ac0373e0fe33fec59 | [
"MIT"
] | 4 | 2019-07-23T12:33:11.000Z | 2019-08-20T11:39:16.000Z | src/settings/tabtexteditor.cpp | nameisalreadytakenexception/PairStormIDE | 7c41dc91611f9a9db62c8c9ac0373e0fe33fec59 | [
"MIT"
] | 1 | 2019-11-02T15:07:13.000Z | 2019-11-02T15:07:13.000Z | #include "tabtexteditor.h"
#include <QHBoxLayout>
#include <QSettings>
#include <QTreeWidget>
#include <QComboBox>
#include <QLabel>
#include <QTextEdit>
#include <QFontDatabase>
#include <QDebug>
TabTextEditor::TabTextEditor(QWidget *parent)
: QWidget(parent)
{
QHBoxLayout *mainLayout = new QHBoxLayout;
mainLayout->addStretch(mBasicStretch);
// getting data from QSettings
QSettings s;
mFontSizeCurrent = (s.contains("editorFontSize") ? s.value("editorFontSize").toString() : mFontSizeDefault);
mFontCurrent = (s.contains("editorFontName") ? s.value("editorFontName").toString() : mFontDefault);
mFontSizeNew = mFontSizeCurrent;
mFontNew = mFontCurrent;
// FONT SIZE
QHBoxLayout *fontSizeLayoutHoriz = new QHBoxLayout;
fontSizeLayoutHoriz->addStretch(mBasicStretch);
// set a label
QLabel *fontSizeLabel = new QLabel(tr("Font size"));
mpComboFontSize = new QComboBox(this);
for (int i = minRange; i <= maxRange; i += 2)
{
mFontSizeList << QString::number(i);
}
mpComboFontSize->addItems(mFontSizeList);
fontSizeLayoutHoriz->addWidget(fontSizeLabel);
fontSizeLayoutHoriz->addWidget(mpComboFontSize);
QVBoxLayout *fontSizeLayoutVert = new QVBoxLayout;
fontSizeLayoutVert->addStretch(mBasicStretch);
fontSizeLayoutVert->addLayout(fontSizeLayoutHoriz);
fontSizeLayoutVert->addSpacing(100);
fontSizeLayoutVert->addStretch(100);
mainLayout->addLayout(fontSizeLayoutVert);
mainLayout->addSpacing(mColumnSpacing);
// set combobox acording to settings
mpComboFontSize->setCurrentIndex(0);
for(int i = 0; i < mFontSizeList.size(); ++i)
{
auto &item = mFontSizeList[i];
if (item == mFontSizeCurrent)
{
mpComboFontSize->setCurrentIndex(i);
break;
}
}
connect(mpComboFontSize, SIGNAL(currentIndexChanged(const QString&)),
SLOT(onChangeFontSize(const QString&)));
// FONT NAME
// handling system fonts
setupFontTree();
mainLayout->addWidget(mpFontTree);
mainLayout->addSpacing(mColumnSpacing);
// preview selected font
mpTextEdit = new QTextEdit(this);
mainLayout->addWidget(mpTextEdit);
showFont(mpFontTree->topLevelItem(mFontNumber - 1));
mainLayout->addStretch(100);
setLayout(mainLayout);
connect(mpFontTree, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
this, SLOT(showFont(QTreeWidgetItem*)));
}
const QString &TabTextEditor::getFontSizeCurrernt() const
{
return mFontSizeCurrent;
}
const QString &TabTextEditor::getFontSizeNew() const
{
return mFontSizeNew;
}
void TabTextEditor::setFontSizeCurrernt(const QString & newFontSize)
{
mFontSizeCurrent = newFontSize;
}
const QString &TabTextEditor::getFontCurrernt() const
{
return mFontCurrent;
}
const QString &TabTextEditor::getFontNew() const
{
return mFontNew;
}
void TabTextEditor::setFontCurrernt(const QString & newFont)
{
mFontCurrent = newFont;
}
void TabTextEditor::setupFontTree()
{
QFontDatabase database;
mpFontTree = new QTreeWidget;
mpFontTree->setColumnCount(1);
mpFontTree->setHeaderLabels(QStringList() << tr("Font"));
int decentFontNumber = 0;
bool foundFont = false;
foreach (QString family, database.families()) {
QTreeWidgetItem *familyItem = new QTreeWidgetItem(mpFontTree);
familyItem->setText(0, family);
++decentFontNumber;
if (family == mFontCurrent)
{
mFontNumber = decentFontNumber;
familyItem->setSelected(true);
foundFont = true;
}
}
if (!foundFont) // in system not found decent font. choose first in database
{
mpFontTree->setCurrentItem(
mpFontTree->topLevelItem(0), // item
0, // column
QItemSelectionModel::Select // command
);
mFontNumber = 1;
}
}
void TabTextEditor::showFont(QTreeWidgetItem *item)
{
if (!item)
return;
QString family;
if (item->parent())
family = item->parent()->text(0);
else
family = item->text(0);
mFontNew = family;
QString oldText = mpTextEdit->toPlainText().trimmed();
bool modified = mpTextEdit->document()->isModified();
mpTextEdit->clear();
QFont font(family, mFontSizePreview, QFont::Normal, false);
mpTextEdit->document()->setDefaultFont(font);
QTextCursor cursor = mpTextEdit->textCursor();
QTextBlockFormat blockFormat;
blockFormat.setAlignment(Qt::AlignCenter);
cursor.insertBlock(blockFormat);
if (modified)
cursor.insertText(QString(oldText));
else
cursor.insertText(QString("%1").arg(family));
mpTextEdit->document()->setModified(modified);
emit onChangeFont(mFontNew);
}
void TabTextEditor::onChangeFont(const QString & newItem)
{
mFontNew = newItem;
}
void TabTextEditor::onChangeFontSize(const QString & newItem)
{
mFontSizeNew = newItem;
}
| 27.421622 | 112 | 0.673172 | nameisalreadytakenexception |
ffe7f0058b6fdb18e002ad15b54f65af93137360 | 2,921 | cpp | C++ | Source/PsDataPlugin/Private/Collection/PsDataBlueprintArrayProxy.cpp | mjukel/PsData | d0f11c82f23b18d32fe30dab259b16329d385a77 | [
"MIT"
] | null | null | null | Source/PsDataPlugin/Private/Collection/PsDataBlueprintArrayProxy.cpp | mjukel/PsData | d0f11c82f23b18d32fe30dab259b16329d385a77 | [
"MIT"
] | null | null | null | Source/PsDataPlugin/Private/Collection/PsDataBlueprintArrayProxy.cpp | mjukel/PsData | d0f11c82f23b18d32fe30dab259b16329d385a77 | [
"MIT"
] | null | null | null | // Copyright 2015-2019 Mail.Ru Group. All Rights Reserved.
#include "Collection/PsDataBlueprintArrayProxy.h"
#include "PsDataCore.h"
UPsDataBlueprintArrayProxy::UPsDataBlueprintArrayProxy(const class FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
, Proxy()
{
}
void UPsDataBlueprintArrayProxy::Init(UPsData* Instance, const TSharedPtr<const FDataField> Field)
{
check(!Proxy.IsValid());
Proxy = FPsDataArrayProxy<UPsData*>(Instance, Field);
check(IsValid());
}
bool UPsDataBlueprintArrayProxy::IsValid()
{
return Proxy.IsValid();
}
void UPsDataBlueprintArrayProxy::Bind(const FString& Type, const FPsDataDynamicDelegate& Delegate) const
{
Proxy.Bind(Type, Delegate);
}
void UPsDataBlueprintArrayProxy::Bind(const FString& Type, const FPsDataDelegate& Delegate) const
{
Proxy.Bind(Type, Delegate);
}
void UPsDataBlueprintArrayProxy::Unbind(const FString& Type, const FPsDataDynamicDelegate& Delegate) const
{
Proxy.Unbind(Type, Delegate);
}
void UPsDataBlueprintArrayProxy::Unbind(const FString& Type, const FPsDataDelegate& Delegate) const
{
Proxy.Unbind(Type, Delegate);
}
FPsDataConstArrayProxy<UPsData*> UPsDataBlueprintArrayProxy::GetProxy()
{
return Proxy;
}
void UPsDataBlueprintArrayProxy::BlueprintBind(const FString& Type, const FPsDataDynamicDelegate& Delegate)
{
Proxy.Bind(Type, Delegate);
}
void UPsDataBlueprintArrayProxy::BlueprintUnbind(const FString& Type, const FPsDataDynamicDelegate& Delegate)
{
Proxy.Unbind(Type, Delegate);
}
const TArray<UPsData*>& UPsDataBlueprintArrayProxy::GetRef()
{
return Proxy.GetRef();
}
int32 UPsDataBlueprintArrayProxy::Add(UPsData* Element) {
return Element != nullptr && this->IsValid() ? Proxy.Add(Element) : -1;
}
void UPsDataBlueprintArrayProxy::Insert(UPsData* Element, int32 Index) {
if(Element != nullptr && this->IsValid()) {
Proxy.Insert(Element, Index);
}
}
void UPsDataBlueprintArrayProxy::RemoveAt(int32 Index) {
if(this->IsValid()) {
Proxy.RemoveAt(Index);
}
}
int32 UPsDataBlueprintArrayProxy::Remove(UPsData* Element) {
return Element != nullptr && this->IsValid() ? Proxy.Remove(Element) : -1;
}
UPsData* UPsDataBlueprintArrayProxy::Set(UPsData* Element, int32 Index) {
return Element != nullptr && this->IsValid() ? Proxy.Set(Element, Index) : nullptr;
}
UPsData* UPsDataBlueprintArrayProxy::Get(int32 Index) {
return this->IsValid() && this->IsValidIndex(Index) ? Proxy.Get(Index) : nullptr;
}
int32 UPsDataBlueprintArrayProxy::Find(UPsData* Element) {
return Element != nullptr && this->IsValid() ? Proxy.Find(Element) : -1;
}
int32 UPsDataBlueprintArrayProxy::Num() {
return this->IsValid() ? Proxy.Num() : 0;
}
bool UPsDataBlueprintArrayProxy::IsEmpty() {
return this->IsValid() ? Proxy.IsEmpty() : true;
}
bool UPsDataBlueprintArrayProxy::IsValidIndex(int32 Index) {
return this->IsValid() ? Proxy.IsValidIndex(Index) : true;
}
| 27.046296 | 109 | 0.747004 | mjukel |
ffeb91d8f68140d4b114a02de42c1f35cdcbe3da | 342 | cpp | C++ | src/Elba/Framework/Module.cpp | nicholasammann/kotor-builder | ab0e042c09974a024a9884c6f9e34cf85ad63eeb | [
"MIT"
] | 1 | 2018-10-01T19:34:57.000Z | 2018-10-01T19:34:57.000Z | src/Elba/Framework/Module.cpp | nicholasammann/kotor-builder | ab0e042c09974a024a9884c6f9e34cf85ad63eeb | [
"MIT"
] | 9 | 2018-09-09T16:07:22.000Z | 2018-11-06T20:34:30.000Z | src/Elba/Framework/Module.cpp | nicholasammann/kotor-builder | ab0e042c09974a024a9884c6f9e34cf85ad63eeb | [
"MIT"
] | null | null | null | /**
* \file Module.cpp
* \author Nicholas Ammann
* \date 2/24/2018
* \brief Member function definitions for Module.
*/
#include "Elba/Framework/Module.hpp"
#include "Elba/Engine.hpp"
namespace Elba
{
Module::Module(Engine* engine)
: mEngine(engine)
{
}
Engine* Module::GetEngine() const
{
return mEngine;
}
} // End of Elba namespace
| 14.25 | 48 | 0.69883 | nicholasammann |
ffec787f0a1d49c22e8916aa92fe2f5ccf4d5121 | 2,152 | cc | C++ | example/provider_demo.cc | yvanwang/workflow-polaris | 06f296fcaa1a55941b2dde07952daca2186c6396 | [
"Apache-2.0"
] | null | null | null | example/provider_demo.cc | yvanwang/workflow-polaris | 06f296fcaa1a55941b2dde07952daca2186c6396 | [
"Apache-2.0"
] | null | null | null | example/provider_demo.cc | yvanwang/workflow-polaris | 06f296fcaa1a55941b2dde07952daca2186c6396 | [
"Apache-2.0"
] | null | null | null | #include <signal.h>
#include <unistd.h>
#include <string>
#include "PolarisManager.h"
#include "workflow/WFFacilities.h"
#include "workflow/WFHttpServer.h"
using namespace polaris;
static WFFacilities::WaitGroup register_wait_group(1);
static WFFacilities::WaitGroup deregister_wait_group(1);
void sig_handler(int signo)
{
register_wait_group.done();
deregister_wait_group.done();
}
int main(int argc, char *argv[])
{
if (argc != 6) {
fprintf(stderr, "USAGE:\n\t%s <polaris cluster> "
"<namespace> <service_name> <localhost> <port>\n\n", argv[0]);
exit(1);
}
signal(SIGINT, sig_handler);
std::string polaris_url = argv[1];
std::string service_namespace = argv[2];
std::string service_name = argv[3];
std::string host = argv[4];
std::string port = argv[5];
if (strncasecmp(argv[1], "http://", 7) != 0 &&
strncasecmp(argv[1], "https://", 8) != 0) {
polaris_url = "http://" + polaris_url;
}
WFHttpServer server([port](WFHttpTask *task) {
task->get_resp()->append_output_body(
"Response from instance 127.0.0.1:" + port);
});
if (server.start(atoi(port.c_str())) != 0) {
fprintf(stderr, "start server error\n");
return 0;
}
PolarisManager mgr(polaris_url);
PolarisInstance instance;
instance.set_host(host);
instance.set_port(atoi(port.c_str()));
std::map<std::string, std::string> meta = {{"key1", "value1"}};
instance.set_metadata(meta);
instance.set_region("south-china");
instance.set_zone("shenzhen");
int ret = mgr.register_service(service_namespace, service_name,
std::move(instance));
fprintf(stderr, "Register %s %s %s %s ret=%d.\n",
service_namespace.c_str(), service_name.c_str(),
host.c_str(), port.c_str(), ret);
fprintf(stderr, "Success. Press Ctrl-C to exit.\n");
register_wait_group.wait();
if (ret == 0) {
bool deregister_ret = mgr.deregister_service(service_namespace,
service_name,
std::move(instance));
fprintf(stderr, "Deregister %s %s %s %s ret=%d.\n",
service_namespace.c_str(), service_name.c_str(),
host.c_str(), port.c_str(), deregister_ret);
deregister_wait_group.wait();
}
server.stop();
return 0;
}
| 26.243902 | 66 | 0.677509 | yvanwang |
ffef2641ed1653fa4b7ff0f624ae14d9d4961d90 | 3,220 | cpp | C++ | src/app/ChunkedWriteCallback.cpp | jcps07/connectedhomeip | 8ce48a73258899a9cfd61bec7a7f085b02eeeffd | [
"Apache-2.0"
] | 4 | 2020-09-11T04:32:44.000Z | 2022-03-11T09:06:07.000Z | src/app/ChunkedWriteCallback.cpp | jcps07/connectedhomeip | 8ce48a73258899a9cfd61bec7a7f085b02eeeffd | [
"Apache-2.0"
] | null | null | null | src/app/ChunkedWriteCallback.cpp | jcps07/connectedhomeip | 8ce48a73258899a9cfd61bec7a7f085b02eeeffd | [
"Apache-2.0"
] | null | null | null | /*
*
* Copyright (c) 2022 Project CHIP Authors
* 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 <app/ChunkedWriteCallback.h>
namespace chip {
namespace app {
void ChunkedWriteCallback::OnResponse(const WriteClient * apWriteClient, const ConcreteDataAttributePath & aPath, StatusIB aStatus)
{
// We may send a chunked list. To make the behavior consistent whether a list is being chunked or not,
// we merge the write responses for a chunked list here and provide our consumer with a single status response.
if (mLastAttributePath.HasValue())
{
// This is not the first write response.
if (IsAppendingToLastItem(aPath))
{
// This is a response on the same path as what we already have stored. Report the first
// failure status we encountered, and ignore subsequent ones.
if (mAttributeStatus.IsSuccess())
{
mAttributeStatus = aStatus;
}
return;
}
// This is a response to another attribute write. Report the final result of last attribute write.
callback->OnResponse(apWriteClient, mLastAttributePath.Value(), mAttributeStatus);
}
// This is the first report for a new attribute. We assume it will never be a list item operation.
if (aPath.IsListItemOperation())
{
aStatus = StatusIB(CHIP_ERROR_INCORRECT_STATE);
}
mLastAttributePath.SetValue(aPath);
mAttributeStatus = aStatus;
// For the last status in the response, we will call the application callback in OnDone()
}
void ChunkedWriteCallback::OnError(const WriteClient * apWriteClient, CHIP_ERROR aError)
{
callback->OnError(apWriteClient, aError);
}
void ChunkedWriteCallback::OnDone(WriteClient * apWriteClient)
{
if (mLastAttributePath.HasValue())
{
// We have a cached status that has yet to be reported to the application so report it now.
// If we failed to receive the response, or we received a malformed response, OnResponse won't be called,
// mLastAttributePath will be Missing() in this case.
callback->OnResponse(apWriteClient, mLastAttributePath.Value(), mAttributeStatus);
}
callback->OnDone(apWriteClient);
}
bool ChunkedWriteCallback::IsAppendingToLastItem(const ConcreteDataAttributePath & aPath)
{
if (!aPath.IsListItemOperation())
{
return false;
}
if (!mLastAttributePath.HasValue() || !(mLastAttributePath.Value() == aPath))
{
return false;
}
return aPath.mListOp == ConcreteDataAttributePath::ListOperation::AppendItem;
}
} // namespace app
} // namespace chip
| 35.777778 | 131 | 0.692547 | jcps07 |
ffefd8a66300792ef85f319b274397da3b2bb2a2 | 6,773 | hpp | C++ | include/jsoncons/tag_type.hpp | watkinsr/jsoncons | c7ab614fe86670a423941b11704a02ad71d745a1 | [
"BSL-1.0"
] | 507 | 2015-01-05T18:50:55.000Z | 2022-03-30T16:50:10.000Z | include/jsoncons/tag_type.hpp | watkinsr/jsoncons | c7ab614fe86670a423941b11704a02ad71d745a1 | [
"BSL-1.0"
] | 272 | 2015-01-20T13:09:19.000Z | 2022-03-28T18:00:37.000Z | include/jsoncons/tag_type.hpp | watkinsr/jsoncons | c7ab614fe86670a423941b11704a02ad71d745a1 | [
"BSL-1.0"
] | 140 | 2015-01-14T01:11:37.000Z | 2022-03-29T08:35:35.000Z | // Copyright 2019 Daniel Parker
// Distributed under the Boost license, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See https://github.com/danielaparker/jsoncons for latest version
#ifndef JSONCONS_TAG_TYPE_HPP
#define JSONCONS_TAG_TYPE_HPP
#include <ostream>
#include <jsoncons/config/jsoncons_config.hpp>
namespace jsoncons {
struct null_type
{
explicit null_type() = default;
};
struct temp_allocator_arg_t
{
explicit temp_allocator_arg_t() = default;
};
constexpr temp_allocator_arg_t temp_allocator_arg{};
struct result_allocator_arg_t
{
explicit result_allocator_arg_t() = default;
};
constexpr result_allocator_arg_t result_allocator_arg{};
struct half_arg_t
{
explicit half_arg_t() = default;
};
constexpr half_arg_t half_arg{};
struct json_array_arg_t
{
explicit json_array_arg_t() = default;
};
constexpr json_array_arg_t json_array_arg{};
struct json_object_arg_t
{
explicit json_object_arg_t() = default;
};
constexpr json_object_arg_t json_object_arg{};
struct byte_string_arg_t
{
explicit byte_string_arg_t() = default;
};
constexpr byte_string_arg_t byte_string_arg{};
struct json_const_pointer_arg_t
{
explicit json_const_pointer_arg_t() = default;
};
constexpr json_const_pointer_arg_t json_const_pointer_arg{};
enum class semantic_tag : uint8_t
{
none = 0,
undefined = 0x01,
datetime = 0x02,
epoch_second = 0x03,
epoch_milli = 0x04,
epoch_nano = 0x05,
bigint = 0x06,
bigdec = 0x07,
bigfloat = 0x08,
float128 = 0x09,
base16 = 0x1a,
base64 = 0x1b,
base64url = 0x1c,
uri = 0x0d,
clamped = 0x0e,
multi_dim_row_major = 0x0f,
multi_dim_column_major = 0x10,
ext = 0x11,
id = 0x12,
regex = 0x13,
code = 0x14
#if !defined(JSONCONS_NO_DEPRECATED)
, big_integer = bigint
, big_decimal = bigdec
, big_float = bigfloat
, date_time = datetime
, timestamp = epoch_second
#endif
};
template <class CharT>
std::basic_ostream<CharT>& operator<<(std::basic_ostream<CharT>& os, semantic_tag tag)
{
static constexpr const CharT* na_name = JSONCONS_CSTRING_CONSTANT(CharT, "n/a");
static constexpr const CharT* undefined_name = JSONCONS_CSTRING_CONSTANT(CharT, "undefined");
static constexpr const CharT* datetime_name = JSONCONS_CSTRING_CONSTANT(CharT, "datetime");
static constexpr const CharT* epoch_second_name = JSONCONS_CSTRING_CONSTANT(CharT, "epoch-second");
static constexpr const CharT* epoch_milli_name = JSONCONS_CSTRING_CONSTANT(CharT, "epoch-milli");
static constexpr const CharT* epoch_nano_name = JSONCONS_CSTRING_CONSTANT(CharT, "epoch-nano");
static constexpr const CharT* bigint_name = JSONCONS_CSTRING_CONSTANT(CharT, "bigint");
static constexpr const CharT* bigdec_name = JSONCONS_CSTRING_CONSTANT(CharT, "bigdec");
static constexpr const CharT* bigfloat_name = JSONCONS_CSTRING_CONSTANT(CharT, "bigfloat");
static constexpr const CharT* base16_name = JSONCONS_CSTRING_CONSTANT(CharT, "base16");
static constexpr const CharT* base64_name = JSONCONS_CSTRING_CONSTANT(CharT, "base64");
static constexpr const CharT* base64url_name = JSONCONS_CSTRING_CONSTANT(CharT, "base64url");
static constexpr const CharT* uri_name = JSONCONS_CSTRING_CONSTANT(CharT, "uri");
static constexpr const CharT* clamped_name = JSONCONS_CSTRING_CONSTANT(CharT, "clamped");
static constexpr const CharT* multi_dim_row_major_name = JSONCONS_CSTRING_CONSTANT(CharT, "multi-dim-row-major");
static constexpr const CharT* multi_dim_column_major_name = JSONCONS_CSTRING_CONSTANT(CharT, "multi-dim-column-major");
static constexpr const CharT* ext_name = JSONCONS_CSTRING_CONSTANT(CharT, "ext");
static constexpr const CharT* id_name = JSONCONS_CSTRING_CONSTANT(CharT, "id");
static constexpr const CharT* float128_name = JSONCONS_CSTRING_CONSTANT(CharT, "float128");
static constexpr const CharT* regex_name = JSONCONS_CSTRING_CONSTANT(CharT, "regex");
static constexpr const CharT* code_name = JSONCONS_CSTRING_CONSTANT(CharT, "code");
switch (tag)
{
case semantic_tag::none:
{
os << na_name;
break;
}
case semantic_tag::undefined:
{
os << undefined_name;
break;
}
case semantic_tag::datetime:
{
os << datetime_name;
break;
}
case semantic_tag::epoch_second:
{
os << epoch_second_name;
break;
}
case semantic_tag::epoch_milli:
{
os << epoch_milli_name;
break;
}
case semantic_tag::epoch_nano:
{
os << epoch_nano_name;
break;
}
case semantic_tag::bigint:
{
os << bigint_name;
break;
}
case semantic_tag::bigdec:
{
os << bigdec_name;
break;
}
case semantic_tag::bigfloat:
{
os << bigfloat_name;
break;
}
case semantic_tag::float128:
{
os << float128_name;
break;
}
case semantic_tag::base16:
{
os << base16_name;
break;
}
case semantic_tag::base64:
{
os << base64_name;
break;
}
case semantic_tag::base64url:
{
os << base64url_name;
break;
}
case semantic_tag::uri:
{
os << uri_name;
break;
}
case semantic_tag::clamped:
{
os << clamped_name;
break;
}
case semantic_tag::multi_dim_row_major:
{
os << multi_dim_row_major_name;
break;
}
case semantic_tag::multi_dim_column_major:
{
os << multi_dim_column_major_name;
break;
}
case semantic_tag::ext:
{
os << ext_name;
break;
}
case semantic_tag::id:
{
os << id_name;
break;
}
case semantic_tag::regex:
{
os << regex_name;
break;
}
case semantic_tag::code:
{
os << code_name;
break;
}
}
return os;
}
#if !defined(JSONCONS_NO_DEPRECATED)
JSONCONS_DEPRECATED_MSG("Instead, use semantic_tag") typedef semantic_tag semantic_tag_type;
JSONCONS_DEPRECATED_MSG("Instead, use byte_string_arg_t") typedef byte_string_arg_t bstr_arg_t;
constexpr byte_string_arg_t bstr_arg{};
#endif
}
#endif
| 27.53252 | 123 | 0.635021 | watkinsr |
fff180f167ae669863138a6ae22163ed55574659 | 1,395 | cpp | C++ | codeforces/1474C.cpp | sgrade/cpptest | 84ade6ec03ea394d4a4489c7559d12b4799c0b62 | [
"MIT"
] | null | null | null | codeforces/1474C.cpp | sgrade/cpptest | 84ade6ec03ea394d4a4489c7559d12b4799c0b62 | [
"MIT"
] | null | null | null | codeforces/1474C.cpp | sgrade/cpptest | 84ade6ec03ea394d4a4489c7559d12b4799c0b62 | [
"MIT"
] | null | null | null | // C. Array Destruction
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
using namespace std;
vector<int> check (int n, vector<int> v, int x){
multiset<int> s(v.begin(), v.end());
vector<int> output;
for (int i = 0; i < n; ++i){
auto last_element = s.end();
--last_element;
int y = x - *last_element;
s.erase(last_element);
auto y_it = s.find(y);
if (y_it == s.end()) return {};
output.push_back(x - y);
output.push_back(y);
x = max(x - y, y);
s.erase(y_it);
}
return output;
}
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
vector<int> v(2 * n);
for (auto &el: v) cin >> el;
sort(v.begin(), v.end(), greater<int>());
bool flag = false;
// Editorial - https://codeforces.com/blog/entry/86933
for (int i = 2 * n - 1; i > 0; --i){
int x = v[0] + v[i];
vector<int> ans = check(n, v, x);
if (!ans.empty()){
flag = true;
cout << "YES\n" << x << endl;
for (int j = 0; j < n; ++j){
cout << ans[2 * j] << " " << ans[2 * j + 1] << endl;
}
break;
}
}
if (!flag) cout << "NO" << endl;
}
return 0;
}
| 21.136364 | 72 | 0.423656 | sgrade |
fff4056b5411431d941ae56a6b1649a5d7dfa9c7 | 776 | cc | C++ | code30/cpp/20190722/new.cc | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | 2 | 2020-12-09T09:55:51.000Z | 2021-01-08T11:38:22.000Z | code30/cpp/20190722/new.cc | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | null | null | null | code30/cpp/20190722/new.cc | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | null | null | null | ///
/// @file new.cc
/// @author lemon(haohb13@gmail.com)
/// @date 2019-07-22 15:59:19
///
#include <stdlib.h>
#include <string.h>
#include <iostream>
using std::cout;
using std::endl;
void test0()
{
int * pint = (int *)malloc(sizeof(int));//系统调用
*pint = 10;
int * pint2 = (int *)malloc(sizeof(int) * 10);
memset(pint2, 0, sizeof(int) * 10);
free(pint);
free(pint2);
}
//malloc/free与new/delete表达式的区别?
//1. malloc/free是库函数; new/delete是表达式
//2. malloc开辟空间的时候,没有进行初始化;
// new表达式在开辟空间的同时,还进行了初始化
void test1()
{
int * pint = new int(10);//new表达式
cout << " * pint = " << *pint << endl;
int * pint2 = new int[10];//没有进行初始化
int * pint3 = new int[10]();//有进行初始化
delete pint;//表达式
delete [] pint2;
}
int main(void)
{
test1();
return 0;
}
| 14.641509 | 48 | 0.600515 | stdbilly |
fffaeab0f9214ae1ada25cc4a6433a2a946e2476 | 664 | cpp | C++ | src/StatusPage.cpp | openMSX/wxcatapult | 388428af2b0767853f5b8a09540b1c61c64afda8 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 12 | 2015-06-29T21:58:33.000Z | 2020-11-02T10:46:08.000Z | src/StatusPage.cpp | openMSX/wxcatapult | 388428af2b0767853f5b8a09540b1c61c64afda8 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 41 | 2015-06-24T12:42:26.000Z | 2021-08-29T22:03:23.000Z | src/StatusPage.cpp | openMSX/wxcatapult | 388428af2b0767853f5b8a09540b1c61c64afda8 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 4 | 2019-02-02T16:02:17.000Z | 2022-02-15T03:05:17.000Z | #include "StatusPage.h"
#include "wxCatapultApp.h"
#include <wx/textctrl.h>
#include <wx/wxprec.h>
#include <wx/xrc/xmlres.h>
IMPLEMENT_CLASS(StatusPage, wxPanel)
BEGIN_EVENT_TABLE(StatusPage, wxPanel)
END_EVENT_TABLE()
StatusPage::StatusPage(wxWindow* parent)
{
wxXmlResource::Get()->LoadPanel(this, parent, wxT("StatusPage"));
m_outputtext = (wxTextCtrl*)FindWindowByName(wxT("OutputText"));
}
void StatusPage::Clear()
{
m_outputtext->Clear();
}
void StatusPage::Add(const wxColour& col, const wxString& str)
{
m_outputtext->SetDefaultStyle(wxTextAttr(
col, wxNullColour,
wxFont(10, wxMODERN, wxNORMAL, wxNORMAL)));
m_outputtext->AppendText(str);
}
| 22.896552 | 66 | 0.753012 | openMSX |
fffbd1d909ef2d2ceb5e31495cdefebbdbb2c697 | 982 | cpp | C++ | Matrix/Make Matrix Beautiful.cpp | pkunjam/Data-Structures-and-Algorithms | 0730bb95347cc824207b5304787b34f4de29ff86 | [
"MIT"
] | 1 | 2020-07-21T20:13:07.000Z | 2020-07-21T20:13:07.000Z | Matrix/Make Matrix Beautiful.cpp | pkunjam/Data-Structures-and-Algorithms | 0730bb95347cc824207b5304787b34f4de29ff86 | [
"MIT"
] | null | null | null | Matrix/Make Matrix Beautiful.cpp | pkunjam/Data-Structures-and-Algorithms | 0730bb95347cc824207b5304787b34f4de29ff86 | [
"MIT"
] | null | null | null | // { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
int findMinOpeartion(int matrix[][100], int n);
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int mat[n][100];
for(int i=0;i<n;i++)for(int j=0;j<n;j++)cin>>mat[i][j];
cout << findMinOpeartion(mat, n) << endl;
}
return 0;
}
// } Driver Code Ends
//Complete this function
// Function to find minimum number of operation
int findMinOpeartion(int matrix[][100], int n)
{
int sum=0,row_sum,col_sum;
int max=0;
for(int i=0;i<n;i++)
{
row_sum=0;
col_sum=0;
for(int j=0;j<n;j++)
{
sum+=matrix[i][j];
row_sum+=matrix[i][j];
col_sum+=matrix[j][i];
}
if(row_sum>max)
{
max=row_sum;
}
if(col_sum>max)
{
max=col_sum;
}
}
return (n*max)-sum;
}
| 17.854545 | 63 | 0.467413 | pkunjam |
080316fcccd0df886566843a74fe008800d32c28 | 4,875 | cpp | C++ | arduino/opencr_fw/opencr_fw_arduino/src/sketch/turtlebot3/turtlebot_waffle/turtlebot3_core/turtlebot3_motor_driver.cpp | ipa-jba/OpenCR | 09bf34f5f9ebc1253e03ac789cf820dcc46eb99d | [
"Apache-2.0"
] | null | null | null | arduino/opencr_fw/opencr_fw_arduino/src/sketch/turtlebot3/turtlebot_waffle/turtlebot3_core/turtlebot3_motor_driver.cpp | ipa-jba/OpenCR | 09bf34f5f9ebc1253e03ac789cf820dcc46eb99d | [
"Apache-2.0"
] | null | null | null | arduino/opencr_fw/opencr_fw_arduino/src/sketch/turtlebot3/turtlebot_waffle/turtlebot3_core/turtlebot3_motor_driver.cpp | ipa-jba/OpenCR | 09bf34f5f9ebc1253e03ac789cf820dcc46eb99d | [
"Apache-2.0"
] | 2 | 2018-02-19T15:35:17.000Z | 2020-01-22T15:56:35.000Z | /*******************************************************************************
* Copyright 2016 ROBOTIS 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.
*******************************************************************************/
/* Authors: Yoonseok Pyo, Leon Jung, Darby Lim, HanCheol Cho */
#include "turtlebot3_motor_driver.h"
Turtlebot3MotorDriver::Turtlebot3MotorDriver()
: baudrate_(BAUDRATE),
protocol_version_(PROTOCOL_VERSION),
left_wheel_id_(DXL_LEFT_ID),
right_wheel_id_(DXL_RIGHT_ID)
{
}
Turtlebot3MotorDriver::~Turtlebot3MotorDriver()
{
closeDynamixel();
}
bool Turtlebot3MotorDriver::init(void)
{
portHandler_ = dynamixel::PortHandler::getPortHandler(DEVICENAME);
packetHandler_ = dynamixel::PacketHandler::getPacketHandler(PROTOCOL_VERSION);
// Open port
if (portHandler_->openPort())
{
// sprintf(log_msg, "Port is Opened");
// nh.loginfo(log_msg);
}
else
{
//return false;
}
// Set port baudrate
if (portHandler_->setBaudRate(baudrate_))
{
// sprintf(log_msg, "Baudrate is set");
// nh.loginfo(log_msg);
}
else
{
//return false;
}
// Enable Dynamixel Torque
setTorque(left_wheel_id_, true);
setTorque(right_wheel_id_, true);
groupSyncWriteVelocity_ = new dynamixel::GroupSyncWrite(portHandler_, packetHandler_, ADDR_X_GOAL_VELOCITY, LEN_X_GOAL_VELOCITY);
groupSyncReadEncoder_ = new dynamixel::GroupSyncRead(portHandler_, packetHandler_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
return true;
}
bool Turtlebot3MotorDriver::setTorque(uint8_t id, bool onoff)
{
uint8_t dxl_error = 0;
int dxl_comm_result = COMM_TX_FAIL;
dxl_comm_result = packetHandler_->write1ByteTxRx(portHandler_, id, ADDR_X_TORQUE_ENABLE, onoff, &dxl_error);
if(dxl_comm_result != COMM_SUCCESS)
packetHandler_->printTxRxResult(dxl_comm_result);
else if(dxl_error != 0)
packetHandler_->printRxPacketError(dxl_error);
}
void Turtlebot3MotorDriver::closeDynamixel(void)
{
// Disable Dynamixel Torque
setTorque(left_wheel_id_, false);
setTorque(right_wheel_id_, false);
// Close port
portHandler_->closePort();
}
bool Turtlebot3MotorDriver::readEncoder(int32_t &left_value, int32_t &right_value)
{
int dxl_comm_result = COMM_TX_FAIL; // Communication result
bool dxl_addparam_result = false; // addParam result
bool dxl_getdata_result = false; // GetParam result
// Set parameter
dxl_addparam_result = groupSyncReadEncoder_->addParam(left_wheel_id_);
if (dxl_addparam_result != true)
{
return false;
}
dxl_addparam_result = groupSyncReadEncoder_->addParam(right_wheel_id_);
if (dxl_addparam_result != true)
{
return false;
}
// Syncread present position
dxl_comm_result = groupSyncReadEncoder_->txRxPacket();
if (dxl_comm_result != COMM_SUCCESS) packetHandler_->printTxRxResult(dxl_comm_result);
// Check if groupSyncRead data of Dynamixels are available
dxl_getdata_result = groupSyncReadEncoder_->isAvailable(left_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
if (dxl_getdata_result != true)
{
return false;
}
dxl_getdata_result = groupSyncReadEncoder_->isAvailable(right_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
if (dxl_getdata_result != true)
{
return false;
}
// Get data
left_value = groupSyncReadEncoder_->getData(left_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
right_value = groupSyncReadEncoder_->getData(right_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
groupSyncReadEncoder_->clearParam();
return true;
}
bool Turtlebot3MotorDriver::speedControl(int64_t left_wheel_value, int64_t right_wheel_value)
{
bool dxl_addparam_result_;
int8_t dxl_comm_result_;
dxl_addparam_result_ = groupSyncWriteVelocity_->addParam(left_wheel_id_, (uint8_t*)&left_wheel_value);
if (dxl_addparam_result_ != true)
{
return false;
}
dxl_addparam_result_ = groupSyncWriteVelocity_->addParam(right_wheel_id_, (uint8_t*)&right_wheel_value);
if (dxl_addparam_result_ != true)
{
return false;
}
dxl_comm_result_ = groupSyncWriteVelocity_->txPacket();
if (dxl_comm_result_ != COMM_SUCCESS)
{
packetHandler_->printTxRxResult(dxl_comm_result_);
return false;
}
groupSyncWriteVelocity_->clearParam();
return true;
}
| 29.36747 | 136 | 0.728205 | ipa-jba |
0803660a7850e933b19b482782cefcf96d0ecc30 | 4,780 | cpp | C++ | src/server_sctp_helper_one_to_many.cpp | z4pu/tcp_to_tls | b5e4923d2da2a220d14f08c5f6dd5b726ac9d962 | [
"MIT"
] | 2 | 2020-05-17T17:16:48.000Z | 2020-08-02T13:03:00.000Z | src/server_sctp_helper_one_to_many.cpp | z4pu/tcp_to_tls | b5e4923d2da2a220d14f08c5f6dd5b726ac9d962 | [
"MIT"
] | 1 | 2019-12-25T02:41:30.000Z | 2021-10-13T11:18:26.000Z | src/server_sctp_helper_one_to_many.cpp | z4pu/tcp_to_tls | b5e4923d2da2a220d14f08c5f6dd5b726ac9d962 | [
"MIT"
] | null | null | null | #include "server_sctp_helper_one_to_many.hpp"
#include "common.hpp"
#include "common_sctp.hpp"
extern "C" {
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/sctp.h>
#include <sys/un.h>
#include <arpa/inet.h>
}
extern "C" {
#include <unistd.h>
}
#include <iostream>
#include <string>
/**
* @brief Creates an SCTP one-to-many socket and listens on specified port to wait for clients
* @param [in] port port to listen on
* @param [in] backlog maximum number of incoming connections to handle
* @return -1 if error, file descriptor of socket if successful
*/
int SCTPListenOneToMany(const int& port, const int& backlog)
{
int sd, reuseaddr, status, r;
struct addrinfo hints, * ai, * aptr;
char port_str[6] = {0};
//struct timeval tv;
//tv.tv_sec = TIMEOUT_IN_SECS;
//tv.tv_usec = 0;
if ((port > 65535) || (port < 1)) {
std::cerr << "SCTPListenOneToMany(): Invalid port number\n";
return -1;
}
if (!port || !backlog) {
std::cerr << "SCTPListenOneToMany(): Null params\n";
return -1;
}
sprintf(port_str, "%d", port);
/* Initialise Hints - Address struct*/
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_PASSIVE ; /* passive open */
hints.ai_family = AF_UNSPEC ; /* IPv4 or IPv6 */
hints.ai_socktype = SOCK_SEQPACKET ; /* TCP - Socket */
hints.ai_protocol = IPPROTO_SCTP;
/* fill Address struct for passive socket */
if ((status = getaddrinfo(nullptr, port_str, &hints, &ai)) == 0)
{
for (aptr = ai; aptr != NULL; aptr = aptr->ai_next )
{
if (( sd = socket(aptr->ai_family,
aptr->ai_socktype, aptr->ai_protocol)) < 0 )
continue; /* If error, go to next Address struct */
/* To avoid "address already in use" Error */
reuseaddr = 1;
r = setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(int));
if (r == -1) {
close(sd);
perror("SCTPListenOneToMany(): setsockopt(SO_REUSEADDR)");
continue;
}
r = enable_notifications(sd);
if (r != 0) {
close(sd);
perror("SCTPListenOneToMany(): enable_notifications()");
continue;
}
// Add timeout value
//setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
if (bind (sd, aptr->ai_addr, aptr->ai_addrlen ) == -1 ) {
close(sd);
perror("SCTPListenOneToMany(): bind");
continue;
}
// /* Change passive socket to active socket */
if (listen(sd, backlog) >= 0 )
/* End loop if successful */
break;
/* If error, close socket ... */
close(sd);
}
freeaddrinfo(ai);
/*
* If list is processed unsucessfull, aptr = NULL
* and errno shows the error in the last call to von
* socket () , bind () or listen ()
*/
if (aptr == NULL){
std::cerr << "SCTPListenOneToMany(): ";
fprintf(stderr, "Can’t listen on port %s :%s\n",
port_str, strerror(errno));
return(-1);
}
}
else {
std::cerr << "SCTPListenOneToMany(): ";
fprintf(stderr, "getaddrinfo () failed : %s \n", gai_strerror(status));
return ( -1 );
}
return (sd);
}
void ProcessSCTPClientWithServerSocket (const int& server_sd)
{
socklen_t peer_addr_len;
struct sockaddr_storage peer_addr;
int r, s, c = 0;
char buff[MAX_STRING_LENGTH+1] = {};
char host[NI_MAXHOST], service[NI_MAXSERV];
peer_addr_len = sizeof(struct sockaddr_storage);
r = RecvSCTPOneToManyMessage(
server_sd, (struct sockaddr_in *) &peer_addr, buff);
if (r == -1) {
perror("ProcessSCTPClientWithServerSocket(): recvfrom()");
return;
}
std::cout << "--> ProcessSCTPClientWithServerSocket(): incoming string "
<< buff << std::endl;
s = getnameinfo((struct sockaddr *) &peer_addr,
peer_addr_len, host, NI_MAXHOST,
service, NI_MAXSERV, NI_NUMERICSERV);
if ( s == 0) {
printf("ProcessSCTPClientWithServerSocket(): Received %ld bytes from %s:%s\n", (long)r, host, service);
} else {
fprintf(stderr, "ProcessSCTPClientWithServerSocket(): getnameinfo: %s\n", gai_strerror(s));
return;
}
ReverseString(reinterpret_cast<char*>(buff));
c = SendSCTPOneToManyMessage(server_sd, (struct sockaddr_in *) &peer_addr,
buff);
if (c != r) {
perror("ProcessSCTPClientWithServerSocket(): sendto(): Error sending response");
}
std::cout << "--> ProcessSCTPClientWithServerSocket(): sent reversed string "
<< buff << std::endl;
return;
}
| 28.622754 | 111 | 0.590795 | z4pu |
080beaccce222e476f7c25b3eb8598f0c292e76f | 396 | cpp | C++ | inverted_pattern.cpp | VivekWesley/CPP_BASICS | 536d4e3b6c94e13ab5263f38c3a2e80f077b2d29 | [
"MIT"
] | null | null | null | inverted_pattern.cpp | VivekWesley/CPP_BASICS | 536d4e3b6c94e13ab5263f38c3a2e80f077b2d29 | [
"MIT"
] | null | null | null | inverted_pattern.cpp | VivekWesley/CPP_BASICS | 536d4e3b6c94e13ab5263f38c3a2e80f077b2d29 | [
"MIT"
] | 1 | 2022-01-17T09:27:19.000Z | 2022-01-17T09:27:19.000Z | // inverted pattern
// SAMPLE OUTPUT:
//enter a number
// 5
// 1 2 3 4 5
// 1 2 3 4
// 1 2 3
// 1 2
// 1
#include <Iostream>
using namespace std;
int main()
{
int n;
cout << "enter a number" << endl;
cin >> n;
for (int i = n; i >= 1; i--)
{
for (int j = 1; j <= i; j++)
{
cout << j << " ";
}
cout << endl;
}
return 0;
} | 12.774194 | 37 | 0.414141 | VivekWesley |
080ce021e8672bfe696250b6d49b6a293a77521d | 483 | hpp | C++ | convolution/inverse-fast-walsh-hadamard-transform.hpp | dutinmeow/library | 3501f36656795f432ac816941ec7e9548dc3d6ef | [
"MIT"
] | 7 | 2022-01-23T07:58:19.000Z | 2022-02-25T04:11:12.000Z | convolution/inverse-fast-walsh-hadamard-transform.hpp | dutinmeow/library | 3501f36656795f432ac816941ec7e9548dc3d6ef | [
"MIT"
] | null | null | null | convolution/inverse-fast-walsh-hadamard-transform.hpp | dutinmeow/library | 3501f36656795f432ac816941ec7e9548dc3d6ef | [
"MIT"
] | null | null | null | #include "convolution/fast-walsh-hadamard-transform.hpp"
#pragma region inverse_fast_walsh_hadamard_transform
namespace conv {
template<typename T>
void inverse_fast_walsh_hadamard_transform(vector<T> &a) {
fast_walsh_hadamard_transform<T>(a);
if constexpr (is_integral<T>::value) {
int n = a.size();
for (auto &x : a)
x /= n;
} else {
T t = T(1) / T(a.size());
for (auto &x : a)
x *= t;
}
}
}
#pragma endregion inverse_fast_walsh_hadamard_transform | 23 | 59 | 0.6853 | dutinmeow |
0812b74c7d6108587a20dcd174578936a17cefca | 2,039 | hh | C++ | include/attribute_info.hh | AnthonyCalandra/bytecode-scanner | e2638a7063447bc947f0bc11d841d536735407ec | [
"MIT"
] | 8 | 2019-07-21T20:15:46.000Z | 2021-06-15T12:28:12.000Z | include/attribute_info.hh | AnthonyCalandra/bytecode-scanner | e2638a7063447bc947f0bc11d841d536735407ec | [
"MIT"
] | null | null | null | include/attribute_info.hh | AnthonyCalandra/bytecode-scanner | e2638a7063447bc947f0bc11d841d536735407ec | [
"MIT"
] | 1 | 2020-09-24T08:28:04.000Z | 2020-09-24T08:28:04.000Z | /**
* Copyright 2019 Anthony Calandra
*
* 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.
*/
#pragma once
#include <fstream>
#include <memory>
#include <vector>
#include "constant_pool.hh"
enum class attribute_info_type : uint8_t
{
constant_value, code, stack_map_table, exceptions, inner_classes, enclosing_method, synthetic,
signature, source_file, source_debug_extension, line_number_table, local_variable_table,
local_variable_type_table, deprecated, runtime_visible_annotations, runtime_invisible_annotations,
runtime_visible_parameter_annotations, runtime_invisible_parameter_annotations, annotation_default,
bootstrap_methods
};
class attribute_info
{
public:
virtual attribute_info_type get_type() const = 0;
virtual ~attribute_info() = default;
};
using entry_attributes = std::vector<std::unique_ptr<attribute_info>>;
entry_attributes parse_attributes(std::ifstream& file, const constant_pool& cp);
void skip_element_value_field(std::ifstream& file);
void skip_annotations(std::ifstream& file);
| 41.612245 | 103 | 0.793526 | AnthonyCalandra |
08166686aa59551d0148d54d79afc652387de7c3 | 5,351 | cpp | C++ | test/streamutils_test.cpp | Skemba/alt-integration-cpp | d9871d56746aabee2f7678af7004cfbc1e17213b | [
"MIT"
] | null | null | null | test/streamutils_test.cpp | Skemba/alt-integration-cpp | d9871d56746aabee2f7678af7004cfbc1e17213b | [
"MIT"
] | null | null | null | test/streamutils_test.cpp | Skemba/alt-integration-cpp | d9871d56746aabee2f7678af7004cfbc1e17213b | [
"MIT"
] | null | null | null | // Copyright (c) 2019-2020 Xenios SEZC
// https://www.veriblock.org
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
#include <gtest/gtest.h>
#include <vector>
#include <veriblock/read_stream.hpp>
#include <veriblock/write_stream.hpp>
TEST(ReadStream, Read) {
std::vector<uint8_t> buf{0, 1, 2, 3};
altintegration::ReadStream stream(buf);
altintegration::ValidationState state;
uint8_t byte = 0;
EXPECT_EQ(stream.assertRead(1), std::vector<uint8_t>{0});
EXPECT_EQ(stream.assertRead(1), std::vector<uint8_t>{1});
EXPECT_EQ(stream.assertRead(1), std::vector<uint8_t>{2});
EXPECT_EQ(stream.assertRead(1), std::vector<uint8_t>{3});
ASSERT_FALSE(stream.readBE<uint8_t>(byte, state));
ASSERT_EQ(state.GetPath(), "readbe-underflow");
state.reset();
stream.reset();
EXPECT_EQ(stream.assertRead(2), (std::vector<uint8_t>{0, 1}));
EXPECT_EQ(stream.assertRead(2), (std::vector<uint8_t>{2, 3}));
stream.reset();
EXPECT_EQ(stream.assertRead(4), (std::vector<uint8_t>{0, 1, 2, 3}));
stream.reset();
std::vector<uint8_t> out(5, 0);
ASSERT_FALSE(stream.read(5, out.data(), state));
ASSERT_EQ(state.GetPath(), "read-underflow");
state.reset();
stream.reset();
auto sl1 = stream.assertReadSlice(2);
EXPECT_EQ(sl1.data(), buf.data());
EXPECT_EQ(sl1.size(), 2);
EXPECT_EQ(sl1[0], 0);
EXPECT_EQ(sl1[1], 1);
auto sl2 = stream.assertReadSlice(2);
EXPECT_EQ(sl2.data(), buf.data() + 2);
EXPECT_EQ(sl2.size(), 2);
EXPECT_EQ(sl2[0], 2);
EXPECT_EQ(sl2[1], 3);
}
TEST(ReadStream, BE) {
std::vector<uint8_t> buf{0x06, 0xfb, 0x0a, 0xfd};
altintegration::ReadStream stream(buf);
EXPECT_EQ(stream.assertReadBE<int8_t>(), 0x06);
EXPECT_EQ(stream.assertReadBE<uint8_t>(), 0xfb);
stream.reset();
EXPECT_EQ(stream.assertReadBE<int16_t>(), 1787);
EXPECT_EQ(stream.assertReadBE<uint16_t>(), 2813);
stream.reset();
EXPECT_EQ(stream.assertReadBE<int32_t>(), 117115645);
stream.reset();
EXPECT_EQ(stream.assertReadBE<uint32_t>(), 117115645);
}
TEST(ReadStream, LE) {
std::vector<uint8_t> buf{0x06, 0xfb, 0x0a, 0xfd};
altintegration::ReadStream stream(buf);
EXPECT_EQ(stream.assertReadLE<int8_t>(), 0x6);
EXPECT_EQ(stream.assertReadLE<uint8_t>(), 0xfb);
stream.reset();
EXPECT_EQ(stream.assertReadLE<int16_t>(), -1274);
EXPECT_EQ(stream.assertReadLE<uint16_t>(), 64778);
stream.reset();
EXPECT_EQ(stream.assertReadLE<int32_t>(), -49612026);
stream.reset();
EXPECT_EQ(stream.assertReadLE<uint32_t>(), 4245355270);
}
TEST(ReadStream, Negative) {
std::vector<uint8_t> buf{0xff, 0xff, 0xff, 0xff};
altintegration::ReadStream stream(buf);
EXPECT_EQ(stream.assertReadBE<uint32_t>(), 4294967295ull);
EXPECT_EQ(stream.remaining(), 0u);
stream.reset();
EXPECT_EQ(stream.assertReadBE<int32_t>(), -1);
EXPECT_EQ(stream.remaining(), 0u);
}
TEST(WriteStream, Write) {
altintegration::WriteStream stream;
stream.write(std::vector<uint8_t>{1});
stream.write(std::vector<uint8_t>{2, 3});
stream.write(std::vector<uint8_t>{4, 5, 6});
EXPECT_EQ(stream.data(), (std::vector<uint8_t>{1, 2, 3, 4, 5, 6}));
stream.write(std::string{"a"});
EXPECT_EQ(stream.data(), (std::vector<uint8_t>{1, 2, 3, 4, 5, 6, 'a'}));
std::vector<uint8_t> v{9, 8, 7};
stream.write(v);
EXPECT_EQ(stream.data(),
(std::vector<uint8_t>{1, 2, 3, 4, 5, 6, 'a', 9, 8, 7}));
}
TEST(WriteStream, LE) {
altintegration::WriteStream stream;
stream.writeLE<uint8_t>(1);
stream.writeLE<int8_t>(-1);
stream.writeLE<uint16_t>(2);
stream.writeLE<int16_t>(-2);
stream.writeLE<uint32_t>(3);
stream.writeLE<int32_t>(-3);
stream.writeLE<uint64_t>(4);
stream.writeLE<int64_t>(-4);
EXPECT_EQ(stream.data().size(),
sizeof(int8_t) * 2 + sizeof(int16_t) * 2 + sizeof(int32_t) * 2 +
sizeof(int64_t) * 2);
EXPECT_EQ(stream.data(),
(std::vector<uint8_t>{
1, 0xff, 2, 0, 0xfe, 0xff, 3, 0, 0, 0,
0xfd, 0xff, 0xff, 0xff, 4, 0, 0, 0, 0, 0,
0, 0, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}));
}
TEST(WriteStream, BE) {
altintegration::WriteStream stream;
stream.writeBE<uint8_t>(1);
stream.writeBE<int8_t>(-1);
stream.writeBE<uint16_t>(2);
stream.writeBE<int16_t>(-2);
stream.writeBE<uint32_t>(3);
stream.writeBE<int32_t>(-3);
stream.writeBE<uint64_t>(4);
stream.writeBE<int64_t>(-4);
EXPECT_EQ(stream.data().size(),
sizeof(int8_t) * 2 + sizeof(int16_t) * 2 + sizeof(int32_t) * 2 +
sizeof(int64_t) * 2);
EXPECT_EQ(stream.data(),
(std::vector<uint8_t>{
1, 0xff, 0, 2, 0xff, 0xfe, 0, 0, 0, 3,
0xff, 0xff, 0xff, 0xfd, 0, 0, 0, 0, 0, 0,
0, 4, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc}));
}
TEST(Streams, BE_Sized) {
altintegration::WriteStream stream;
// nonce is 5 bytes
uint64_t nonce = 0x0000001122334455;
stream.writeBE<uint64_t>(nonce, 5);
ASSERT_EQ(stream.data(),
(std::vector<uint8_t>{0x11, 0x22, 0x33, 0x44, 0x55}));
altintegration::ReadStream rs(stream.data());
uint64_t actual = rs.assertReadBE<uint64_t>(5);
ASSERT_EQ(nonce, actual) << std::hex << actual;
} | 32.041916 | 78 | 0.646608 | Skemba |
081c38183c60b4e042c8bb56d2c281f49d96fc37 | 1,282 | cpp | C++ | source/vector/Sort/quickSortRand.cpp | Tridu33/myclionarch | d4e41b3465a62a83cbf6c7119401c05009f4b636 | [
"MIT"
] | null | null | null | source/vector/Sort/quickSortRand.cpp | Tridu33/myclionarch | d4e41b3465a62a83cbf6c7119401c05009f4b636 | [
"MIT"
] | null | null | null | source/vector/Sort/quickSortRand.cpp | Tridu33/myclionarch | d4e41b3465a62a83cbf6c7119401c05009f4b636 | [
"MIT"
] | null | null | null | //
// Created by tridu33 on 9/27/2021.
//
#include "quickSortRand.h"
#include <stdlib.h> /* srand, rand */
using namespace std;
#include <bits/stdc++.h>
class Solution {
public:
int partition(vector<int> & nums,int l,int r){
int pivot = nums[r];
int s = l,e = r-1;
while(s<=e){
while(s<=e && nums[s] <= pivot) s++;
while(s<=e && nums[e] >= pivot) e--;
if(s <= e) swap(nums[s],nums[e]);
}
swap(nums[s],nums[r]);
return s;
}
int Random_partition(vector<int> & nums,int l,int r){
srand((unsigned) time(NULL));
int i = rand()%nums.size();
swap(nums[i],nums[r]);
return partition(nums,l,r);
}
void quicksort(vector<int> & nums,int s , int e){
if(s >= e) return;
int pivotindex = Random_partition(nums,s,e);
quicksort(nums,s,pivotindex-1);
quicksort(nums,pivotindex+1,e);
}
vector<int> sortArray(vector<int>& nums) {
int n = nums.size();
quicksort(nums,0,n-1);//快排
return nums;
}
};
int main(){
vector<int> nums = {1,4,3,5,7,9,0,56};
Solution sol;
vector<int> vec = sol.sortArray(nums);
for(auto x: vec){
cout << x << ' ' << endl;
}
return 0;
} | 26.163265 | 57 | 0.517941 | Tridu33 |
081dd4e6fd71f785dc42d66e92cc7772d4578452 | 5,067 | cpp | C++ | Alfred/src/ApiHttp.cpp | rhymu8354/Alfred | 225c16ed578ebc8221021a8a164c52d17f89fdf7 | [
"MIT"
] | null | null | null | Alfred/src/ApiHttp.cpp | rhymu8354/Alfred | 225c16ed578ebc8221021a8a164c52d17f89fdf7 | [
"MIT"
] | null | null | null | Alfred/src/ApiHttp.cpp | rhymu8354/Alfred | 225c16ed578ebc8221021a8a164c52d17f89fdf7 | [
"MIT"
] | null | null | null | /**
* @file ApiHttp.cpp
*
* This module contains the implementation of functions which implement an
* Application Programming Interface (API) to the service via Hypertext
* Transfer Protocol (HTTP).
*/
#include "ApiHttp.hpp"
#include <functional>
#include <Json/Value.hpp>
#include <memory>
#include <unordered_set>
namespace {
using Handler = std::function<
Json::Value(
const std::shared_ptr< Store >& store,
const Http::Request& request,
Http::Response& response
)
>;
struct HandlerRegistration {
HandlerRegistration* next;
std::vector< std::string > resourceSubspacePath;
std::unordered_set< std::string > methods;
Handler handler;
};
HandlerRegistration* handlerRegistrations = nullptr;
struct AddHandlerRegistration {
AddHandlerRegistration(
HandlerRegistration* handlerRegistration,
Handler&& handler,
std::unordered_set< std::string >&& methods,
std::vector< std::string >&& resourceSubspacePath
) {
handlerRegistration->next = handlerRegistrations;
handlerRegistration->resourceSubspacePath = std::move(resourceSubspacePath);
handlerRegistration->methods = std::move(methods);
handlerRegistration->handler = std::move(handler);
handlerRegistrations = handlerRegistration;
}
};
#define DEFINE_HANDLER(handler) \
Json::Value handler( \
const std::shared_ptr< Store >& store, \
const Http::Request& request, \
Http::Response& response \
); \
HandlerRegistration HandlerRegistration##handler; \
const AddHandlerRegistration AddHandlerRegistration##handler(\
&HandlerRegistration##handler, \
handler, \
HANDLER_METHODS, \
HANDLER_PATH \
); \
Json::Value handler( \
const std::shared_ptr< Store >& store, \
const Http::Request& request, \
Http::Response& response \
)
#undef HANDLER_METHODS
#undef HANDLER_PATH
#define HANDLER_METHODS {"GET", "PUT", "POST", "DELETE"}
#define HANDLER_PATH {}
DEFINE_HANDLER(Unknown){
response.statusCode = 404;
response.reasonPhrase = "Not Found";
return Json::Object({
{"message", "No such resource defined"},
});
}
#undef HANDLER_METHODS
#undef HANDLER_PATH
#define HANDLER_METHODS {"GET"}
#define HANDLER_PATH {"data"}
DEFINE_HANDLER(Test){
return store->GetData(
request.target.GetPath(),
{"public"}
);
}
#undef DEFINE_HANDLER
#undef HANDLER_METHODS
#undef HANDLER_PATH
}
namespace ApiHttp {
void RegisterResources(
const std::shared_ptr< Store >& store,
Http::Server& httpServer
) {
std::weak_ptr< Store > storeWeak(store);
for (
auto handlerRegistration = handlerRegistrations;
handlerRegistration != nullptr;
handlerRegistration = handlerRegistration->next
) {
const auto handler = handlerRegistration->handler;
const auto methods = handlerRegistration->methods;
(void)httpServer.RegisterResource(
handlerRegistration->resourceSubspacePath,
[storeWeak, handler, methods](
const Http::Request& request,
std::shared_ptr< Http::Connection > connection,
const std::string& trailer
){
Http::Response response;
const auto store = storeWeak.lock();
if (store == nullptr) {
response.statusCode = 503;
response.reasonPhrase = "Service Unavailable";
response.body = Json::Object({
{"message", "The service is shutting down. Please try again later!"},
}).ToEncoding();
} else if (methods.find(request.method) == methods.end()) {
response.statusCode = 405;
response.reasonPhrase = "Method Not Allowed";
} else {
response.statusCode = 200;
response.reasonPhrase = "OK";
response.body = handler(store, request, response).ToEncoding();
}
if (response.body.empty()) {
response.headers.SetHeader("Content-Length", "0");
} else {
response.headers.SetHeader("Content-Type", "application/json");
}
if (response.statusCode / 100 == 2) {
response.headers.SetHeader("Access-Control-Allow-Origin", "*");
}
return response;
}
);
}
}
}
| 33.78 | 98 | 0.548056 | rhymu8354 |
082e473f456f5e141cd6a0116c0031c4c200b167 | 20,158 | hpp | C++ | project/include/Alter/PipelineLayout.hpp | helixd2s/ZEON | b4b6394fa15e7a8ebeaa336d8bf6f45e2d096d46 | [
"MIT"
] | null | null | null | project/include/Alter/PipelineLayout.hpp | helixd2s/ZEON | b4b6394fa15e7a8ebeaa336d8bf6f45e2d096d46 | [
"MIT"
] | null | null | null | project/include/Alter/PipelineLayout.hpp | helixd2s/ZEON | b4b6394fa15e7a8ebeaa336d8bf6f45e2d096d46 | [
"MIT"
] | null | null | null | #pragma once
//
#ifdef __cplusplus
#include "./Core.hpp"
#include "./Instance.hpp"
#include "./Device.hpp"
//#include "./Resource.hpp"
//
struct DescriptorBindings {
std::vector<vk::DescriptorSetLayoutBinding> bindings = {};
std::vector<vk::DescriptorBindingFlags> bindingFlags = {};
};
//
namespace ANAMED {
//
class PipelineLayoutObj : public BaseObj {
public:
using tType = WrapShared<PipelineLayoutObj>;
using BaseObj::BaseObj;
//using BaseObj;
protected:
//
friend DeviceObj;
friend PipelineObj;
friend ResourceObj;
friend FramebufferObj;
friend SwapchainObj;
//
//std::vector<ResourceObj> bindedResources = {};
//
vk::PipelineCache cache = {};
//vk::PipelineLayout layout = {};
vk::DescriptorPool pool = {};
std::vector<vk::DescriptorSet> sets = {};
std::vector<vk::DescriptorSetLayout> layouts = {};
std::vector<vk::PushConstantRange> pushConstantRanges = {};
//
cpp21::vector_of_shared<MSS> layoutInfoMaps = {};
cpp21::vector_of_shared<DescriptorBindings> layoutBindings = {};
std::vector<uint32_t> descriptorCounts = {};
//
cpp21::bucket<vk::DescriptorImageInfo> textures = std::vector<vk::DescriptorImageInfo>{};
cpp21::bucket<vk::DescriptorImageInfo> samplers = std::vector<vk::DescriptorImageInfo>{};
cpp21::bucket<vk::DescriptorImageInfo> images = std::vector<vk::DescriptorImageInfo>{};
std::optional<vk::DescriptorBufferInfo> uniformBufferDesc = {};
std::vector<vk::DescriptorBufferInfo> cacheBufferDescs = {};
//
std::vector<vk::DescriptorPoolSize> DPC = {};
std::optional<DescriptorsCreateInfo> cInfo = DescriptorsCreateInfo{};
//
//std::shared_ptr<DeviceObj> deviceObj = {};
//std::shared_ptr<ResourceObj> uniformBuffer = {};
vk::Buffer uniformBuffer = {};
vk::Buffer cacheBuffer = {};
//
WrapShared<ResourceObj> uniformBufferObj = {};
WrapShared<ResourceSparseObj> cacheBufferObj = {};
//
std::vector<char8_t> initialData = {};
//
size_t cachePages = 16u;
size_t cachePageSize = 65536ull;
size_t uniformSize = 65536ull;
//
vk::Image nullTexture = {};
vk::Image nullImage = {};
vk::Sampler nullSampler = {};
//
inline decltype(auto) SFT() { using T = std::decay_t<decltype(*this)>; return WrapShared<T>(std::dynamic_pointer_cast<T>(shared_from_this())); };
inline decltype(auto) SFT() const { using T = std::decay_t<decltype(*this)>; return WrapShared<T>(std::const_pointer_cast<T>(std::dynamic_pointer_cast<T const>(shared_from_this()))); };
public:
//
PipelineLayoutObj(WrapShared<DeviceObj> deviceObj = {}, cpp21::const_wrap_arg<DescriptorsCreateInfo> cInfo = DescriptorsCreateInfo{}) : BaseObj(std::move(deviceObj->getHandle())), cInfo(cInfo) {
//this->construct(deviceObj, cInfo);
};
//
PipelineLayoutObj(cpp21::const_wrap_arg<Handle> handle, cpp21::const_wrap_arg<DescriptorsCreateInfo> cInfo = DescriptorsCreateInfo{}) : BaseObj(handle), cInfo(cInfo) {
//this->construct(ANAMED::context->get<DeviceObj>(this->base), cInfo);
};
//
std::type_info const& type_info() const override {
return typeid(std::decay_t<decltype(this)>);
};
//
virtual tType registerSelf() {
ANAMED::context->get<DeviceObj>(this->base)->registerObj(this->handle, shared_from_this());
return SFT();
};
//
inline virtual std::vector<vk::DescriptorSet>& getDescriptorSets() { return this->sets; };
inline virtual std::vector<vk::DescriptorSet> const& getDescriptorSets() const { return this->sets; };
//
inline virtual vk::PipelineCache& getPipelineCache() { return this->cache; };
inline virtual vk::PipelineCache const& getPipelineCache() const { return this->cache; };
//
inline virtual vk::PipelineLayout& getPipelineLayout() { return this->handle.as<vk::PipelineLayout>(); };
inline virtual vk::PipelineLayout const& getPipelineLayout() const { return this->handle.as<vk::PipelineLayout>(); };
//
inline virtual cpp21::bucket<vk::DescriptorImageInfo>& getTextureDescriptors() { return textures; };
inline virtual cpp21::bucket<vk::DescriptorImageInfo> const& getTextureDescriptors() const { return textures; };
//
inline virtual cpp21::bucket<vk::DescriptorImageInfo>& getSamplerDescriptors() { return samplers; };
inline virtual cpp21::bucket<vk::DescriptorImageInfo> const& getSamplerDescriptors() const { return samplers; };
//
inline virtual cpp21::bucket<vk::DescriptorImageInfo>& getImageDescriptors() { return images; };
inline virtual cpp21::bucket<vk::DescriptorImageInfo> const& getImageDescriptors() const { return images; };
//
inline static tType make(cpp21::const_wrap_arg<Handle> handle, cpp21::const_wrap_arg<DescriptorsCreateInfo> cInfo = DescriptorsCreateInfo{}) {
auto shared = std::make_shared<PipelineLayoutObj>(handle, cInfo);
shared->construct(ANAMED::context->get<DeviceObj>(handle), cInfo);
auto wrap = shared->registerSelf();
wrap->createNullImages();
return wrap;
};
protected:
//
virtual void createDescriptorLayout(cpp21::const_wrap_arg<vk::DescriptorType> type, cpp21::const_wrap_arg<uint32_t> count = 1u) {
decltype(auto) device = this->base.as<vk::Device>();
decltype(auto) last = this->layouts.size();
this->layoutInfoMaps->push_back(std::make_shared<MSS>(MSS()));
this->layoutBindings->push_back(std::make_shared<DescriptorBindings>());
decltype(auto) layoutInfoMap = this->layoutInfoMaps[last];
decltype(auto) layoutBindingStack = this->layoutBindings[last];
layoutBindingStack->bindings.push_back(vk::DescriptorSetLayoutBinding{ .binding = 0u, .descriptorType = type, .descriptorCount = count, .stageFlags = vk::ShaderStageFlagBits::eAll });
layoutBindingStack->bindingFlags.push_back(vk::DescriptorBindingFlags{ vk::DescriptorBindingFlagBits::eVariableDescriptorCount | vk::DescriptorBindingFlagBits::ePartiallyBound | vk::DescriptorBindingFlagBits::eUpdateAfterBind });
decltype(auto) layoutInfo = layoutInfoMap->set(vk::StructureType::eDescriptorSetLayoutCreateInfo, vk::DescriptorSetLayoutCreateInfo{
.pNext = &(layoutInfoMap->set(vk::StructureType::eDescriptorSetLayoutBindingFlagsCreateInfo, vk::DescriptorSetLayoutBindingFlagsCreateInfo{
})->setBindingFlags(layoutBindingStack->bindingFlags)),
.flags = vk::DescriptorSetLayoutCreateFlagBits::eUpdateAfterBindPool
})->setBindings(layoutBindingStack->bindings);
this->layouts.push_back(device.createDescriptorSetLayout(layoutInfo));
this->descriptorCounts.push_back(count);
};
//
virtual void createDescriptorLayoutUniformStorage(cpp21::const_wrap_arg<uint32_t> maxPageCount = 1u) {
decltype(auto) device = this->base.as<vk::Device>();
decltype(auto) last = this->layouts.size();
this->layoutInfoMaps->push_back(std::make_shared<MSS>(MSS()));
this->layoutBindings->push_back(std::make_shared<DescriptorBindings>());
decltype(auto) layoutInfoMap = this->layoutInfoMaps[last];
decltype(auto) layoutBindingStack = this->layoutBindings[last];
layoutBindingStack->bindings.push_back(vk::DescriptorSetLayoutBinding{ .binding = 0u, .descriptorType = vk::DescriptorType::eUniformBuffer, .descriptorCount = 1u, .stageFlags = vk::ShaderStageFlagBits::eAll });
layoutBindingStack->bindings.push_back(vk::DescriptorSetLayoutBinding{ .binding = 1u, .descriptorType = vk::DescriptorType::eStorageBuffer, .descriptorCount = maxPageCount, .stageFlags = vk::ShaderStageFlagBits::eAll });
layoutBindingStack->bindingFlags.push_back(vk::DescriptorBindingFlags{ vk::DescriptorBindingFlagBits::ePartiallyBound | vk::DescriptorBindingFlagBits::eUpdateAfterBind });
layoutBindingStack->bindingFlags.push_back(vk::DescriptorBindingFlags{ vk::DescriptorBindingFlagBits::ePartiallyBound | vk::DescriptorBindingFlagBits::eUpdateAfterBind | vk::DescriptorBindingFlagBits::eVariableDescriptorCount });
decltype(auto) layoutInfo = layoutInfoMap->set(vk::StructureType::eDescriptorSetLayoutCreateInfo, vk::DescriptorSetLayoutCreateInfo{
.pNext = &(layoutInfoMap->set(vk::StructureType::eDescriptorSetLayoutBindingFlagsCreateInfo, vk::DescriptorSetLayoutBindingFlagsCreateInfo{
})->setBindingFlags(layoutBindingStack->bindingFlags)),
.flags = vk::DescriptorSetLayoutCreateFlagBits::eUpdateAfterBindPool
})->setBindings(layoutBindingStack->bindings);
this->layouts.push_back(device.createDescriptorSetLayout(layoutInfo));
this->descriptorCounts.push_back(maxPageCount);
};
//
virtual void construct(std::shared_ptr<DeviceObj> deviceObj = {}, cpp21::const_wrap_arg<DescriptorsCreateInfo> cInfo = DescriptorsCreateInfo{}) {
//this->deviceObj = deviceObj;
if (cInfo) { this->cInfo = cInfo; };
//
decltype(auto) device = this->base.as<vk::Device>();
decltype(auto) DPI = infoMap->set(vk::StructureType::eDescriptorPoolCreateInfo, vk::DescriptorPoolCreateInfo{
.flags = vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet | vk::DescriptorPoolCreateFlagBits::eUpdateAfterBind,
.maxSets = 6u,
})->setPoolSizes(this->DPC = std::vector<vk::DescriptorPoolSize>{
vk::DescriptorPoolSize{ vk::DescriptorType::eSampler, 64u },
vk::DescriptorPoolSize{ vk::DescriptorType::eSampledImage, 256u },
vk::DescriptorPoolSize{ vk::DescriptorType::eUniformBuffer, 2u },
vk::DescriptorPoolSize{ vk::DescriptorType::eStorageImage, 64u },
vk::DescriptorPoolSize{ vk::DescriptorType::eStorageBuffer, 2u },
});
//
this->layoutBindings = cpp21::vector_of_shared<DescriptorBindings>();
this->layouts = std::vector<vk::DescriptorSetLayout>{};
this->sets = std::vector<vk::DescriptorSet>{};
this->layoutInfoMaps = cpp21::vector_of_shared<MSS>();
this->descriptorCounts = std::vector<uint32_t>{};
//this->createDescriptorLayout(vk::DescriptorType::eUniformBuffer, 1u);
//this->createDescriptorLayout(vk::DescriptorType::eStorageBuffer, 1u);
this->createDescriptorLayoutUniformStorage(16u);
this->createDescriptorLayout(vk::DescriptorType::eSampledImage, 256u);
this->createDescriptorLayout(vk::DescriptorType::eSampler, 64u);
this->createDescriptorLayout(vk::DescriptorType::eStorageImage, 64u);
// reserve for ping-pong
this->pushConstantRanges.push_back(vk::PushConstantRange{ vk::ShaderStageFlagBits::eAll, 0ull, sizeof(PushConstantData) + sizeof(InstanceAddressBlock) + sizeof(PingPongStateInfo) + sizeof(SwapchainStateInfo) });
//this->pushConstantRanges.push_back(vk::PushConstantRange{ vk::ShaderStageFlagBits::eAll, sizeof(PushConstantData), sizeof(InstanceAddressBlock) });
//
this->sets = device.allocateDescriptorSets(this->infoMap->set(vk::StructureType::eDescriptorSetAllocateInfo, vk::DescriptorSetAllocateInfo{
.pNext = &this->infoMap->set(vk::StructureType::eDescriptorSetVariableDescriptorCountAllocateInfo, vk::DescriptorSetVariableDescriptorCountAllocateInfo{
})->setDescriptorCounts(this->descriptorCounts),
.descriptorPool = (this->pool = device.createDescriptorPool(DPI))
})->setSetLayouts(this->layouts));
//
this->handle = device.createPipelineLayout(infoMap->set(vk::StructureType::ePipelineLayoutCreateInfo, vk::PipelineLayoutCreateInfo{
})->setSetLayouts(this->layouts).setPushConstantRanges(this->pushConstantRanges));
//
this->cache = device.createPipelineCache(infoMap->set(vk::StructureType::ePipelineCacheCreateInfo, vk::PipelineCacheCreateInfo{
})->setInitialData<char8_t>(this->initialData));
//
//ANAMED::context->get(this->base)->registerObj(this->handle, shared_from_this());
//
this->createUniformBuffer();
this->createCacheBuffer();
this->updateDescriptors();
//
//return this->SFT();
};
//
virtual vk::Buffer& createUniformBuffer();
virtual vk::Buffer& createCacheBuffer();
virtual void createNullImages();
//
public:
//
virtual void updateDescriptors() {
decltype(auto) device = this->base.as<vk::Device>();
decltype(auto) writes = std::vector<vk::WriteDescriptorSet>{};
decltype(auto) temp = vk::WriteDescriptorSet{ .dstSet = this->sets[0u], .dstBinding = 0u, .dstArrayElement = 0u, .descriptorType = vk::DescriptorType::eUniformBuffer };
if (this->uniformBufferDesc) {
writes.push_back(vk::WriteDescriptorSet(temp).setDstSet(this->sets[0u]).setDstBinding(0u).setDescriptorType(vk::DescriptorType::eUniformBuffer).setPBufferInfo(&this->uniformBufferDesc.value()).setDescriptorCount(1u));
};
if (this->cacheBufferDescs.size() > 0) {
writes.push_back(vk::WriteDescriptorSet(temp).setDstSet(this->sets[0u]).setDstBinding(1u).setDescriptorType(vk::DescriptorType::eStorageBuffer).setBufferInfo(this->cacheBufferDescs));
};
if (this->textures->size() > 0ull) { writes.push_back(vk::WriteDescriptorSet(temp).setDstSet(this->sets[1u]).setPImageInfo(this->textures.data()).setDescriptorCount(uint32_t(this->textures.size())).setDescriptorType(vk::DescriptorType::eSampledImage)); };
if (this->samplers->size() > 0ull) { writes.push_back(vk::WriteDescriptorSet(temp).setDstSet(this->sets[2u]).setPImageInfo(this->samplers.data()).setDescriptorCount(uint32_t(this->samplers.size())).setDescriptorType(vk::DescriptorType::eSampler)); };
if (this->images->size() > 0ull) { writes.push_back(vk::WriteDescriptorSet(temp).setDstSet(this->sets[3u]).setPImageInfo(this->images.data()).setDescriptorCount(uint32_t(this->images.size())).setDescriptorType(vk::DescriptorType::eStorageImage)); };
device.updateDescriptorSets(writes, {});
};
//
virtual tType writeUniformUpdateCommand(cpp21::const_wrap_arg<UniformDataWriteSet> cInfo) {
size_t size = std::min(cInfo->data.size(), cInfo->region->size);
decltype(auto) device = this->base.as<vk::Device>();
decltype(auto) depInfo = vk::DependencyInfo{ .dependencyFlags = vk::DependencyFlagBits::eByRegion };
//
decltype(auto) bufferBarriersBegin = std::vector<vk::BufferMemoryBarrier2>{
vk::BufferMemoryBarrier2{
.srcStageMask = vku::getCorrectPipelineStagesByAccessMask<vk::PipelineStageFlagBits2>(AccessFlagBitsSet::eGeneralRead),
.srcAccessMask = vk::AccessFlagBits2(AccessFlagBitsSet::eGeneralRead) | vk::AccessFlagBits2::eUniformRead,
.dstStageMask = vku::getCorrectPipelineStagesByAccessMask<vk::PipelineStageFlagBits2>(AccessFlagBitsSet::eTransferWrite),
.dstAccessMask = vk::AccessFlagBits2(AccessFlagBitsSet::eTransferWrite),
.srcQueueFamilyIndex = cInfo->info->queueFamilyIndex,
.dstQueueFamilyIndex = cInfo->info->queueFamilyIndex,
.buffer = this->uniformBuffer,
.offset = cInfo->region->offset,
.size = size
}
};
//
decltype(auto) bufferBarriersEnd = std::vector<vk::BufferMemoryBarrier2>{
vk::BufferMemoryBarrier2{
.srcStageMask = vku::getCorrectPipelineStagesByAccessMask<vk::PipelineStageFlagBits2>(AccessFlagBitsSet::eTransferWrite),
.srcAccessMask = vk::AccessFlagBits2(AccessFlagBitsSet::eTransferWrite),
.dstStageMask = vku::getCorrectPipelineStagesByAccessMask<vk::PipelineStageFlagBits2>(AccessFlagBitsSet::eGeneralRead),
.dstAccessMask = vk::AccessFlagBits2(AccessFlagBitsSet::eGeneralRead) | vk::AccessFlagBits2::eUniformRead,
.srcQueueFamilyIndex = cInfo->info->queueFamilyIndex,
.dstQueueFamilyIndex = cInfo->info->queueFamilyIndex,
.buffer = this->uniformBuffer,
.offset = cInfo->region->offset,
.size = size
}
};
//
cInfo->cmdBuf.pipelineBarrier2(depInfo.setBufferMemoryBarriers(bufferBarriersBegin));
cInfo->cmdBuf.updateBuffer(this->uniformBuffer, cInfo->region->offset, size, cInfo->data.data());
cInfo->cmdBuf.pipelineBarrier2(depInfo.setBufferMemoryBarriers(bufferBarriersEnd));
//
return SFT();
};
virtual tType writeCacheUpdateCommand(cpp21::const_wrap_arg<CacheDataWriteSet> cInfo) {
size_t size = std::min(cInfo->data.size(), cInfo->region->size);
decltype(auto) device = this->base.as<vk::Device>();
decltype(auto) depInfo = vk::DependencyInfo{ .dependencyFlags = vk::DependencyFlagBits::eByRegion };
//
decltype(auto) bufferBarriersBegin = std::vector<vk::BufferMemoryBarrier2>{
vk::BufferMemoryBarrier2{
.srcStageMask = vku::getCorrectPipelineStagesByAccessMask<vk::PipelineStageFlagBits2>(AccessFlagBitsSet::eGeneralReadWrite),
.srcAccessMask = vk::AccessFlagBits2(AccessFlagBitsSet::eGeneralReadWrite) | vk::AccessFlagBits2::eShaderStorageWrite | vk::AccessFlagBits2::eShaderStorageRead | vk::AccessFlagBits2::eTransformFeedbackCounterReadEXT | vk::AccessFlagBits2::eTransformFeedbackCounterWriteEXT,
.dstStageMask = vku::getCorrectPipelineStagesByAccessMask<vk::PipelineStageFlagBits2>(AccessFlagBitsSet::eTransferWrite),
.dstAccessMask = vk::AccessFlagBits2(AccessFlagBitsSet::eTransferWrite),
.srcQueueFamilyIndex = cInfo->info->queueFamilyIndex,
.dstQueueFamilyIndex = cInfo->info->queueFamilyIndex,
.buffer = this->cacheBuffer,
.offset = this->cachePageSize * cInfo->page + cInfo->region->offset,
.size = size
}
};
//
decltype(auto) bufferBarriersEnd = std::vector<vk::BufferMemoryBarrier2>{
vk::BufferMemoryBarrier2{
.srcStageMask = vku::getCorrectPipelineStagesByAccessMask<vk::PipelineStageFlagBits2>(AccessFlagBitsSet::eTransferWrite),
.srcAccessMask = vk::AccessFlagBits2(AccessFlagBitsSet::eTransferWrite) | vk::AccessFlagBits2::eShaderStorageWrite | vk::AccessFlagBits2::eShaderStorageRead | vk::AccessFlagBits2::eTransformFeedbackCounterReadEXT | vk::AccessFlagBits2::eTransformFeedbackCounterWriteEXT,
.dstStageMask = vku::getCorrectPipelineStagesByAccessMask<vk::PipelineStageFlagBits2>(AccessFlagBitsSet::eGeneralReadWrite),
.dstAccessMask = vk::AccessFlagBits2(AccessFlagBitsSet::eGeneralReadWrite),
.srcQueueFamilyIndex = cInfo->info->queueFamilyIndex,
.dstQueueFamilyIndex = cInfo->info->queueFamilyIndex,
.buffer = this->cacheBuffer,
.offset = this->cachePageSize * cInfo->page + cInfo->region->offset,
.size = size
}
};
//
cInfo->cmdBuf.pipelineBarrier2(depInfo.setBufferMemoryBarriers(bufferBarriersBegin));
cInfo->cmdBuf.updateBuffer(this->cacheBuffer, this->cachePageSize * cInfo->page + cInfo->region->offset, size, cInfo->data.data());
cInfo->cmdBuf.pipelineBarrier2(depInfo.setBufferMemoryBarriers(bufferBarriersEnd));
//
return SFT();
};
//
virtual FenceType executeUniformUpdateOnce(cpp21::const_wrap_arg<UniformDataSet> cInfo) {
decltype(auto) submission = CommandOnceSubmission{ .submission = cInfo->submission };
//
submission.commandInits.push_back([this, cInfo](cpp21::const_wrap_arg<vk::CommandBuffer> cmdBuf) {
this->writeUniformUpdateCommand(cInfo->writeInfo->with(cmdBuf));
return cmdBuf;
});
//
return ANAMED::context->get<DeviceObj>(this->base)->executeCommandOnce(submission);
};
//
virtual FenceType executeCacheUpdateOnce(cpp21::const_wrap_arg<CacheDataSet> cInfo) {
decltype(auto) submission = CommandOnceSubmission{ .submission = cInfo->submission };
//
submission.commandInits.push_back([this, cInfo](cpp21::const_wrap_arg<vk::CommandBuffer> cmdBuf) {
this->writeCacheUpdateCommand(cInfo->writeInfo->with(cmdBuf));
return cmdBuf;
});
//
return ANAMED::context->get<DeviceObj>(this->base)->executeCommandOnce(submission);
};
};
};
#endif
| 50.269327 | 283 | 0.710239 | helixd2s |
082e88e0210a7b20e595672aec799aae86ffaaba | 4,555 | hh | C++ | nox/src/nox/netapps/user_event_log/log_entry.hh | ayjazz/OESS | deadc504d287febc7cbd7251ddb102bb5c8b1f04 | [
"Apache-2.0"
] | 28 | 2015-02-04T13:59:25.000Z | 2021-12-29T03:44:47.000Z | nox/src/nox/netapps/user_event_log/log_entry.hh | ayjazz/OESS | deadc504d287febc7cbd7251ddb102bb5c8b1f04 | [
"Apache-2.0"
] | 552 | 2015-01-05T18:25:54.000Z | 2022-03-16T18:51:13.000Z | nox/src/nox/netapps/user_event_log/log_entry.hh | ayjazz/OESS | deadc504d287febc7cbd7251ddb102bb5c8b1f04 | [
"Apache-2.0"
] | 25 | 2015-02-04T18:48:20.000Z | 2020-06-18T15:51:05.000Z | #ifndef __LOG_ENTRY_HH__
#define __LOG_ENTRY_HH__
#include "bindings_storage/bindings_storage.hh"
#include "data/datatypes.hh"
namespace vigil {
namespace applications {
// This class represents a single log message, along with the
// information that will be used to insert high-level names into
// the log message.
//
// The goal of the user_event_log is to let applications easily
// generate 'network event log' messages that include high-level
// network names. Essentially, the application provides a format
// string and one or more network identifiers, and the user_event_log fills
// in the format string with high-level names associated with those
// network identifiers. For example, an application may call the
// user_event_log with a format string:
// "%sh is scanning the local network" and and IP address
// as a network identifer. The user_event_log then finds out the
// host names associated with that IP address (e.g., 'host1')
// and creates the resulting message 'host1 is scanning the local network'.
//
// The user_event_log deals with three types of names: hosts, users, and
// locations. When logging, the application can provide network
// identifiers for both a source and destination, meaning that the following
// format characters are valid: %sh, %dh, %su, %du, %sl, and %dl.
//
// There are a few methods below for more "exotic" uses of the user_event_log
// but they are mainly related to corner cases that should not be common for
// most NOX app writers.
//
class LogEntry {
public:
// Log levels to be used by applications generating log messages
enum Level { INVALID = 0, CRITICAL, ALERT, INFO };
enum Direction { SRC = 0, DST } ;
LogEntry(const std::string &_app, Level _level, const std::string &_msg):
app(_app), msg(_msg), level(_level) {}
// This hard-codes the values used to resolve named format
// string (currently, su,du,sh,dh,sl,dl)
// If setName is used in conjunction with an addKey call for
// the same direction, any names found during a key lookup
// with the same direction and type as a name provided to
// setName will be ignored. For example, if one where to call
// AddMacKey(1,SRC) and setName('bob',USER,SRC), even if there
// were many other user names associated with mac = 1, the {su}
// format string would be replaced only with the user name 'bob'
void setName(int64_t uid, PrincipalType type,Direction dir) {
PrincipalList &nlist = (dir == SRC) ? src_names : dst_names;
Principal p;
p.id = uid;
p.type = type;
nlist.push_back(p);
}
// This is similar to a setName() call, but handles the situation when
// the caller does not know the location name, only the DPID and port.
// This is really just a hack to handle the case a log entry contains dl/sl
// but no corresponding bindings exist in Bindings_Storage (e.g., b/c they
// just created it themselves). Unless you create/remove bindings, it is
// unlikely that you need to use this function.
// Note: if the same Log_Entry object has a location set by both setName()
// and setNameByLocation(), the name given to setName() takes precedence.
/*
void setNameByLocation(const datapathid &dpid, uint16_t port, Direction dir) {
storage::Query &q = (dir == SRC) ? src_locname_query : dst_locname_query;
q.clear();
q["principal_type"] = (int64_t) Name::LOCATION;
q["dpid"] = (int64_t) dpid.as_host();
q["port"] = (int64_t) port;
}
*/
// add*Key functions
// Only the last key supplied for each direction is kept and used.
void addLocationKey(const datapathid &dpid, uint16_t port,Direction dir) {
storage::Query &q = (dir == SRC) ? src_key_query : dst_key_query;
q.clear();
q["dpid"] = (int64_t) dpid.as_host();
q["port"] = (int64_t) port;
}
void addMacKey(const ethernetaddr &dladdr, Direction dir) {
storage::Query &q = (dir == SRC) ? src_key_query : dst_key_query;
q.clear();
q["dladdr"] = (int64_t) dladdr.hb_long();
}
void addIPKey(uint32_t nwaddr, Direction dir) {
storage::Query &q = (dir == SRC) ? src_key_query : dst_key_query;
q.clear();
q["nwaddr"] = (int64_t) nwaddr;
}
std::string app,msg;
Level level;
storage::Query src_key_query,dst_key_query,
src_locname_query,dst_locname_query;
PrincipalList src_names, dst_names;
} ;
}
}
#endif
| 38.931624 | 82 | 0.67618 | ayjazz |
082f26d3515c0123deff69d5d7e57c2fc65a60f6 | 1,074 | cc | C++ | opi/emacs/windows/ppid.cc | Ahzed11/mozart2 | 4806504b103e11be723e7813be8f69e4d85875cf | [
"BSD-2-Clause"
] | 379 | 2015-01-02T20:27:33.000Z | 2022-03-26T23:18:17.000Z | opi/emacs/windows/ppid.cc | Ahzed11/mozart2 | 4806504b103e11be723e7813be8f69e4d85875cf | [
"BSD-2-Clause"
] | 81 | 2015-01-08T13:18:52.000Z | 2021-12-21T14:02:21.000Z | opi/emacs/windows/ppid.cc | Ahzed11/mozart2 | 4806504b103e11be723e7813be8f69e4d85875cf | [
"BSD-2-Clause"
] | 75 | 2015-01-06T09:08:20.000Z | 2021-12-17T09:40:18.000Z | /*
* Authors:
* Leif Kornstaedt <kornstae@ps.uni-sb.de>
* Ralf Scheidhauer <scheidhr@dfki.de>
*
* Copyright:
* Leif Kornstaedt, 1999
* Ralf Scheidhauer, 1999
*
* Last change:
* $Date$ by $Author$
* $Revision$
*
* This file is part of Mozart, an implementation of Oz 3:
* http://www.mozart-oz.org
*
* See the file "LICENSE" or
* http://www.mozart-oz.org/LICENSE.html
* for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*/
//
// Set the OZPPID environment variable such that an ozengine.exe subprocess
// can check whether its father still lives
//
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>
#include <stdio.h>
#include "startup.hh"
/* win32 does not support process groups,
* so we set OZPPID such that a subprocess can check whether
* its father still lives
*/
void publishPid(void) {
char auxbuf[100];
int ppid = GetCurrentProcessId();
sprintf(auxbuf,"%d",ppid);
SetEnvironmentVariable("OZPPID",strdup(auxbuf));
}
| 22.375 | 75 | 0.673184 | Ahzed11 |
083038068bcca8bc777a3c88fbc7fccdfdc8ee6a | 499 | cpp | C++ | Test/AOJ/TopologicalSort.test.cpp | maguroplusia/Library | 02e0e277986833fe1c12e20b3677a553b7b27346 | [
"CC0-1.0"
] | null | null | null | Test/AOJ/TopologicalSort.test.cpp | maguroplusia/Library | 02e0e277986833fe1c12e20b3677a553b7b27346 | [
"CC0-1.0"
] | null | null | null | Test/AOJ/TopologicalSort.test.cpp | maguroplusia/Library | 02e0e277986833fe1c12e20b3677a553b7b27346 | [
"CC0-1.0"
] | null | null | null | #define PROBLEM "https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/4/GRL_4_B"
#define IGNORE
#include<bits/stdc++.h>
using namespace std;
#include"../../Other/Template.cpp"
#include"../../Graph/TopologicalSort.cpp"
int main() {
cin >> N;
int M;
cin >> M;
for(int i = 0;i < M;i++) {
int s,t;
cin >> s >> t;
graph[s].push_back(t);
}
vector<int> ret = topological_sort();
for(int i = 0;i < N;i++) {
cout << ret.at(i) << endl;
}
}
| 20.791667 | 82 | 0.543086 | maguroplusia |
083ee3a067734900431b9592bbe07a9cb0e228e8 | 1,106 | cpp | C++ | src/0811.cpp | killf/leetcode_cpp | d1f308a9c3da55ae5416ea28ec2e7a3146533ae9 | [
"MIT"
] | null | null | null | src/0811.cpp | killf/leetcode_cpp | d1f308a9c3da55ae5416ea28ec2e7a3146533ae9 | [
"MIT"
] | null | null | null | src/0811.cpp | killf/leetcode_cpp | d1f308a9c3da55ae5416ea28ec2e7a3146533ae9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <hash_map>
#include <map>
#include <sstream>
#include <type_traits>
#include <algorithm>
#include <stack>
#include <queue>
#include <bitset>
#include <set>
using namespace std;
vector<string> get_all_domains(const string &s) {
vector<string> result = {s};
int start = 0, pos = s.find('.');
while (pos != -1) {
result.push_back(s.substr(start = pos + 1));
pos = s.find('.', start);
}
return result;
}
class Solution {
public:
vector<string> subdomainVisits(vector<string> &lines) {
map<string, int> map;
for (const auto &line:lines) {
int pos = line.find(' ');
int count = atoi(line.substr(0, pos).c_str());
auto domains = get_all_domains(line.substr(pos + 1));
for (const auto &key:domains) map[key] += count;
}
vector<string> result;
stringstream ss;
for (auto[k, v]:map) {
ss.str("");
ss << v << " " << k;
result.push_back(ss.str());
}
return result;
}
};
int main() {
get_all_domains("www.killf.info");
return 0;
} | 20.481481 | 59 | 0.608499 | killf |
08418781039ecfbe9969e0d77b1797ab3e97ddb7 | 6,048 | cpp | C++ | OREData/ored/portfolio/portfolio.cpp | paul-giltinan/Engine | 49b6e142905ca2cce93c2ae46e9ac69380d9f7a1 | [
"BSD-3-Clause"
] | null | null | null | OREData/ored/portfolio/portfolio.cpp | paul-giltinan/Engine | 49b6e142905ca2cce93c2ae46e9ac69380d9f7a1 | [
"BSD-3-Clause"
] | null | null | null | OREData/ored/portfolio/portfolio.cpp | paul-giltinan/Engine | 49b6e142905ca2cce93c2ae46e9ac69380d9f7a1 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (C) 2016 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include <ored/portfolio/fxforward.hpp>
#include <ored/portfolio/portfolio.hpp>
#include <ored/portfolio/swap.hpp>
#include <ored/portfolio/swaption.hpp>
#include <ored/utilities/log.hpp>
#include <ored/utilities/xmlutils.hpp>
#include <ql/errors.hpp>
#include <ql/time/date.hpp>
using namespace QuantLib;
using namespace std;
namespace ore {
namespace data {
using namespace data;
void Portfolio::reset() {
LOG("Reset portfolio of size " << trades_.size());
for (auto t : trades_)
t->reset();
}
void Portfolio::load(const string& fileName, const boost::shared_ptr<TradeFactory>& factory) {
LOG("Parsing XML " << fileName.c_str());
XMLDocument doc(fileName);
LOG("Loaded XML file");
XMLNode* node = doc.getFirstNode("Portfolio");
fromXML(node, factory);
}
void Portfolio::loadFromXMLString(const string& xmlString, const boost::shared_ptr<TradeFactory>& factory) {
LOG("Parsing XML string");
XMLDocument doc;
doc.fromXMLString(xmlString);
LOG("Loaded XML string");
XMLNode* node = doc.getFirstNode("Portfolio");
fromXML(node, factory);
}
void Portfolio::fromXML(XMLNode* node, const boost::shared_ptr<TradeFactory>& factory) {
XMLUtils::checkNode(node, "Portfolio");
vector<XMLNode*> nodes = XMLUtils::getChildrenNodes(node, "Trade");
for (Size i = 0; i < nodes.size(); i++) {
string tradeType = XMLUtils::getChildValue(nodes[i], "TradeType", true);
// Get the id attribute
string id = XMLUtils::getAttribute(nodes[i], "id");
QL_REQUIRE(id != "", "No id attribute in Trade Node");
DLOG("Parsing trade id:" << id);
boost::shared_ptr<Trade> trade = factory->build(tradeType);
if (trade) {
try {
trade->fromXML(nodes[i]);
trade->id() = id;
add(trade);
DLOG("Added Trade " << id << " (" << trade->id() << ")"
<< " class:" << tradeType);
} catch (std::exception& ex) {
ALOG("Exception parsing Trade XML Node (id=" << id
<< ") "
"(class="
<< tradeType << ") : " << ex.what());
}
} else {
WLOG("Unable to build Trade for tradeType=" << tradeType);
}
}
LOG("Finished Parsing XML doc");
}
void Portfolio::save(const string& fileName) const {
LOG("Saving Portfolio to " << fileName);
XMLDocument doc;
XMLNode* node = doc.allocNode("Portfolio");
doc.appendNode(node);
for (auto t : trades_)
XMLUtils::appendNode(node, t->toXML(doc));
// Write doc out.
doc.toFile(fileName);
}
bool Portfolio::remove(const std::string& tradeID) {
for (auto it = trades_.begin(); it != trades_.end(); ++it) {
if ((*it)->id() == tradeID) {
trades_.erase(it);
return true;
}
}
return false;
}
void Portfolio::build(const boost::shared_ptr<EngineFactory>& engineFactory) {
LOG("Building Portfolio of size " << trades_.size());
auto trade = trades_.begin();
while (trade != trades_.end()) {
try {
(*trade)->build(engineFactory);
++trade;
} catch (std::exception& e) {
ALOG("Error building trade (" << (*trade)->id() << ") : " << e.what());
trade = trades_.erase(trade);
}
}
LOG("Built Portfolio. Size now " << trades_.size());
QL_REQUIRE(trades_.size() > 0, "Portfolio does not contain any built trades");
}
Date Portfolio::maturity() const {
QL_REQUIRE(trades_.size() > 0, "Cannot get maturity of an empty portfolio");
Date mat = trades_.front()->maturity();
for (const auto& t : trades_)
mat = std::max(mat, t->maturity());
return mat;
}
vector<string> Portfolio::ids() const {
vector<string> ids;
for (auto t : trades_)
ids.push_back(t->id());
return ids;
}
map<string, string> Portfolio::nettingSetMap() const {
map<string, string> nettingSetMap;
for (auto t : trades_)
nettingSetMap[t->id()] = t->envelope().nettingSetId();
return nettingSetMap;
}
void Portfolio::add(const boost::shared_ptr<Trade>& trade) {
QL_REQUIRE(!has(trade->id()), "Attempted to add a trade to the portfolio with an id, which already exists.");
trades_.push_back(trade);
}
bool Portfolio::has(const string& id) {
return find_if(trades_.begin(), trades_.end(),
[id](const boost::shared_ptr<Trade>& trade) { return trade->id() == id; }) != trades_.end();
}
boost::shared_ptr<Trade> Portfolio::get(const string& id) const {
auto it = find_if(trades_.begin(), trades_.end(),
[id](const boost::shared_ptr<Trade>& trade) { return trade->id() == id; });
if (it == trades_.end()) {
return nullptr;
} else {
return *it;
}
}
std::set<std::string> Portfolio::portfolioIds() const {
std::set<std::string> portfolioIds;
for (auto const& t : trades_)
portfolioIds.insert(t->portfolioIds().begin(), t->portfolioIds().end());
return portfolioIds;
}
} // namespace data
} // namespace ore
| 32.691892 | 113 | 0.604828 | paul-giltinan |
0842862027183166d682912b5a9e1784c0fe6cad | 2,753 | cpp | C++ | src/test/boost_utils/serial_port_test.cpp | PolarGoose/UtilsH | 2b94d4244149f9612d0c3e0f1552cfd1315e5f68 | [
"MIT"
] | 1 | 2021-07-20T14:35:56.000Z | 2021-07-20T14:35:56.000Z | src/test/boost_utils/serial_port_test.cpp | PolarGoose/UtilsH | 2b94d4244149f9612d0c3e0f1552cfd1315e5f68 | [
"MIT"
] | null | null | null | src/test/boost_utils/serial_port_test.cpp | PolarGoose/UtilsH | 2b94d4244149f9612d0c3e0f1552cfd1315e5f68 | [
"MIT"
] | null | null | null | #include "utils/socat_loopback_serial_port.h"
#include "utils_h/boost_utils/serial_port.h"
#include "utils_h/concurrency/waiting_queue.h"
#include <boost/range/irange.hpp>
#include <gtest/gtest.h>
using namespace utils_h;
using namespace concurrency;
using namespace boost_utils;
using namespace testing;
using namespace std::chrono_literals;
static auto generate_message(size_t size)
{
std::vector<char> message;
message.reserve(size);
for (const auto i : boost::irange(static_cast<size_t>(0), size)) {
message.emplace_back(static_cast<char>(i));
}
return message;
}
class serial_port_test : public Test, public serial_port_events_handler {
void on_bytes_received(const char *data, const size_t size) override
{
_receive_queue.blocking_push({data, data + size});
}
void on_receive_error(const boost::system::error_code & /*ec*/) override
{
}
void on_send_error(const boost::system::error_code & /*ec*/) override
{
}
protected:
serial_port_test()
{
_serial_port.start_receiving();
}
auto wait_for_message()
{
return _receive_queue.blocking_pop(3s);
}
std::optional<socat_loopback_serial_port> _loopback_port{std::make_optional<socat_loopback_serial_port>()};
waiting_queue<std::vector<char>> _receive_queue;
serial_port _serial_port{_loopback_port->port_name(), *this};
};
TEST_F(serial_port_test, Throws_exception_if_port_doesnt_exist)
{
auto constructor = [&] { serial_port{"non_existing_port_name", *this}; };
ASSERT_THROW(constructor(), boost::system::system_error);
}
TEST_F(serial_port_test, Message_can_be_sent_and_received)
{
const auto message = generate_message(100);
_serial_port.async_send(message.data(), message.size());
const auto received_message = wait_for_message();
ASSERT_EQ(message.size(), received_message.size());
ASSERT_EQ(message, received_message);
ASSERT_EQ(_receive_queue.size(), 0);
}
TEST_F(serial_port_test, Works_if_message_is_being_sent_while_port_is_destructing)
{
const auto message = generate_message(10 * 1000 * 1000);
_serial_port.async_send(message.data(), message.size());
}
TEST_F(serial_port_test, Stress_test)
{
const auto message = generate_message(10 * 1000 * 1000);
std::vector<char> received_message;
for (size_t i{0}; i < message.size(); i += 1000) {
_serial_port.async_send(message.data() + i, 1000);
}
while (received_message.size() != message.size()) {
const auto m = wait_for_message();
received_message.insert(std::end(received_message), std::begin(m), std::end(m));
}
ASSERT_EQ(message.size(), received_message.size());
ASSERT_EQ(message, received_message);
}
| 29.287234 | 111 | 0.714493 | PolarGoose |
0845952a10053f9eb70bcec6dc242ec42431bac7 | 9,225 | hpp | C++ | include/Newtonsoft/Json/Converters/DataTableConverter.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/Newtonsoft/Json/Converters/DataTableConverter.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/Newtonsoft/Json/Converters/DataTableConverter.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: Newtonsoft.Json.JsonConverter
#include "Newtonsoft/Json/JsonConverter.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Newtonsoft::Json
namespace Newtonsoft::Json {
// Forward declaring type: JsonReader
class JsonReader;
// Forward declaring type: JsonSerializer
class JsonSerializer;
// Forward declaring type: JsonWriter
class JsonWriter;
}
// Forward declaring namespace: System::Data
namespace System::Data {
// Forward declaring type: DataTable
class DataTable;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
}
// Completed forward declares
// Type namespace: Newtonsoft.Json.Converters
namespace Newtonsoft::Json::Converters {
// Forward declaring type: DataTableConverter
class DataTableConverter;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::Newtonsoft::Json::Converters::DataTableConverter);
DEFINE_IL2CPP_ARG_TYPE(::Newtonsoft::Json::Converters::DataTableConverter*, "Newtonsoft.Json.Converters", "DataTableConverter");
// Type namespace: Newtonsoft.Json.Converters
namespace Newtonsoft::Json::Converters {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: Newtonsoft.Json.Converters.DataTableConverter
// [TokenAttribute] Offset: FFFFFFFF
// [NullableAttribute] Offset: 67426C
// [NullableContextAttribute] Offset: 67426C
class DataTableConverter : public ::Newtonsoft::Json::JsonConverter {
public:
// static private System.Void CreateRow(Newtonsoft.Json.JsonReader reader, System.Data.DataTable dt, Newtonsoft.Json.JsonSerializer serializer)
// Offset: 0xDBECD0
static void CreateRow(::Newtonsoft::Json::JsonReader* reader, ::System::Data::DataTable* dt, ::Newtonsoft::Json::JsonSerializer* serializer);
// static private System.Type GetColumnDataType(Newtonsoft.Json.JsonReader reader)
// Offset: 0xDBF1E0
static ::System::Type* GetColumnDataType(::Newtonsoft::Json::JsonReader* reader);
// public System.Void .ctor()
// Offset: 0xDBDE84
// Implemented from: Newtonsoft.Json.JsonConverter
// Base method: System.Void JsonConverter::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static DataTableConverter* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Converters::DataTableConverter::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<DataTableConverter*, creationType>()));
}
// public override System.Void WriteJson(Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.JsonSerializer serializer)
// Offset: 0xDBE238
// Implemented from: Newtonsoft.Json.JsonConverter
// Base method: System.Void JsonConverter::WriteJson(Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.JsonSerializer serializer)
void WriteJson(::Newtonsoft::Json::JsonWriter* writer, ::Il2CppObject* value, ::Newtonsoft::Json::JsonSerializer* serializer);
// public override System.Object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Object existingValue, Newtonsoft.Json.JsonSerializer serializer)
// Offset: 0xDBE9B0
// Implemented from: Newtonsoft.Json.JsonConverter
// Base method: System.Object JsonConverter::ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Object existingValue, Newtonsoft.Json.JsonSerializer serializer)
::Il2CppObject* ReadJson(::Newtonsoft::Json::JsonReader* reader, ::System::Type* objectType, ::Il2CppObject* existingValue, ::Newtonsoft::Json::JsonSerializer* serializer);
// public override System.Boolean CanConvert(System.Type valueType)
// Offset: 0xDBF3DC
// Implemented from: Newtonsoft.Json.JsonConverter
// Base method: System.Boolean JsonConverter::CanConvert(System.Type valueType)
bool CanConvert(::System::Type* valueType);
}; // Newtonsoft.Json.Converters.DataTableConverter
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Newtonsoft::Json::Converters::DataTableConverter::CreateRow
// Il2CppName: CreateRow
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::Newtonsoft::Json::JsonReader*, ::System::Data::DataTable*, ::Newtonsoft::Json::JsonSerializer*)>(&Newtonsoft::Json::Converters::DataTableConverter::CreateRow)> {
static const MethodInfo* get() {
static auto* reader = &::il2cpp_utils::GetClassFromName("Newtonsoft.Json", "JsonReader")->byval_arg;
static auto* dt = &::il2cpp_utils::GetClassFromName("System.Data", "DataTable")->byval_arg;
static auto* serializer = &::il2cpp_utils::GetClassFromName("Newtonsoft.Json", "JsonSerializer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Converters::DataTableConverter*), "CreateRow", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader, dt, serializer});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Converters::DataTableConverter::GetColumnDataType
// Il2CppName: GetColumnDataType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Type* (*)(::Newtonsoft::Json::JsonReader*)>(&Newtonsoft::Json::Converters::DataTableConverter::GetColumnDataType)> {
static const MethodInfo* get() {
static auto* reader = &::il2cpp_utils::GetClassFromName("Newtonsoft.Json", "JsonReader")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Converters::DataTableConverter*), "GetColumnDataType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Converters::DataTableConverter::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: Newtonsoft::Json::Converters::DataTableConverter::WriteJson
// Il2CppName: WriteJson
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Newtonsoft::Json::Converters::DataTableConverter::*)(::Newtonsoft::Json::JsonWriter*, ::Il2CppObject*, ::Newtonsoft::Json::JsonSerializer*)>(&Newtonsoft::Json::Converters::DataTableConverter::WriteJson)> {
static const MethodInfo* get() {
static auto* writer = &::il2cpp_utils::GetClassFromName("Newtonsoft.Json", "JsonWriter")->byval_arg;
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* serializer = &::il2cpp_utils::GetClassFromName("Newtonsoft.Json", "JsonSerializer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Converters::DataTableConverter*), "WriteJson", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{writer, value, serializer});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Converters::DataTableConverter::ReadJson
// Il2CppName: ReadJson
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (Newtonsoft::Json::Converters::DataTableConverter::*)(::Newtonsoft::Json::JsonReader*, ::System::Type*, ::Il2CppObject*, ::Newtonsoft::Json::JsonSerializer*)>(&Newtonsoft::Json::Converters::DataTableConverter::ReadJson)> {
static const MethodInfo* get() {
static auto* reader = &::il2cpp_utils::GetClassFromName("Newtonsoft.Json", "JsonReader")->byval_arg;
static auto* objectType = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
static auto* existingValue = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* serializer = &::il2cpp_utils::GetClassFromName("Newtonsoft.Json", "JsonSerializer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Converters::DataTableConverter*), "ReadJson", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader, objectType, existingValue, serializer});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Converters::DataTableConverter::CanConvert
// Il2CppName: CanConvert
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Newtonsoft::Json::Converters::DataTableConverter::*)(::System::Type*)>(&Newtonsoft::Json::Converters::DataTableConverter::CanConvert)> {
static const MethodInfo* get() {
static auto* valueType = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Converters::DataTableConverter*), "CanConvert", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{valueType});
}
};
| 64.0625 | 307 | 0.755881 | v0idp |
36b0b125724a6a8ac343a481f545cb27ac2b9d55 | 5,224 | hpp | C++ | include/CQLDriver/Common/ColumnTypes/Time.hpp | cpv-project/cpv-cql-driver | 66eebfd4e9ec75dc49cd4a7073a51a830236807a | [
"MIT"
] | 41 | 2018-01-23T09:27:32.000Z | 2021-02-15T15:49:07.000Z | include/CQLDriver/Common/ColumnTypes/Time.hpp | cpv-project/cpv-cql-driver | 66eebfd4e9ec75dc49cd4a7073a51a830236807a | [
"MIT"
] | 20 | 2018-01-25T04:25:48.000Z | 2019-03-09T02:49:41.000Z | include/CQLDriver/Common/ColumnTypes/Time.hpp | cpv-project/cpv-cql-driver | 66eebfd4e9ec75dc49cd4a7073a51a830236807a | [
"MIT"
] | 5 | 2018-04-10T12:19:13.000Z | 2020-02-17T03:30:50.000Z | #pragma once
#include <iomanip>
#include "./ColumnDefinitions.hpp"
#include "./DateTimeBase.hpp"
namespace cql {
/**
* An 8 byte two's complement long representing nanoseconds since midnignt.
* Valid values are in the range 0 to 86'3999'9999'9999
*/
class Time : private DateTimeBase {
public:
using DateTimeBase::UnderlyingType;
using DateTimeBase::get;
using DateTimeBase::set;
using DateTimeBase::reset;
using DateTimeBase::operator UnderlyingType;
using DateTimeBase::operator std::time_t;
using DateTimeBase::operator std::tm;
static const std::size_t EncodeSize = sizeof(std::uint64_t);
static const std::uint32_t SecondsPerDay = 86400;
static const std::uint32_t NanoSecondsPerSecond = 1'000'000'000;
/** Set duration since midnight of this day, in local timezone */
template <class Rep, class Period>
void set(std::chrono::duration<Rep, Period> duration) {
std::chrono::nanoseconds nanoSeconds(duration);
std::time_t localTime = nanoSeconds.count() / NanoSecondsPerSecond;
std::tm localTm = {};
::gmtime_r(&localTime, &localTm);
set(localTm);
value_ += std::chrono::nanoseconds(nanoSeconds.count() % NanoSecondsPerSecond);
}
/** Reset to initial state */
void reset() {
set(std::chrono::nanoseconds(0));
}
/** Encode to binary data */
void encodeBody(std::string& data) const {
// store local time in database, not utc time
std::chrono::nanoseconds nanoSeconds = *this;
std::uint64_t dbValue = nanoSeconds.count();
dbValue = seastar::cpu_to_be(dbValue);
data.append(reinterpret_cast<const char*>(&dbValue), sizeof(dbValue));
}
/** Decode from binary data */
void decodeBody(const char* ptr, const ColumnEncodeDecodeSizeType& size) {
std::uint64_t dbValue = 0;
if (size == 0) {
reset(); // empty
} else if (CQL_UNLIKELY(size != sizeof(dbValue))) {
throw DecodeException(CQL_CODEINFO,
"time length not matched, expected to be", sizeof(dbValue),
"but actual is", size);
} else {
// load local time from database
std::memcpy(&dbValue, ptr, sizeof(dbValue));
dbValue = seastar::be_to_cpu(dbValue);
set(std::chrono::nanoseconds(dbValue));
}
}
/** Constructors */
Time() : DateTimeBase() { reset(); }
template <class... Args>
// cppcheck-suppress noExplicitConstructor
Time(Args&&... args) : DateTimeBase() {
set(std::forward<Args>(args)...);
}
/** Allow assign from whatever function "set" would take */
template <class... Args>
void operator=(Args&&... args) {
set(std::forward<Args>(args)...);
}
/** Get total nanoseconds since midnight of this day, in local timezone */
operator std::chrono::nanoseconds() const {
std::tm localTm = *this;
std::time_t localTime = ::timegm(&localTm);
std::uint64_t nanoseconds = (localTime % SecondsPerDay) * NanoSecondsPerSecond;
nanoseconds += (
std::chrono::nanoseconds(value_.time_since_epoch()).count() % NanoSecondsPerSecond);
return std::chrono::nanoseconds(nanoseconds);
}
/** Get total microseconds since midnight of this day, in local timezone */
operator std::chrono::microseconds() const {
return std::chrono::duration_cast<std::chrono::microseconds>(
static_cast<std::chrono::nanoseconds>(*this));
}
/** Get total milliseconds since midnight of this day, in local timezone */
operator std::chrono::milliseconds() const {
return std::chrono::duration_cast<std::chrono::milliseconds>(
static_cast<std::chrono::nanoseconds>(*this));
}
/** Get total seconds since midnight of this day, in local timezone */
operator std::chrono::seconds() const {
return std::chrono::duration_cast<std::chrono::seconds>(
static_cast<std::chrono::nanoseconds>(*this));
}
/** Get total minutes since midnight of this day, in local timezone */
operator std::chrono::minutes() const {
return std::chrono::duration_cast<std::chrono::minutes>(
static_cast<std::chrono::nanoseconds>(*this));
}
/** Get total hours since midnight of this day, in local timezone */
operator std::chrono::hours() const {
return std::chrono::duration_cast<std::chrono::hours>(
static_cast<std::chrono::nanoseconds>(*this));
}
/** Create a Time with specificed hour:minute:second */
static Time create(std::uint8_t hour, std::uint8_t minute, std::uint8_t second) {
std::tm localTm = {};
localTm.tm_sec = second; // [0, 60]
localTm.tm_min = minute; // [0, 59]
localTm.tm_hour = hour; // [0, 23]
localTm.tm_mday = 1; // [1, 31]
localTm.tm_mon = 1; // [0, 11]
localTm.tm_year = 70; // years since 1900
return Time(localTm);
}
/** Create a Time with now, in local timezone */
static Time now() {
return Time(std::chrono::system_clock::now());
}
};
/** Write text description expressed in local timezone of time */
std::ostream& operator<<(std::ostream& stream, const Time& time) {
std::tm localTm = time;
std::chrono::nanoseconds nanoSeconds = time;
stream << std::setfill('0') <<
std::setw(2) << localTm.tm_hour << ":" <<
std::setw(2) << localTm.tm_min << ":" <<
std::setw(2) << localTm.tm_sec << "." <<
std::setw(9) << (nanoSeconds.count() % Time::NanoSecondsPerSecond);
return stream;
}
}
| 34.596026 | 88 | 0.675919 | cpv-project |
36b1aa71d1ee62fe7612ccf769e9f37e5b58a0a3 | 384 | cpp | C++ | A. Stones on the Table.cpp | Samim-Arefin/Codeforce-Problem-Solution | 7219ee6173faaa9e06231d4cd3e9ba292ae27ce3 | [
"MIT"
] | null | null | null | A. Stones on the Table.cpp | Samim-Arefin/Codeforce-Problem-Solution | 7219ee6173faaa9e06231d4cd3e9ba292ae27ce3 | [
"MIT"
] | null | null | null | A. Stones on the Table.cpp | Samim-Arefin/Codeforce-Problem-Solution | 7219ee6173faaa9e06231d4cd3e9ba292ae27ce3 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{
int size;
while (cin >> size)
{
string str;
for (int i = 0; i < size; i++)
{
char ch;
cin >> ch;
str.push_back(ch);
}
int count = 0;
for (int i = 0; i <size - 1; i++)
{
for (int j = i; j <= i; j++)
{
if (str[j] == str[j + 1])
{
count++;
}
}
}
cout << count << endl;
}
} | 13.714286 | 35 | 0.445313 | Samim-Arefin |
36b47ab98d0731781ad2664a6d4a671a6300dfe6 | 707 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/game/ui/UnlockableProgram.hpp | WSSDude420/RED4ext.SDK | eaca8bdf7b92c48422b18431ed8cd0876f53bdb3 | [
"MIT"
] | null | null | null | include/RED4ext/Scripting/Natives/Generated/game/ui/UnlockableProgram.hpp | WSSDude420/RED4ext.SDK | eaca8bdf7b92c48422b18431ed8cd0876f53bdb3 | [
"MIT"
] | null | null | null | include/RED4ext/Scripting/Natives/Generated/game/ui/UnlockableProgram.hpp | WSSDude420/RED4ext.SDK | eaca8bdf7b92c48422b18431ed8cd0876f53bdb3 | [
"MIT"
] | null | null | null | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/CName.hpp>
#include <RED4ext/NativeTypes.hpp>
namespace RED4ext
{
namespace game::ui {
struct UnlockableProgram
{
static constexpr const char* NAME = "gameuiUnlockableProgram";
static constexpr const char* ALIAS = NAME;
CName name; // 00
CName note; // 08
bool isFulfilled; // 10
uint8_t unk11[0x14 - 0x11]; // 11
TweakDBID programTweakID; // 14
TweakDBID iconTweakID; // 1C
bool hidden; // 24
uint8_t unk25[0x28 - 0x25]; // 25
};
RED4EXT_ASSERT_SIZE(UnlockableProgram, 0x28);
} // namespace game::ui
} // namespace RED4ext
| 23.566667 | 66 | 0.697313 | WSSDude420 |
36b4806dc61fbbd50418c375f355a2cbaf74d2a0 | 11,034 | cpp | C++ | src/tests/Interop/COM/NativeClients/Dispatch/Client.cpp | AustinWise/runtime | 0df6dac02c71ca400e81c62d6cd18366dec519c4 | [
"MIT"
] | 1 | 2021-09-08T07:08:49.000Z | 2021-09-08T07:08:49.000Z | src/tests/Interop/COM/NativeClients/Dispatch/Client.cpp | mknotzer/runtime | 2b2eb5ad72cd22c7ce0364efa836e3372cecc092 | [
"MIT"
] | null | null | null | src/tests/Interop/COM/NativeClients/Dispatch/Client.cpp | mknotzer/runtime | 2b2eb5ad72cd22c7ce0364efa836e3372cecc092 | [
"MIT"
] | 2 | 2021-05-17T22:12:46.000Z | 2021-05-19T06:21:16.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "ClientTests.h"
#include <memory>
void Validate_Numeric_In_ReturnByRef();
void Validate_Float_In_ReturnAndUpdateByRef();
void Validate_Double_In_ReturnAndUpdateByRef();
void Validate_LCID_Marshaled();
void Validate_Enumerator();
template<COINIT TM>
struct ComInit
{
const HRESULT Result;
ComInit()
: Result{ ::CoInitializeEx(nullptr, TM) }
{ }
~ComInit()
{
if (SUCCEEDED(Result))
::CoUninitialize();
}
};
using ComMTA = ComInit<COINIT_MULTITHREADED>;
int __cdecl main()
{
ComMTA init;
if (FAILED(init.Result))
return -1;
try
{
Validate_Numeric_In_ReturnByRef();
Validate_Float_In_ReturnAndUpdateByRef();
Validate_Double_In_ReturnAndUpdateByRef();
Validate_LCID_Marshaled();
Validate_Enumerator();
}
catch (HRESULT hr)
{
::printf("Test Failure: 0x%08x\n", hr);
return 101;
}
return 100;
}
void Validate_Numeric_In_ReturnByRef()
{
HRESULT hr;
CoreShimComActivation csact{ W("NETServer"), W("DispatchTesting") };
ComSmartPtr<IDispatchTesting> dispatchTesting;
THROW_IF_FAILED(::CoCreateInstance(CLSID_DispatchTesting, nullptr, CLSCTX_INPROC, IID_IDispatchTesting, (void**)&dispatchTesting));
LPOLESTR numericMethodName = (LPOLESTR)W("DoubleNumeric_ReturnByRef");
LCID lcid = MAKELCID(LANG_USER_DEFAULT, SORT_DEFAULT);
DISPID methodId;
::wprintf(W("Invoke %s\n"), numericMethodName);
THROW_IF_FAILED(dispatchTesting->GetIDsOfNames(
IID_NULL,
&numericMethodName,
1,
lcid,
&methodId));
BYTE b1 = 24;
BYTE b2;
SHORT s1 = 53;
SHORT s2;
USHORT us1 = 74;
USHORT us2;
LONG i1 = 34;
LONG i2;
ULONG ui1 = 854;
ULONG ui2;
LONGLONG l1 = 894;
LONGLONG l2;
ULONGLONG ul1 = 4168;
ULONGLONG ul2;
DISPPARAMS params;
params.cArgs = 14;
params.rgvarg = new VARIANTARG[params.cArgs];
params.cNamedArgs = 0;
params.rgdispidNamedArgs = nullptr;
V_VT(¶ms.rgvarg[13]) = VT_UI1;
V_UI1(¶ms.rgvarg[13]) = b1;
V_VT(¶ms.rgvarg[12]) = VT_BYREF | VT_UI1;
V_UI1REF(¶ms.rgvarg[12]) = &b2;
V_VT(¶ms.rgvarg[11]) = VT_I2;
V_I2(¶ms.rgvarg[11]) = s1;
V_VT(¶ms.rgvarg[10]) = VT_BYREF | VT_I2;
V_I2REF(¶ms.rgvarg[10]) = &s2;
V_VT(¶ms.rgvarg[9]) = VT_UI2;
V_UI2(¶ms.rgvarg[9]) = us1;
V_VT(¶ms.rgvarg[8]) = VT_BYREF | VT_UI2;
V_UI2REF(¶ms.rgvarg[8]) = &us2;
V_VT(¶ms.rgvarg[7]) = VT_I4;
V_I4(¶ms.rgvarg[7]) = i1;
V_VT(¶ms.rgvarg[6]) = VT_BYREF | VT_I4;
V_I4REF(¶ms.rgvarg[6]) = &i2;
V_VT(¶ms.rgvarg[5]) = VT_UI4;
V_UI4(¶ms.rgvarg[5]) = ui1;
V_VT(¶ms.rgvarg[4]) = VT_BYREF | VT_UI4;
V_UI4REF(¶ms.rgvarg[4]) = &ui2;
V_VT(¶ms.rgvarg[3]) = VT_I8;
V_I8(¶ms.rgvarg[3]) = l1;
V_VT(¶ms.rgvarg[2]) = VT_BYREF | VT_I8;
V_I8REF(¶ms.rgvarg[2]) = &l2;
V_VT(¶ms.rgvarg[1]) = VT_UI8;
V_UI8(¶ms.rgvarg[1]) = ul1;
V_VT(¶ms.rgvarg[0]) = VT_BYREF | VT_UI8;
V_UI8REF(¶ms.rgvarg[0]) = &ul2;
THROW_IF_FAILED(dispatchTesting->Invoke(
methodId,
IID_NULL,
lcid,
DISPATCH_METHOD,
¶ms,
nullptr,
nullptr,
nullptr
));
THROW_FAIL_IF_FALSE(b2 == b1 * 2);
THROW_FAIL_IF_FALSE(s2 == s1 * 2);
THROW_FAIL_IF_FALSE(us2 == us1 * 2);
THROW_FAIL_IF_FALSE(i2 == i1 * 2);
THROW_FAIL_IF_FALSE(ui2 == ui1 * 2);
THROW_FAIL_IF_FALSE(l2 == l1 * 2);
THROW_FAIL_IF_FALSE(ul2 == ul1 * 2);
}
namespace
{
bool EqualByBound(float expected, float actual)
{
float low = expected - 0.0001f;
float high = expected + 0.0001f;
float eps = abs(expected - actual);
return eps < std::numeric_limits<float>::epsilon() || (low < actual && actual < high);
}
bool EqualByBound(double expected, double actual)
{
double low = expected - 0.00001;
double high = expected + 0.00001;
double eps = abs(expected - actual);
return eps < std::numeric_limits<double>::epsilon() || (low < actual && actual < high);
}
}
void Validate_Float_In_ReturnAndUpdateByRef()
{
HRESULT hr;
CoreShimComActivation csact{ W("NETServer"), W("DispatchTesting") };
ComSmartPtr<IDispatchTesting> dispatchTesting;
THROW_IF_FAILED(::CoCreateInstance(CLSID_DispatchTesting, nullptr, CLSCTX_INPROC, IID_IDispatchTesting, (void**)&dispatchTesting));
LPOLESTR numericMethodName = (LPOLESTR)W("Add_Float_ReturnAndUpdateByRef");
LCID lcid = MAKELCID(LANG_USER_DEFAULT, SORT_DEFAULT);
DISPID methodId;
::wprintf(W("Invoke %s\n"), numericMethodName);
THROW_IF_FAILED(dispatchTesting->GetIDsOfNames(
IID_NULL,
&numericMethodName,
1,
lcid,
&methodId));
float a = 12.34f;
float b = 1.234f;
float expected = b + a;
DISPPARAMS params;
params.cArgs = 2;
params.rgvarg = new VARIANTARG[params.cArgs];
params.cNamedArgs = 0;
params.rgdispidNamedArgs = nullptr;
VARIANT result;
V_VT(¶ms.rgvarg[1]) = VT_R4;
V_R4(¶ms.rgvarg[1]) = a;
V_VT(¶ms.rgvarg[0]) = VT_BYREF | VT_R4;
V_R4REF(¶ms.rgvarg[0]) = &b;
THROW_IF_FAILED(dispatchTesting->Invoke(
methodId,
IID_NULL,
lcid,
DISPATCH_METHOD,
¶ms,
&result,
nullptr,
nullptr
));
THROW_FAIL_IF_FALSE(EqualByBound(expected, V_R4(&result)));
THROW_FAIL_IF_FALSE(EqualByBound(expected, b));
}
void Validate_Double_In_ReturnAndUpdateByRef()
{
HRESULT hr;
CoreShimComActivation csact{ W("NETServer"), W("DispatchTesting") };
ComSmartPtr<IDispatchTesting> dispatchTesting;
THROW_IF_FAILED(::CoCreateInstance(CLSID_DispatchTesting, nullptr, CLSCTX_INPROC, IID_IDispatchTesting, (void**)&dispatchTesting));
LPOLESTR numericMethodName = (LPOLESTR)W("Add_Double_ReturnAndUpdateByRef");
LCID lcid = MAKELCID(LANG_USER_DEFAULT, SORT_DEFAULT);
DISPID methodId;
::wprintf(W("Invoke %s\n"), numericMethodName);
THROW_IF_FAILED(dispatchTesting->GetIDsOfNames(
IID_NULL,
&numericMethodName,
1,
lcid,
&methodId));
double a = 1856.5634;
double b = 587867.757;
double expected = a + b;
DISPPARAMS params;
params.cArgs = 2;
params.rgvarg = new VARIANTARG[params.cArgs];
params.cNamedArgs = 0;
params.rgdispidNamedArgs = nullptr;
VARIANT result;
V_VT(¶ms.rgvarg[1]) = VT_R8;
V_R8(¶ms.rgvarg[1]) = a;
V_VT(¶ms.rgvarg[0]) = VT_BYREF | VT_R8;
V_R8REF(¶ms.rgvarg[0]) = &b;
THROW_IF_FAILED(dispatchTesting->Invoke(
methodId,
IID_NULL,
lcid,
DISPATCH_METHOD,
¶ms,
&result,
nullptr,
nullptr
));
THROW_FAIL_IF_FALSE(EqualByBound(expected, V_R8(&result)));
THROW_FAIL_IF_FALSE(EqualByBound(expected, b));
}
void Validate_LCID_Marshaled()
{
HRESULT hr;
CoreShimComActivation csact{ W("NETServer"), W("DispatchTesting") };
ComSmartPtr<IDispatchTesting> dispatchTesting;
THROW_IF_FAILED(::CoCreateInstance(CLSID_DispatchTesting, nullptr, CLSCTX_INPROC, IID_IDispatchTesting, (void**)&dispatchTesting));
LPOLESTR numericMethodName = (LPOLESTR)W("PassThroughLCID");
LCID lcid = MAKELCID(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_CHILE), SORT_DEFAULT);
DISPID methodId;
::wprintf(W("Invoke %s\n"), numericMethodName);
THROW_IF_FAILED(dispatchTesting->GetIDsOfNames(
IID_NULL,
&numericMethodName,
1,
lcid,
&methodId));
DISPPARAMS params;
params.cArgs = 0;
params.rgvarg = nullptr;
params.cNamedArgs = 0;
params.rgdispidNamedArgs = nullptr;
VARIANT result;
THROW_IF_FAILED(dispatchTesting->Invoke(
methodId,
IID_NULL,
lcid,
DISPATCH_METHOD,
¶ms,
&result,
nullptr,
nullptr
));
THROW_FAIL_IF_FALSE(lcid == V_I4(&result));
}
namespace
{
void ValidateExpectedEnumVariant(IEnumVARIANT *enumVariant, int expectedStart, int expectedCount)
{
HRESULT hr;
VARIANT element;
ULONG numFetched;
for(int i = expectedStart; i < expectedStart + expectedCount; ++i)
{
THROW_IF_FAILED(enumVariant->Next(1, &element, &numFetched));
THROW_FAIL_IF_FALSE(numFetched == 1);
THROW_FAIL_IF_FALSE(V_I4(&element) == i)
::VariantClear(&element);
}
hr = enumVariant->Next(1, &element, &numFetched);
THROW_FAIL_IF_FALSE(hr == S_FALSE && numFetched == 0);
}
void ValidateReturnedEnumerator(VARIANT *toValidate)
{
HRESULT hr;
THROW_FAIL_IF_FALSE(V_VT(toValidate) == VT_UNKNOWN || V_VT(toValidate) == VT_DISPATCH);
ComSmartPtr<IEnumVARIANT> enumVariant;
THROW_IF_FAILED(V_UNKNOWN(toValidate)->QueryInterface<IEnumVARIANT>(&enumVariant));
// Implementation of IDispatchTesting should return [0,9]
ValidateExpectedEnumVariant(enumVariant, 0, 10);
THROW_IF_FAILED(enumVariant->Reset());
ValidateExpectedEnumVariant(enumVariant, 0, 10);
THROW_IF_FAILED(enumVariant->Reset());
THROW_IF_FAILED(enumVariant->Skip(3));
ValidateExpectedEnumVariant(enumVariant, 3, 7);
}
}
void Validate_Enumerator()
{
HRESULT hr;
CoreShimComActivation csact{ W("NETServer"), W("DispatchTesting") };
ComSmartPtr<IDispatchTesting> dispatchTesting;
THROW_IF_FAILED(::CoCreateInstance(CLSID_DispatchTesting, nullptr, CLSCTX_INPROC, IID_IDispatchTesting, (void**)&dispatchTesting));
LCID lcid = MAKELCID(LANG_USER_DEFAULT, SORT_DEFAULT);
::printf("Invoke GetEnumerator (DISPID_NEWENUM)\n");
DISPPARAMS params {};
VARIANT result;
THROW_IF_FAILED(dispatchTesting->Invoke(
DISPID_NEWENUM,
IID_NULL,
lcid,
DISPATCH_METHOD,
¶ms,
&result,
nullptr,
nullptr
));
::printf(" -- Validate returned IEnumVARIANT\n");
ValidateReturnedEnumerator(&result);
LPOLESTR methodName = (LPOLESTR)W("ExplicitGetEnumerator");
::wprintf(W("Invoke %s\n"), methodName);
DISPID methodId;
THROW_IF_FAILED(dispatchTesting->GetIDsOfNames(
IID_NULL,
&methodName,
1,
lcid,
&methodId));
::VariantClear(&result);
THROW_IF_FAILED(dispatchTesting->Invoke(
methodId,
IID_NULL,
lcid,
DISPATCH_METHOD,
¶ms,
&result,
nullptr,
nullptr
));
::printf(" -- Validate returned IEnumVARIANT\n");
ValidateReturnedEnumerator(&result);
}
| 27.044118 | 135 | 0.642741 | AustinWise |
36c0d750124fa417c4cb5eb3691658d7aaa511ad | 1,867 | cpp | C++ | src/c/schemas/ModioQueuedModUpload.cpp | nlspartanNL/SDK | 291f1e5869210baedbb5447f8f7388f50ec93950 | [
"MIT"
] | 1 | 2018-10-05T15:59:04.000Z | 2018-10-05T15:59:04.000Z | src/c/schemas/ModioQueuedModUpload.cpp | nlspartanNL/SDK | 291f1e5869210baedbb5447f8f7388f50ec93950 | [
"MIT"
] | null | null | null | src/c/schemas/ModioQueuedModUpload.cpp | nlspartanNL/SDK | 291f1e5869210baedbb5447f8f7388f50ec93950 | [
"MIT"
] | 1 | 2020-11-06T01:42:10.000Z | 2020-11-06T01:42:10.000Z | #include "c/schemas/ModioQueuedModfileUpload.h"
extern "C"
{
void modioInitQueuedModfileUpload(ModioQueuedModfileUpload* queued_modfile_upload, nlohmann::json queued_modfile_upload_json)
{
queued_modfile_upload->state = 0;
if(modio::hasKey(queued_modfile_upload_json, "state"))
queued_modfile_upload->state = queued_modfile_upload_json["state"];
queued_modfile_upload->mod_id = 0;
if(modio::hasKey(queued_modfile_upload_json, "mod_id"))
queued_modfile_upload->mod_id = queued_modfile_upload_json["mod_id"];
queued_modfile_upload->current_progress = 0;
if(modio::hasKey(queued_modfile_upload_json, "current_progress"))
queued_modfile_upload->current_progress = queued_modfile_upload_json["current_progress"];
queued_modfile_upload->total_size = 0;
if(modio::hasKey(queued_modfile_upload_json, "total_size"))
queued_modfile_upload->total_size = queued_modfile_upload_json["total_size"];
queued_modfile_upload->path = NULL;
if(modio::hasKey(queued_modfile_upload_json, "path"))
{
std::string path_str = queued_modfile_upload_json["path"];
queued_modfile_upload->path = new char[path_str.size() + 1];
strcpy(queued_modfile_upload->path, path_str.c_str());
}
nlohmann::json modfile_creator_json;
if(modio::hasKey(queued_modfile_upload_json, "modfile_creator"))
modfile_creator_json = queued_modfile_upload_json["modfile_creator"];
modio::modioInitModfileCreatorFromJson(&(queued_modfile_upload->modio_modfile_creator), modfile_creator_json);
}
void modioFreeQueuedModfileUpload(ModioQueuedModfileUpload* queued_modfile_upload)
{
if(queued_modfile_upload)
{
if(queued_modfile_upload->path)
delete[] queued_modfile_upload->path;
modioFreeModfileCreator(&(queued_modfile_upload->modio_modfile_creator));
}
}
}
| 39.723404 | 127 | 0.759507 | nlspartanNL |
36cc78ba0d78273057473ace90f77d999ab85a18 | 1,667 | cpp | C++ | src/math/beta_distribution.cpp | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 3 | 2020-03-05T23:56:14.000Z | 2021-02-17T19:06:50.000Z | src/math/beta_distribution.cpp | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 1 | 2021-03-07T01:23:47.000Z | 2021-03-07T01:23:47.000Z | src/math/beta_distribution.cpp | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 1 | 2021-03-03T07:54:16.000Z | 2021-03-03T07:54:16.000Z | /* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
/**
* \file beta_distribution.cpp
* \author Collin Johnson
*
* Definition of BetaDistribution.
*/
#include "math/beta_distribution.h"
#include <boost/math/special_functions/beta.hpp>
#include <cassert>
#include <iostream>
namespace vulcan
{
namespace math
{
double beta_normalizer(double alpha, double beta)
{
return 1.0 / boost::math::beta(alpha, beta);
}
BetaDistribution::BetaDistribution(double alpha, double beta)
: alpha_(alpha)
, beta_(beta)
, normalizer_(beta_normalizer(alpha_, beta_))
{
assert(alpha_ >= 0.0);
assert(beta_ >= 0.0);
}
double BetaDistribution::sample(void) const
{
std::cout << "STUB: BetaDistribution::sample(void)\n";
return 0.0;
}
double BetaDistribution::likelihood(double value) const
{
if ((value <= 0.0) || (value >= 1.0)) {
return 0.0;
}
return std::pow(value, alpha_ - 1.0) * std::pow(1.0 - value, beta_ - 1.0) * normalizer_;
}
bool BetaDistribution::save(std::ostream& out) const
{
out << alpha_ << ' ' << beta_ << '\n';
return out.good();
}
bool BetaDistribution::load(std::istream& in)
{
in >> alpha_ >> beta_;
assert(alpha_ >= 0.0);
assert(beta_ >= 0.0);
normalizer_ = beta_normalizer(alpha_, beta_);
return in.good();
}
} // namespace math
} // namespace vulcan
| 20.580247 | 95 | 0.671866 | anuranbaka |
36ce5a4e30f29ea685c39d972b15f9df4e4279a2 | 637 | cpp | C++ | File Handlers/CHK/Sections/CHKSectionTECS.cpp | poiuyqwert/SCMS | 8aa5f90a8f4caf1db489614fdbd5fb2decf783d7 | [
"MIT"
] | null | null | null | File Handlers/CHK/Sections/CHKSectionTECS.cpp | poiuyqwert/SCMS | 8aa5f90a8f4caf1db489614fdbd5fb2decf783d7 | [
"MIT"
] | null | null | null | File Handlers/CHK/Sections/CHKSectionTECS.cpp | poiuyqwert/SCMS | 8aa5f90a8f4caf1db489614fdbd5fb2decf783d7 | [
"MIT"
] | null | null | null | //
// CHKSectionTECS.cpp
// SCMS
//
// Created by Zach Zahos on 2016-01-04.
//
//
#include "CHKSectionTECS.h"
#include <string>
const CHKRequirements CHKSectionTECS::Requirements = {CHKVer::VanillaHybrid, CHKGameMode::UseMapSettings};
CHKSectionTECS::CHKSectionTECS(CHK *chk)
: CHKSection(chk)
{
#warning COMPLEX DEFAULTS
}
void CHKSectionTECS::load_data(const u8 *data, u32 size) {
memcpy(&this->technology, data, sizeof(CHKSectionTECS::technology));
}
u8* CHKSectionTECS::save_data(u32 &size) {
size = sizeof(CHKSectionTECS::technology);
u8 *buffer = new u8[size];
memcpy(buffer, &this->technology, size);
return buffer;
}
| 22.75 | 106 | 0.733124 | poiuyqwert |
36d078ed379ae6ed4740bb4c58bf1e6e18544f18 | 1,380 | cpp | C++ | random/random.cpp | fjanisze/UnnamedGame | 572e9c504a2242f77d375ad220b3c881cffc8ce2 | [
"MIT"
] | null | null | null | random/random.cpp | fjanisze/UnnamedGame | 572e9c504a2242f77d375ad220b3c881cffc8ce2 | [
"MIT"
] | null | null | null | random/random.cpp | fjanisze/UnnamedGame | 572e9c504a2242f77d375ad220b3c881cffc8ce2 | [
"MIT"
] | null | null | null | #include "random.hpp"
#include "../logger/logger.hpp"
#include <limits>
namespace random_engine
{
random::random():
eng(rd()),
dist(std::numeric_limits<llong>::min(),
std::numeric_limits<llong>::max())
{
LOG3("Starting the game random engine.");
llong_randoms.reserve(random_numbers_limis);
ldouble_randoms.reserve(random_numbers_limis);
//Setting this index to 0 means that we have no
//more random numbers available now.
llong_randoms_idx = 0;
ldouble_randoms_idx = 0;
generate();
}
void random::generate()
{
while(llong_randoms_idx < random_numbers_limis - 1){
llong_randoms[llong_randoms_idx++] = dist(eng);
}
while(ldouble_randoms_idx < random_numbers_limis - 1){
ldouble_randoms[ldouble_randoms_idx++] = std::generate_canonical<ldouble,10>(eng);
}
LOG1("Random data, llong:",llong_randoms_idx,
", ldouble:",ldouble_queue.size());
}
llong random::get_llong()
{
if(llong_randoms_idx == 0)
generate();
return llong_randoms[llong_randoms_idx--];
}
std::pair<llong, llong> random::get_llong_pair()
{
if(llong_randoms_idx < 2)
generate();
//To avoid the "multiple unsequenced warning"
llong_randoms_idx -= 2;
return std::make_pair(llong_randoms[llong_randoms_idx + 1],
llong_randoms[llong_randoms_idx + 2]);
}
}
| 25.090909 | 90 | 0.667391 | fjanisze |
36d3bc77c953af9b6ee032afc175f8acb5f2ab53 | 5,925 | inl | C++ | External/gli/core/image.inl | SuperflyJon/VulkanPlayground | 891b88227b66fc1e933ff77c1603e5d685d89047 | [
"MIT"
] | 2 | 2021-01-25T16:59:56.000Z | 2021-02-14T21:11:05.000Z | External/gli/core/image.inl | SuperflyJon/VulkanPlayground | 891b88227b66fc1e933ff77c1603e5d685d89047 | [
"MIT"
] | null | null | null | External/gli/core/image.inl | SuperflyJon/VulkanPlayground | 891b88227b66fc1e933ff77c1603e5d685d89047 | [
"MIT"
] | 1 | 2021-04-23T10:20:53.000Z | 2021-04-23T10:20:53.000Z | namespace gli{
namespace detail
{
inline size_t texel_linear_aAdressing
(
extent1d const& Extent,
extent1d const& TexelCoord
)
{
GLI_ASSERT(glm::all(glm::lessThan(TexelCoord, Extent)));
return static_cast<size_t>(TexelCoord.x);
}
inline size_t texel_linear_adressing
(
extent2d const& Extent,
extent2d const& TexelCoord
)
{
GLI_ASSERT(TexelCoord.x < Extent.x);
GLI_ASSERT(TexelCoord.y < Extent.y);
return static_cast<size_t>(TexelCoord.x + Extent.x * TexelCoord.y);
}
inline size_t texel_linear_adressing
(
extent3d const& Extent,
extent3d const& TexelCoord
)
{
GLI_ASSERT(TexelCoord.x < Extent.x);
GLI_ASSERT(TexelCoord.y < Extent.y);
GLI_ASSERT(TexelCoord.z < Extent.z);
return static_cast<size_t>(TexelCoord.x + Extent.x * (TexelCoord.y + Extent.y * TexelCoord.z));
}
inline size_t texel_morton_adressing
(
extent1d const& Extent,
extent1d const& TexelCoord
)
{
GLI_ASSERT(TexelCoord.x < Extent.x);
return TexelCoord.x;
}
inline size_t texel_morton_adressing
(
extent2d const& Extent,
extent2d const& TexelCoord
)
{
GLI_ASSERT(TexelCoord.x < Extent.x && TexelCoord.x >= 0 && TexelCoord.x < std::numeric_limits<extent2d::value_type>::max());
GLI_ASSERT(TexelCoord.y < Extent.y && TexelCoord.y >= 0 && TexelCoord.y < std::numeric_limits<extent2d::value_type>::max());
glm::u32vec2 const Input(TexelCoord);
return static_cast<size_t>(glm::bitfieldInterleave(Input.x, Input.y));
}
inline size_t texel_morton_adressing
(
extent3d const& Extent,
extent3d const& TexelCoord
)
{
GLI_ASSERT(TexelCoord.x < Extent.x);
GLI_ASSERT(TexelCoord.y < Extent.y);
GLI_ASSERT(TexelCoord.z < Extent.z);
glm::u32vec3 const Input(TexelCoord);
return static_cast<size_t>(glm::bitfieldInterleave(Input.x, Input.y, Input.z));
}
}//namespace detail
inline image::image()
: Format(static_cast<gli::format>(FORMAT_INVALID))
, BaseLevel(0)
, Data(nullptr)
, Size(0)
{}
inline image::image
(
format_type Format,
extent_type const& Extent
)
: Storage(std::make_shared<storage_linear>(Format, Extent, 1, 1, 1))
, Format(Format)
, BaseLevel(0)
, Data(Storage->data())
, Size(compute_size(0))
{}
inline image::image
(
std::shared_ptr<storage_linear> Storage,
format_type Format,
size_type BaseLayer,
size_type BaseFace,
size_type BaseLevel
)
: Storage(Storage)
, Format(Format)
, BaseLevel(BaseLevel)
, Data(compute_data(BaseLayer, BaseFace, BaseLevel))
, Size(compute_size(BaseLevel))
{}
inline image::image
(
image const & Image,
format_type Format
)
: Storage(Image.Storage)
, Format(Format)
, BaseLevel(Image.BaseLevel)
, Data(Image.Data)
, Size(Image.Size)
{
GLI_ASSERT(block_size(Format) == block_size(Image.format()));
}
inline bool image::empty() const
{
if(this->Storage.get() == nullptr)
return true;
return this->Storage->empty();
}
inline image::size_type image::size() const
{
GLI_ASSERT(!this->empty());
return this->Size;
}
template <typename genType>
inline image::size_type image::size() const
{
GLI_ASSERT(sizeof(genType) <= this->Storage->block_size());
return this->size() / sizeof(genType);
}
inline image::format_type image::format() const
{
return this->Format;
}
inline image::extent_type image::extent() const
{
GLI_ASSERT(!this->empty());
storage_linear::extent_type const& SrcExtent = this->Storage->extent(this->BaseLevel);
storage_linear::extent_type const& DstExtent = SrcExtent * block_extent(this->format()) / this->Storage->block_extent();
return glm::max(DstExtent, storage_linear::extent_type(1));
}
inline void* image::data()
{
GLI_ASSERT(!this->empty());
return this->Data;
}
inline void const* image::data() const
{
GLI_ASSERT(!this->empty());
return this->Data;
}
template <typename genType>
inline genType* image::data()
{
GLI_ASSERT(!this->empty());
GLI_ASSERT(this->Storage->block_size() >= sizeof(genType));
return reinterpret_cast<genType *>(this->data());
}
template <typename genType>
inline genType const* image::data() const
{
GLI_ASSERT(!this->empty());
GLI_ASSERT(this->Storage->block_size() >= sizeof(genType));
return reinterpret_cast<genType const *>(this->data());
}
inline void image::clear()
{
GLI_ASSERT(!this->empty());
memset(this->data<glm::byte>(), 0, this->size<glm::byte>());
}
template <typename genType>
inline void image::clear(genType const& Texel)
{
GLI_ASSERT(!this->empty());
GLI_ASSERT(this->Storage->block_size() == sizeof(genType));
for(size_type TexelIndex = 0; TexelIndex < this->size<genType>(); ++TexelIndex)
*(this->data<genType>() + TexelIndex) = Texel;
}
inline image::data_type* image::compute_data(size_type BaseLayer, size_type BaseFace, size_type BaseLevelX)
{
size_type const BaseOffset = this->Storage->base_offset(BaseLayer, BaseFace, BaseLevelX);
return this->Storage->data() + BaseOffset;
}
inline image::size_type image::compute_size(size_type Level) const
{
GLI_ASSERT(!this->empty());
return this->Storage->level_size(Level);
}
template <typename genType>
genType image::load(extent_type const& TexelCoord)
{
GLI_ASSERT(!this->empty());
GLI_ASSERT(!is_compressed(this->format()));
GLI_ASSERT(this->Storage->block_size() == sizeof(genType));
GLI_ASSERT(glm::all(glm::lessThan(TexelCoord, this->extent())));
return *(this->data<genType>() + detail::texel_linear_adressing(this->extent(), TexelCoord));
}
template <typename genType>
void image::store(extent_type const& TexelCoord, genType const& Data)
{
GLI_ASSERT(!this->empty());
GLI_ASSERT(!is_compressed(this->format()));
GLI_ASSERT(this->Storage->block_size() == sizeof(genType));
GLI_ASSERT(glm::all(glm::lessThan(TexelCoord, this->extent())));
*(this->data<genType>() + detail::texel_linear_adressing(this->extent(), TexelCoord)) = Data;
}
}//namespace gli
| 23.511905 | 126 | 0.700591 | SuperflyJon |
36d8eab4e8d10f87e5ec91b0cdea644557f797fc | 384 | cpp | C++ | src/pin.cpp | glehmann/gpedal | 6226fe2ff275e910f49f44f2b644569ab71a8910 | [
"Apache-2.0"
] | null | null | null | src/pin.cpp | glehmann/gpedal | 6226fe2ff275e910f49f44f2b644569ab71a8910 | [
"Apache-2.0"
] | null | null | null | src/pin.cpp | glehmann/gpedal | 6226fe2ff275e910f49f44f2b644569ab71a8910 | [
"Apache-2.0"
] | 1 | 2021-04-03T18:00:58.000Z | 2021-04-03T18:00:58.000Z | #include "pin.h"
#include <Arduino.h>
#include <Wire.h>
void pin_setup() {
// no need for 12 bits resolution - the usual 10 bits is more than enough
// and much more stable
analogReadResolution(10);
// activate other boards and power button led
pinMode(PIN_STATUS, OUTPUT);
digitalWrite(PIN_STATUS, HIGH);
// setup i2c
Wire.begin(PIN_SDA, PIN_SCL);
}
| 25.6 | 77 | 0.679688 | glehmann |
36d9b8d45aaf7eb16cb6f8e35d253d3dba4a3d02 | 2,007 | cpp | C++ | bfloat/arithmetic/bfloat_subtract.cpp | mrdcvlsc/bignum | 7e3b03069495e7f2151d25d5f62c35075f9b6a7f | [
"MIT"
] | 8 | 2020-11-17T02:12:14.000Z | 2021-08-09T02:02:13.000Z | bfloat/arithmetic/bfloat_subtract.cpp | mrdcvlsc/bignum | 7e3b03069495e7f2151d25d5f62c35075f9b6a7f | [
"MIT"
] | 2 | 2020-12-03T05:43:51.000Z | 2021-01-16T14:15:25.000Z | bfloat/arithmetic/bfloat_subtract.cpp | mrdcvlsc/bignum | 7e3b03069495e7f2151d25d5f62c35075f9b6a7f | [
"MIT"
] | 2 | 2021-01-13T05:23:27.000Z | 2021-02-10T04:38:32.000Z | #ifndef BFLOAT_SUBTRACT_HPP
#define BFLOAT_SUBTRACT_HPP
#include <iostream>
#include "../bfloat.hpp"
namespace apa
{
bfloat bfloat::operator-(const bfloat& rhs) const
{
bfloat difference = *this;
difference-=rhs;
return difference;
}
bfloat& bfloat::operator-=(const bfloat& rhs)
{
bool same_sign = this->sign==rhs.sign;
bool pos_minuend = (this->sign)>=0;
bool minuendIsMax = *this>rhs;
int comp = floatlimbs.compare(rhs.floatlimbs);
if(same_sign)
{
if(comp==0)
{
sign = 1;
floatlimbs.limbs.clear();
floatlimbs.limbs.push_back(0);
floatlimbs.limbs.push_back(0);
floatlimbs.decimal_point = 1;
return *this;
}
else if(pos_minuend)
{
if(minuendIsMax)
{
this->floatlimbs -= rhs.floatlimbs;
this->sign = 1;
return *this;
}
this->floatlimbs = rhs.floatlimbs-this->floatlimbs;
this->sign = -1;
return *this;
}
else if(!pos_minuend)
{
if(minuendIsMax)
{
this->floatlimbs = rhs.floatlimbs-this->floatlimbs;
this->sign = 1;
return *this;
}
this->floatlimbs -= rhs.floatlimbs;
this->sign = (-1);
return *this;
}
}
else
{
this->floatlimbs += rhs.floatlimbs;
if(*this<rhs)
{
this->sign = -1;
return *this;
}
this->sign = 1;
return *this;
}
sign = 1;
floatlimbs.limbs.clear();
floatlimbs.limbs.push_back(0);
return *this;
}
}
#endif | 25.0875 | 71 | 0.433981 | mrdcvlsc |
36dcb324fd4507aa05b0170714674ba05f46bd79 | 1,497 | cpp | C++ | Game/src/RenderList.cpp | realn/exptor3D | 85bafa0a4c59eb15102756046805e4f9b23245c2 | [
"MIT"
] | null | null | null | Game/src/RenderList.cpp | realn/exptor3D | 85bafa0a4c59eb15102756046805e4f9b23245c2 | [
"MIT"
] | null | null | null | Game/src/RenderList.cpp | realn/exptor3D | 85bafa0a4c59eb15102756046805e4f9b23245c2 | [
"MIT"
] | null | null | null | #include "RenderList.h"
CRenderList::CRenderList( gfx::TextureRepository& texManager, gfx::ModelManager& modelManager ) :
TexManager( texManager ),
ModelManager( modelManager )
{
}
void CRenderList::Add( IRenderable* pObj )
{
if( std::find( List.cbegin(), List.cend(), pObj ) == List.cend() )
{
List.push_back( pObj );
if( !pObj->IsGfxLoaded() )
AddToLoad( pObj );
}
}
void CRenderList::Remove( IRenderable* pObj )
{
auto it = std::find( List.cbegin(), List.cend(), pObj );
if( it != List.cend() )
List.erase( it );
}
void CRenderList::PreLoad()
{
if( ToLoad.empty() )
return;
for( unsigned i = 0; i < ToLoad.size(); i++ )
{
ToLoad[i]->LoadGraphic( TexManager, ModelManager );
}
ToLoad.clear();
}
void CRenderList::Sort()
{
SolidList.clear();
TransparentList.clear();
for( unsigned i = 0; i < List.size(); i++ )
{
if( !List[i]->IsVisible() )
continue;
if( !List[i]->IsGfxLoaded() )
{
AddToLoad( List[i] );
continue;
}
if( List[i]->IsTransparent() )
TransparentList.push_back( List[i] );
else
SolidList.push_back( List[i] );
}
}
void CRenderList::Render(const bool solid)
{
if( solid )
{
for( unsigned i = 0; i < SolidList.size(); i++ )
SolidList[i]->Render();
}
else
{
for( unsigned i = 0; i < TransparentList.size(); i++ )
TransparentList[i]->Render();
}
}
void CRenderList::AddToLoad( IRenderable* pObj )
{
if( std::find( ToLoad.cbegin(), ToLoad.cend(), pObj ) == ToLoad.cend() )
ToLoad.push_back( pObj );
} | 18.7125 | 97 | 0.625251 | realn |
36e32eef0c078316a8af99b2a49b199a5329a7f0 | 293 | hpp | C++ | src/Elliptic/DiscontinuousGalerkin/DiscontinuousGalerkin.hpp | trami18/spectre | 6b1f6497bf2e26d1474bfadf143b3321942c40b4 | [
"MIT"
] | 2 | 2021-04-11T04:07:42.000Z | 2021-04-11T05:07:54.000Z | src/Elliptic/DiscontinuousGalerkin/DiscontinuousGalerkin.hpp | trami18/spectre | 6b1f6497bf2e26d1474bfadf143b3321942c40b4 | [
"MIT"
] | 1 | 2022-03-25T18:26:16.000Z | 2022-03-25T19:30:39.000Z | src/Elliptic/DiscontinuousGalerkin/DiscontinuousGalerkin.hpp | isaaclegred/spectre | 5765da85dad680cad992daccd479376c67458a8c | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
/// \file
/// Documents the elliptic::dg namespace
#pragma once
namespace elliptic {
/// Functionality related to discontinuous Galerkin discretizations of elliptic
/// equations
namespace dg {}
} // namespace elliptic
| 20.928571 | 79 | 0.74744 | trami18 |
36e4da6036375fbb6bfe5c6a9f7f5ac8407dcd79 | 53 | tpp | C++ | examples/imp1/ns1.tpp | kobbled/vscode-tpp-extension | fc787694845b913ff09ce1abc4eb92142a7f6e7d | [
"MIT"
] | 1 | 2021-12-20T20:48:10.000Z | 2021-12-20T20:48:10.000Z | examples/imp1/ns1.tpp | kobbled/vscode-tpp-extension | fc787694845b913ff09ce1abc4eb92142a7f6e7d | [
"MIT"
] | null | null | null | examples/imp1/ns1.tpp | kobbled/vscode-tpp-extension | fc787694845b913ff09ce1abc4eb92142a7f6e7d | [
"MIT"
] | 2 | 2021-07-12T07:02:19.000Z | 2021-09-30T14:09:09.000Z | namespace ns1
CONST1 := 3.14
CONST2 := 2.7182
end | 13.25 | 18 | 0.660377 | kobbled |
36e774e1b7301cb17816e80c8474b1e555717e5c | 467 | cpp | C++ | Difficulty 1/friday.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | Difficulty 1/friday.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | Difficulty 1/friday.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
int T, D, M, month, day, ft;
cin >> T;
for(int i = 0; i < T; i++) {
cin >> D >> M;
day = 0;
ft = 0;
for (int j = 0; j < M; j++) {
cin >> month;
for (int k = 0; k < month; k++) {
if (day == 5 && k == 12) ft++;
day++;
day %= 7;
}
}
cout << ft << endl;
}
} | 20.304348 | 46 | 0.308351 | BrynjarGeir |
36ee6774b09b5d7f2134dcd1c83c9be0a8bca458 | 1,870 | cpp | C++ | DP/adding.cpp | zyzkevin/C-Programming-and-Algorithms | be9642b62a3285341990c25bdc3c124c4dd8c38b | [
"MIT"
] | null | null | null | DP/adding.cpp | zyzkevin/C-Programming-and-Algorithms | be9642b62a3285341990c25bdc3c124c4dd8c38b | [
"MIT"
] | null | null | null | DP/adding.cpp | zyzkevin/C-Programming-and-Algorithms | be9642b62a3285341990c25bdc3c124c4dd8c38b | [
"MIT"
] | null | null | null | /*
张雨泽1900094801
B:最佳加法表达式
2020/05/19
*/
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
string sum (string a, string b)
{
string tmp;
int flag = 0;
int al = a.length(), bl = b.length();
for (int i = al - 1, j = bl - 1; i >= 0 || j >= 0; i--, j--)
{
//moving all digits right
tmp = " " + tmp;
int sum1 = 0, sum2 = 0;
if(i >= 0)
sum1 = a[i] - '0';
if( j >= 0)
sum2 = b[j] - '0';
tmp[0] = sum1 + sum2 + flag;
if( tmp[0] >= 10) {
flag = 1; tmp[0] = tmp[0] - 10;
}else {
flag = 0;
}
tmp[0] = tmp[0] + '0';
}
//last flag needs to be seperately added
if(flag)
tmp = '1' + tmp;
return tmp;
}
string mymin ( string a, string b)
{
if( a.length() == b.length())
return a < b ? a: b;
return a.length() < b.length() ? a : b;
}
int main()
{
string dp[65][60]; //min of x numbers insert y plus signs
string a;
//cout << sum(string("9999"), string("44"));
int m;
while(cin >> m)
{
cin >> a;
a= " " + a;
//memset(dp, 0, sizeof(dp));
int len = a.length();
for( int i = 0; i <= len; i++)
dp[i][0] = a.substr(1, i);
for( int i = 1; i <= m; i++)
for( int j = i + 1 ; j <= len; j++ )
for( int k = i; k < j; k++)
{
if(k == i) //no choice but to place + before second to last digit and add everything that's later.
dp[j][i] = sum( dp[k][ i - 1], a.substr( k + 1,j - k));
else
dp[j][i] = mymin( dp[j][i], sum(dp[k][i - 1], a.substr(k + 1, j - k)));
}
cout << dp[len][m]<< endl;
}
system("pause");
return 0;
} | 23.974359 | 119 | 0.409626 | zyzkevin |
36f8dcaeb7b0a04c3aaf8e1df43f84e428f2274c | 7,010 | cpp | C++ | src/effects/Echo.cpp | gspeedtech/Audacity | 570c5651c5934469c18dad25db03f05076f91225 | [
"CC-BY-3.0"
] | 16 | 2015-01-26T18:58:26.000Z | 2017-11-12T05:42:58.000Z | src/effects/Echo.cpp | gspeedtech/Audacity | 570c5651c5934469c18dad25db03f05076f91225 | [
"CC-BY-3.0"
] | null | null | null | src/effects/Echo.cpp | gspeedtech/Audacity | 570c5651c5934469c18dad25db03f05076f91225 | [
"CC-BY-3.0"
] | 7 | 2015-04-13T20:01:00.000Z | 2021-07-05T09:28:22.000Z | /**********************************************************************
Audacity: A Digital Audio Editor
Echo.cpp
Dominic Mazzoni
Vaughan Johnson (dialog)
*******************************************************************//**
\class EffectEcho
\brief An Effect that causes an echo, variable delay and volume.
*//****************************************************************//**
\class EchoDialog
\brief EchoDialog used with EffectEcho
*//*******************************************************************/
#include "../Audacity.h"
#include <wx/defs.h>
#include <wx/button.h>
#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/textctrl.h>
#include <wx/validate.h>
#include <wx/valtext.h>
#include <wx/generic/textdlgg.h>
#include <wx/intl.h>
#include <math.h>
#include "Echo.h"
#include "../WaveTrack.h"
EffectEcho::EffectEcho()
{
delay = float(1.0);
decay = float(0.5);
}
wxString EffectEcho::GetEffectDescription() {
// Note: This is useful only after values have been set.
return wxString::Format(_("Applied effect: %s delay = %f seconds, decay factor = %f"),
this->GetEffectName().c_str(), delay, decay);
}
bool EffectEcho::PromptUser()
{
EchoDialog dlog(this, mParent);
dlog.delay = delay;
dlog.decay = decay;
dlog.CentreOnParent();
dlog.ShowModal();
if (dlog.GetReturnCode() == wxID_CANCEL)
return false;
delay = dlog.delay;
decay = dlog.decay;
return true;
}
bool EffectEcho::TransferParameters( Shuttle & shuttle )
{
shuttle.TransferFloat(wxT("Delay"),delay,1.0);
shuttle.TransferFloat(wxT("Decay"),decay,0.5);
return true;
}
bool EffectEcho::Process()
{
this->CopyInputTracks(); // Set up mOutputTracks.
bool bGoodResult = true;
SelectedTrackListOfKindIterator iter(Track::Wave, mOutputTracks);
WaveTrack *track = (WaveTrack *) iter.First();
int count = 0;
while (track) {
double trackStart = track->GetStartTime();
double trackEnd = track->GetEndTime();
double t0 = mT0 < trackStart? trackStart: mT0;
double t1 = mT1 > trackEnd? trackEnd: mT1;
if (t1 > t0) {
sampleCount start = track->TimeToLongSamples(t0);
sampleCount end = track->TimeToLongSamples(t1);
sampleCount len = (sampleCount)(end - start);
if (!ProcessOne(count, track, start, len))
{
bGoodResult = false;
break;
}
}
track = (WaveTrack *) iter.Next();
count++;
}
this->ReplaceProcessedTracks(bGoodResult);
return bGoodResult;
}
bool EffectEcho::ProcessOne(int count, WaveTrack * track,
sampleCount start, sampleCount len)
{
sampleCount s = 0;
sampleCount blockSize = (sampleCount) (track->GetRate() * delay);
//do nothing if the delay is less than 1 sample or greater than
//the length of the selection
if (blockSize < 1 || blockSize > len)
return true;
float *buffer0 = new float[blockSize];
float *buffer1 = new float[blockSize];
float *ptr0 = buffer0;
float *ptr1 = buffer1;
bool first = true;
while (s < len) {
sampleCount block = blockSize;
if (s + block > len)
block = len - s;
track->Get((samplePtr)ptr0, floatSample, start + s, block);
if (!first) {
for (sampleCount i = 0; i < block; i++)
ptr0[i] += ptr1[i] * decay;
track->Set((samplePtr)ptr0, floatSample, start + s, block);
}
float *ptrtemp = ptr0;
ptr0 = ptr1;
ptr1 = ptrtemp;
first = false;
s += block;
if (TrackProgress(count, s / (double) len)) {
delete[]buffer0;
delete[]buffer1;
return false;
}
}
delete[]buffer0;
delete[]buffer1;
return true;
}
//----------------------------------------------------------------------------
// EchoDialog
//----------------------------------------------------------------------------
// event table for EchoDialog
BEGIN_EVENT_TABLE(EchoDialog, EffectDialog)
EVT_BUTTON(ID_EFFECT_PREVIEW, EchoDialog::OnPreview)
END_EVENT_TABLE()
EchoDialog::EchoDialog(EffectEcho * effect, wxWindow * parent)
: EffectDialog(parent, _("Echo"))
{
m_bLoopDetect = false;
m_pEffect = effect;
// NULL out these control members because there are some cases where the
// event table handlers get called during this method, and those handlers that
// can cause trouble check for NULL.
m_pTextCtrl_Delay = NULL;
m_pTextCtrl_Decay = NULL;
// effect parameters
delay = float(1.0);
decay = float(0.5);
// Initialize dialog
Init();
}
void EchoDialog::PopulateOrExchange(ShuttleGui & S)
{
S.StartHorizontalLay(wxCENTER, false);
{
/* i18n-hint: && in here is an escape character to get a single & on
* screen, so keep it as is */
S.AddTitle(_("by Dominic Mazzoni && Vaughan Johnson"));
}
S.EndHorizontalLay();
S.StartHorizontalLay(wxCENTER, false);
{
// Add a little space
}
S.EndHorizontalLay();
S.StartMultiColumn(2, wxALIGN_CENTER);
{
m_pTextCtrl_Delay = S.AddTextBox(_("Delay time (seconds):"),
wxT("1.0"),
10);
m_pTextCtrl_Delay->SetValidator(wxTextValidator(wxFILTER_NUMERIC));
m_pTextCtrl_Decay = S.AddTextBox(_("Decay factor:"),
wxT("0.5"),
10);
m_pTextCtrl_Decay->SetValidator(wxTextValidator(wxFILTER_NUMERIC));
}
S.EndMultiColumn();
}
bool EchoDialog::TransferDataToWindow()
{
m_bLoopDetect = true;
wxString str;
if (m_pTextCtrl_Delay) {
str.Printf(wxT("%g"), delay);
m_pTextCtrl_Delay->SetValue(str);
}
if (m_pTextCtrl_Decay) {
str.Printf(wxT("%g"), decay);
m_pTextCtrl_Decay->SetValue(str);
}
m_bLoopDetect = false;
return true;
}
bool EchoDialog::TransferDataFromWindow()
{
double newValue;
wxString str;
if (m_pTextCtrl_Delay) {
str = m_pTextCtrl_Delay->GetValue();
str.ToDouble(&newValue);
delay = (float)(newValue);
}
if (m_pTextCtrl_Decay) {
str = m_pTextCtrl_Decay->GetValue();
str.ToDouble(&newValue);
decay = (float)(newValue);
}
return true;
}
// handler implementations for EchoDialog
void EchoDialog::OnPreview(wxCommandEvent &event)
{
TransferDataFromWindow();
// Save & restore parameters around Preview, because we didn't do OK.
float oldDelay = m_pEffect->delay;
float oldDecay = m_pEffect->decay;
m_pEffect->delay = delay;
m_pEffect->decay = decay;
m_pEffect->Preview();
m_pEffect->delay = oldDelay;
m_pEffect->decay = oldDecay;
}
// Indentation settings for Vim and Emacs and unique identifier for Arch, a
// version control system. Please do not modify past this point.
//
// Local Variables:
// c-basic-offset: 3
// indent-tabs-mode: nil
// End:
//
// vim: et sts=3 sw=3
// arch-tag: 1c174e3a-7748-4045-8066-b394189a7ba7
| 24.256055 | 90 | 0.592582 | gspeedtech |
36ff9ab5c339f1f7e1f85d60a823fdcd31e43b1d | 993 | cpp | C++ | android-31/android/text/method/DialerKeyListener.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/text/method/DialerKeyListener.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/android/text/method/DialerKeyListener.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../../JCharArray.hpp"
#include "../../view/KeyEvent.hpp"
#include "./DialerKeyListener.hpp"
namespace android::text::method
{
// Fields
JCharArray DialerKeyListener::CHARACTERS()
{
return getStaticObjectField(
"android.text.method.DialerKeyListener",
"CHARACTERS",
"[C"
);
}
// QJniObject forward
DialerKeyListener::DialerKeyListener(QJniObject obj) : android::text::method::NumberKeyListener(obj) {}
// Constructors
DialerKeyListener::DialerKeyListener()
: android::text::method::NumberKeyListener(
"android.text.method.DialerKeyListener",
"()V"
) {}
// Methods
android::text::method::DialerKeyListener DialerKeyListener::getInstance()
{
return callStaticObjectMethod(
"android.text.method.DialerKeyListener",
"getInstance",
"()Landroid/text/method/DialerKeyListener;"
);
}
jint DialerKeyListener::getInputType() const
{
return callMethod<jint>(
"getInputType",
"()I"
);
}
} // namespace android::text::method
| 22.066667 | 104 | 0.703927 | YJBeetle |
36ffc20c676389be161a2dce23b468ebdaac2f6e | 6,337 | cpp | C++ | Engine/Code/Engine/Renderer/DepthStencilState.cpp | cugone/Abrams2019 | 0b94c43275069275bbbeadfa773c336fa1947882 | [
"MIT"
] | 1 | 2020-07-14T06:58:50.000Z | 2020-07-14T06:58:50.000Z | Engine/Code/Engine/Renderer/DepthStencilState.cpp | cugone/Abrams2019 | 0b94c43275069275bbbeadfa773c336fa1947882 | [
"MIT"
] | 1 | 2020-04-06T06:52:11.000Z | 2020-04-06T06:52:19.000Z | Engine/Code/Engine/Renderer/DepthStencilState.cpp | cugone/Abrams2019 | 0b94c43275069275bbbeadfa773c336fa1947882 | [
"MIT"
] | 2 | 2019-05-01T21:49:33.000Z | 2021-04-01T08:22:21.000Z | #include "Engine/Renderer/DepthStencilState.hpp"
#include "Engine/Core/BuildConfig.hpp"
#include "Engine/Core/ErrorWarningAssert.hpp"
#include "Engine/RHI/RHIDevice.hpp"
#include "Engine/Renderer/DirectX/DX11.hpp"
#include <string>
void DepthStencilState::SetDebugName([[maybe_unused]] const std::string& name) const noexcept {
#ifdef RENDER_DEBUG
_dx_state->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<unsigned int>(name.size()), name.data());
#endif
}
DepthStencilState::DepthStencilState(const RHIDevice* device, const XMLElement& element) noexcept
: DepthStencilState(device, DepthStencilDesc{element}) {
/* DO NOTHING */
}
DepthStencilState::DepthStencilState(const RHIDevice* device, const DepthStencilDesc& desc) noexcept
: _desc(desc) {
if(!CreateDepthStencilState(device, desc)) {
if(_dx_state) {
_dx_state->Release();
_dx_state = nullptr;
}
ERROR_AND_DIE("DepthStencilState failed to create.");
}
}
DepthStencilState::~DepthStencilState() noexcept {
if(_dx_state) {
_dx_state->Release();
_dx_state = nullptr;
}
}
ID3D11DepthStencilState* DepthStencilState::GetDxDepthStencilState() const noexcept {
return _dx_state;
}
DepthStencilDesc DepthStencilState::GetDesc() const noexcept {
return _desc;
}
bool DepthStencilState::CreateDepthStencilState(const RHIDevice* device, const DepthStencilDesc& desc /*= DepthStencilDesc{}*/) noexcept {
D3D11_DEPTH_STENCIL_DESC dx_desc;
dx_desc.DepthEnable = desc.depth_enabled ? TRUE : FALSE;
dx_desc.DepthWriteMask = desc.depth_write ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
dx_desc.StencilEnable = desc.stencil_enabled ? TRUE : FALSE;
dx_desc.StencilReadMask = desc.stencil_read ? D3D11_DEFAULT_STENCIL_READ_MASK : 0x00;
dx_desc.StencilWriteMask = desc.stencil_write ? D3D11_DEFAULT_STENCIL_WRITE_MASK : 0x00;
dx_desc.DepthFunc = ComparisonFunctionToD3DComparisonFunction(desc.depth_comparison);
dx_desc.FrontFace.StencilFailOp = StencilOperationToD3DStencilOperation(desc.stencil_failFrontOp);
dx_desc.FrontFace.StencilDepthFailOp = StencilOperationToD3DStencilOperation(desc.stencil_failDepthFrontOp);
dx_desc.FrontFace.StencilFunc = ComparisonFunctionToD3DComparisonFunction(desc.stencil_testFront);
dx_desc.FrontFace.StencilPassOp = StencilOperationToD3DStencilOperation(desc.stencil_passFrontOp);
dx_desc.BackFace.StencilFailOp = StencilOperationToD3DStencilOperation(desc.stencil_failBackOp);
dx_desc.BackFace.StencilDepthFailOp = StencilOperationToD3DStencilOperation(desc.stencil_failDepthBackOp);
dx_desc.BackFace.StencilFunc = ComparisonFunctionToD3DComparisonFunction(desc.stencil_testBack);
dx_desc.BackFace.StencilPassOp = StencilOperationToD3DStencilOperation(desc.stencil_passBackOp);
HRESULT hr = device->GetDxDevice()->CreateDepthStencilState(&dx_desc, &_dx_state);
return SUCCEEDED(hr);
}
DepthStencilDesc::DepthStencilDesc(const XMLElement& element) noexcept {
if(const auto* xml_depth = element.FirstChildElement("depth")) {
DataUtils::ValidateXmlElement(*xml_depth, "depth", "", "", "", "enable,writable,test");
depth_enabled = DataUtils::ParseXmlAttribute(*xml_depth, "enable", depth_enabled);
depth_write = DataUtils::ParseXmlAttribute(*xml_depth, "writable", depth_write);
std::string comp_func_str = "less";
comp_func_str = DataUtils::ParseXmlAttribute(*xml_depth, "test", comp_func_str);
depth_comparison = ComparisonFunctionFromString(comp_func_str);
}
if(const auto* xml_stencil = element.FirstChildElement("stencil")) {
DataUtils::ValidateXmlElement(*xml_stencil, "stencil", "", "", "front,back", "enable,writable,readable");
stencil_read = DataUtils::ParseXmlAttribute(*xml_stencil, "readable", stencil_read);
stencil_write = DataUtils::ParseXmlAttribute(*xml_stencil, "writable", stencil_write);
stencil_enabled = DataUtils::ParseXmlAttribute(*xml_stencil, "enable", stencil_enabled);
if(const auto* xml_stencilfront = xml_stencil->FirstChildElement("front")) {
DataUtils::ValidateXmlElement(*xml_stencilfront, "front", "", "fail,depthfail,pass,test");
std::string failFront_str = "keep";
failFront_str = DataUtils::ParseXmlAttribute(*xml_stencilfront, "fail", failFront_str);
stencil_failFrontOp = StencilOperationFromString(failFront_str);
std::string depthfailFront_str = "keep";
depthfailFront_str = DataUtils::ParseXmlAttribute(*xml_stencilfront, "depthfail", depthfailFront_str);
stencil_failDepthFrontOp = StencilOperationFromString(depthfailFront_str);
std::string passFront_str = "keep";
passFront_str = DataUtils::ParseXmlAttribute(*xml_stencilfront, "pass", passFront_str);
stencil_passFrontOp = StencilOperationFromString(passFront_str);
std::string compareFront_str = "always";
compareFront_str = DataUtils::ParseXmlAttribute(*xml_stencilfront, "test", compareFront_str);
stencil_testFront = ComparisonFunctionFromString(compareFront_str);
}
if(const auto* xml_stencilback = xml_stencil->FirstChildElement("back")) {
DataUtils::ValidateXmlElement(*xml_stencilback, "back", "", "fail,depthfail,pass,test");
std::string failBack_str = "keep";
failBack_str = DataUtils::ParseXmlAttribute(*xml_stencilback, "fail", failBack_str);
stencil_failBackOp = StencilOperationFromString(failBack_str);
std::string depthfailBack_str = "keep";
depthfailBack_str = DataUtils::ParseXmlAttribute(*xml_stencilback, "depthfail", depthfailBack_str);
stencil_failDepthBackOp = StencilOperationFromString(depthfailBack_str);
std::string passBack_str = "keep";
passBack_str = DataUtils::ParseXmlAttribute(*xml_stencilback, "pass", passBack_str);
stencil_passBackOp = StencilOperationFromString(passBack_str);
std::string compareBack_str = "always";
compareBack_str = DataUtils::ParseXmlAttribute(*xml_stencilback, "test", compareBack_str);
stencil_testBack = ComparisonFunctionFromString(compareBack_str);
}
}
}
| 49.507813 | 138 | 0.738678 | cugone |
36ffedf6cde7d04d5bb17f40b53e19333b8acbba | 1,850 | hpp | C++ | samples/boost.asio/drink_shop/drink_shop_transaction.hpp | roamingunner/cmake-template | c4254d261eb945ae7fdff83f28b1bab999f72e8c | [
"Apache-2.0"
] | null | null | null | samples/boost.asio/drink_shop/drink_shop_transaction.hpp | roamingunner/cmake-template | c4254d261eb945ae7fdff83f28b1bab999f72e8c | [
"Apache-2.0"
] | null | null | null | samples/boost.asio/drink_shop/drink_shop_transaction.hpp | roamingunner/cmake-template | c4254d261eb945ae7fdff83f28b1bab999f72e8c | [
"Apache-2.0"
] | null | null | null | #ifndef _DRINK_SHOP_TRANSACTION_H_
#define _DRINK_SHOP_TRANSACTION_H_
#include <stdint.h>
#include <string>
#include <vector>
#include <ctime>
#include <iostream>
#include "aixlog.hpp"
using namespace std;
class transacation
{
private:
/* data */
uint32_t tid_;
uint32_t rid_;
string type_;
string size_;
bool packed_;
vector<string> stamps_;
public:
static uint32_t tid_iterator_;
public:
transacation(const uint32_t rid, const string& type, const string& size, const bool packed)
:tid_(tid_iterator_++), rid_(rid), type_(type), size_(size),packed_(packed){
LOG(NOTICE) << "transacation create: tid="
<< tid_ << " rid_=" << rid_ << " type=" << type_ << " size=" << size_ << " packed=" << packed_ << endl;
}
~transacation() {
LOG(NOTICE) << "transacation destory: tid="
<< tid_ << " rid_=" << rid_ << " type=" << type_ << " size=" << size_ << " packed=" << packed_ << endl;
}
void add_stamp(const string& who){
string stamp = who;
time_t now = time(0);
stamp += "@";
stamp += ctime(&now);
stamps_.push_back(stamp);
}
const bool is_packed(){
return packed_;
}
const uint32_t tid() const {
return tid_;
}
const uint32_t rid() const {
return rid_;
}
const string type() const {
return type_;
}
const string size() const {
return size_;
}
vector<string>& stamps() {
return stamps_;
}
friend ostream &operator <<(ostream& out, const transacation& instance){
out << "transacation tid:" << instance.tid_ << " rid:" << instance.rid_
<< " type:" << instance.type_ << " size_:" << instance.size_ << " packed:" << instance.packed_ << endl;
return out;
}
};
#endif | 28.030303 | 119 | 0.571351 | roamingunner |
3c07fbe9cc3a2dd20b02684c5b17544b9c39e8a8 | 15,993 | cpp | C++ | android-31/android/view/accessibility/AccessibilityNodeInfo_AccessibilityAction.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/view/accessibility/AccessibilityNodeInfo_AccessibilityAction.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-31/android/view/accessibility/AccessibilityNodeInfo_AccessibilityAction.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../os/Parcel.hpp"
#include "../../../JString.hpp"
#include "../../../JObject.hpp"
#include "../../../JString.hpp"
#include "./AccessibilityNodeInfo_AccessibilityAction.hpp"
namespace android::view::accessibility
{
// Fields
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_ACCESSIBILITY_FOCUS()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_ACCESSIBILITY_FOCUS",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_CLEAR_ACCESSIBILITY_FOCUS()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_CLEAR_ACCESSIBILITY_FOCUS",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_CLEAR_FOCUS()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_CLEAR_FOCUS",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_CLEAR_SELECTION()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_CLEAR_SELECTION",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_CLICK()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_CLICK",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_COLLAPSE()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_COLLAPSE",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_CONTEXT_CLICK()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_CONTEXT_CLICK",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_COPY()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_COPY",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_CUT()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_CUT",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_DISMISS()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_DISMISS",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_EXPAND()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_EXPAND",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_FOCUS()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_FOCUS",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_HIDE_TOOLTIP()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_HIDE_TOOLTIP",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_IME_ENTER()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_IME_ENTER",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_LONG_CLICK()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_LONG_CLICK",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_MOVE_WINDOW()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_MOVE_WINDOW",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_NEXT_AT_MOVEMENT_GRANULARITY()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_NEXT_AT_MOVEMENT_GRANULARITY",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_NEXT_HTML_ELEMENT()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_NEXT_HTML_ELEMENT",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_PAGE_DOWN()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_PAGE_DOWN",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_PAGE_LEFT()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_PAGE_LEFT",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_PAGE_RIGHT()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_PAGE_RIGHT",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_PAGE_UP()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_PAGE_UP",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_PASTE()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_PASTE",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_PRESS_AND_HOLD()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_PRESS_AND_HOLD",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_PREVIOUS_HTML_ELEMENT()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_PREVIOUS_HTML_ELEMENT",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_SCROLL_BACKWARD()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_SCROLL_BACKWARD",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_SCROLL_DOWN()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_SCROLL_DOWN",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_SCROLL_FORWARD()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_SCROLL_FORWARD",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_SCROLL_LEFT()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_SCROLL_LEFT",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_SCROLL_RIGHT()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_SCROLL_RIGHT",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_SCROLL_TO_POSITION()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_SCROLL_TO_POSITION",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_SCROLL_UP()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_SCROLL_UP",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_SELECT()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_SELECT",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_SET_PROGRESS()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_SET_PROGRESS",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_SET_SELECTION()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_SET_SELECTION",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_SET_TEXT()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_SET_TEXT",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_SHOW_ON_SCREEN()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_SHOW_ON_SCREEN",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
android::view::accessibility::AccessibilityNodeInfo_AccessibilityAction AccessibilityNodeInfo_AccessibilityAction::ACTION_SHOW_TOOLTIP()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"ACTION_SHOW_TOOLTIP",
"Landroid/view/accessibility/AccessibilityNodeInfo$AccessibilityAction;"
);
}
JObject AccessibilityNodeInfo_AccessibilityAction::CREATOR()
{
return getStaticObjectField(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"CREATOR",
"Landroid/os/Parcelable$Creator;"
);
}
// QJniObject forward
AccessibilityNodeInfo_AccessibilityAction::AccessibilityNodeInfo_AccessibilityAction(QJniObject obj) : JObject(obj) {}
// Constructors
AccessibilityNodeInfo_AccessibilityAction::AccessibilityNodeInfo_AccessibilityAction(jint arg0, JString arg1)
: JObject(
"android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction",
"(ILjava/lang/CharSequence;)V",
arg0,
arg1.object<jstring>()
) {}
// Methods
jint AccessibilityNodeInfo_AccessibilityAction::describeContents() const
{
return callMethod<jint>(
"describeContents",
"()I"
);
}
jboolean AccessibilityNodeInfo_AccessibilityAction::equals(JObject arg0) const
{
return callMethod<jboolean>(
"equals",
"(Ljava/lang/Object;)Z",
arg0.object<jobject>()
);
}
jint AccessibilityNodeInfo_AccessibilityAction::getId() const
{
return callMethod<jint>(
"getId",
"()I"
);
}
JString AccessibilityNodeInfo_AccessibilityAction::getLabel() const
{
return callObjectMethod(
"getLabel",
"()Ljava/lang/CharSequence;"
);
}
jint AccessibilityNodeInfo_AccessibilityAction::hashCode() const
{
return callMethod<jint>(
"hashCode",
"()I"
);
}
JString AccessibilityNodeInfo_AccessibilityAction::toString() const
{
return callObjectMethod(
"toString",
"()Ljava/lang/String;"
);
}
void AccessibilityNodeInfo_AccessibilityAction::writeToParcel(android::os::Parcel arg0, jint arg1) const
{
callMethod<void>(
"writeToParcel",
"(Landroid/os/Parcel;I)V",
arg0.object(),
arg1
);
}
} // namespace android::view::accessibility
| 40.183417 | 157 | 0.823173 | YJBeetle |
3c0cf4b14de368379a8db1b865d4ad9324ca4b51 | 5,516 | cpp | C++ | libs/fnd/type_traits/test/src/unit_test_fnd_type_traits_remove_constref.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/type_traits/test/src/unit_test_fnd_type_traits_remove_constref.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/type_traits/test/src/unit_test_fnd_type_traits_remove_constref.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file unit_test_fnd_type_traits_remove_constref.cpp
*
* @brief remove_constref のテスト
*
* @author myoukaku
*/
#include <bksge/fnd/type_traits/remove_constref.hpp>
#include <bksge/fnd/type_traits/is_same.hpp>
#include <gtest/gtest.h>
#include "type_traits_test_utility.hpp"
#define BKSGE_REMOVE_CONSTREF_TEST_IMPL(T1, T2) \
static_assert(bksge::is_same<bksge::remove_constref<T1>::type, T2>::value, #T1 ", " #T2); \
static_assert(bksge::is_same<bksge::remove_constref_t<T1>, T2>::value, #T1 ", " #T2)
#define BKSGE_REMOVE_CONSTREF_TEST(T) \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( T, T); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const T, T); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( volatile T, volatile T); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const volatile T, volatile T); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( T&, T); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const T&, T); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( volatile T&, volatile T); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const volatile T&, volatile T); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( T&&, T); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const T&&, T); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( volatile T&&, volatile T); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const volatile T&&, volatile T); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( T*, T*); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const T*, const T*); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( volatile T*, volatile T*); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const volatile T*, const volatile T*); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( T*&, T*); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const T*&, const T*); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( volatile T*&, volatile T*); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const volatile T*&, const volatile T*); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( T*&&, T*); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const T*&&, const T*); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( volatile T*&&, volatile T*); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const volatile T*&&, const volatile T*); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( T[2], T[2]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const T[3], T[3]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( volatile T[4], volatile T[4]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const volatile T[5], volatile T[5]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( T[], T[]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const T[], T[]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( volatile T[], volatile T[]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const volatile T[], volatile T[]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( T(*)[2], T(*)[2]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const T(*)[3], const T(*)[3]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( volatile T(*)[4], volatile T(*)[4]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const volatile T(*)[5], const volatile T(*)[5]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( T(&)[2], T[2]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const T(&)[3], T[3]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( volatile T(&)[4], volatile T[4]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const volatile T(&)[5], volatile T[5]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( T(&)[], T[]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const T(&)[], T[]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( volatile T(&)[], volatile T[]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const volatile T(&)[], volatile T[]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( T(&&)[2], T[2]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const T(&&)[3], T[3]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( volatile T(&&)[4], volatile T[4]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const volatile T(&&)[5], volatile T[5]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( T(&&)[], T[]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const T(&&)[], T[]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL( volatile T(&&)[], volatile T[]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(const volatile T(&&)[], volatile T[]); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(T(T), T(T)); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(T(void), T(void)); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(void(T), void(T)); \
BKSGE_REMOVE_CONSTREF_TEST_IMPL(T(T, T), T(T, T))
BKSGE_REMOVE_CONSTREF_TEST(int);
BKSGE_REMOVE_CONSTREF_TEST(UDT);
BKSGE_REMOVE_CONSTREF_TEST_IMPL(f1, f1);
BKSGE_REMOVE_CONSTREF_TEST_IMPL(f2, f2);
BKSGE_REMOVE_CONSTREF_TEST_IMPL(f3, f3);
BKSGE_REMOVE_CONSTREF_TEST_IMPL(mf1, mf1);
BKSGE_REMOVE_CONSTREF_TEST_IMPL(mf2, mf2);
BKSGE_REMOVE_CONSTREF_TEST_IMPL(mf3, mf3);
BKSGE_REMOVE_CONSTREF_TEST_IMPL(mf4, mf4);
BKSGE_REMOVE_CONSTREF_TEST_IMPL(mp, mp);
BKSGE_REMOVE_CONSTREF_TEST_IMPL(cmf, cmf);
BKSGE_REMOVE_CONSTREF_TEST_IMPL(foo0_t, foo0_t);
BKSGE_REMOVE_CONSTREF_TEST_IMPL(foo1_t, foo1_t);
BKSGE_REMOVE_CONSTREF_TEST_IMPL(foo2_t, foo2_t);
BKSGE_REMOVE_CONSTREF_TEST_IMPL(foo3_t, foo3_t);
BKSGE_REMOVE_CONSTREF_TEST_IMPL(foo4_t, foo4_t);
#undef BKSGE_REMOVE_CONSTREF_TEST
#undef BKSGE_REMOVE_CONSTREF_TEST_IMPL
| 58.063158 | 93 | 0.646664 | myoukaku |
3c0e885823d5d53c963b8be7ce8392377be53e1b | 4,013 | cpp | C++ | src/Engine/Scene.cpp | fgagamedev/voID | 37cd56fe2878d036c36dafcf595e48ed85408d02 | [
"MIT"
] | null | null | null | src/Engine/Scene.cpp | fgagamedev/voID | 37cd56fe2878d036c36dafcf595e48ed85408d02 | [
"MIT"
] | null | null | null | src/Engine/Scene.cpp | fgagamedev/voID | 37cd56fe2878d036c36dafcf595e48ed85408d02 | [
"MIT"
] | null | null | null | /**
@file Scene.cpp
@brief Methods that manages all scenes in the game.
@copyright LGPL. MIT License.
*/
#include "Engine/Scene.hpp"
#include "Log/log.hpp"
// Constructor
Scene::Scene() {}
Scene::~Scene() {}
/**
@brief That function is for start the scene of the game.
*/
void Scene::Start() {
// Run through the vector of game objects, starting them.
for (auto obj : m_gameObjects) {
obj->Start();
}
}
/**
@brief That function is for update the scene of the game.
Compare the game objects, the begin and end objects. Checks if is
active and update it.
*/
void Scene::Update() {
// Sort and compares the gameobjects by the first element in its vector, and the last one, for update them.
std::sort(m_gameObjects.begin(), m_gameObjects.end(), CompareGameObjects);
for (auto it : m_gameObjects) {
if (it->active) {
it->Update();
}
}
}
/**
@brief That function is for update the draws of the game.
Compare the game objects, the begin and end objects. Checks if is
active and update the draws.
*/
void Scene::DrawUpdate() {
// Sort and compares the gameobjects by the first element in its vector, and the last one, for update the object's draw.
std::sort(m_gameObjects.begin(), m_gameObjects.end(), CompareGameObjects);
for (auto it : m_gameObjects) {
if (it->active) {
it->DrawUpdate();
}
}
}
/**
@brief that function is for add the gameobjects to the game
@param[in] GameObject pointer that points to the current gameobject
*/
void Scene::AddGameObject(GameObject *gameObject) {
//Appends a gameobject to the end of the vector of gameobjects.
m_gameObjects.push_back(gameObject);
}
void Scene::AddGameObject(std::vector<GameObject *> gameObjects) {
//Inserts gameobjects in the end-position of the vector of gameobjects.
m_gameObjects.insert(std::end(m_gameObjects), std::begin(gameObjects),
std::end(gameObjects));
}
/**
@brief That function is for fix the updates made before.
Checks if gameObjects are active and fix the update.
*/
void Scene::FixedUpdate() {
//Run through the gameobjects vector, and updates the active gameObjects.
for (auto it : m_gameObjects) {
if (it->active) {
it->FixedUpdate();
}
}
}
/**
@brief set the state of the scene. Check the states of the scene,
if is activated, deactivated, hidden and shown and change the state according
to the state.
@param[in] state = is the state of the scene.
*/
void Scene::SetState(SceneStates state) {
// Sets the current state scene according to the int constants defined on the SceneStates enum.
m_currentState = state;
INFO("[SCENE] " << m_name << " state: " << m_currentState);
if (state == SCENE_ACTIVATED) {
Activation();
} else if (state == SCENE_DEACTIVATED) {
Deactivation();
} else if (state == SCENE_HIDDEN) {
Hidden();
} else if (state == SCENE_SHOWN) {
Shown();
}
}
/**
@brief That function is for when the state is activated. So the Scene
starts.
*/
void Scene::Activation() {
OnActivation();
Start();
}
/**
@brief That function is for when the state isn't activated.
*/
void Scene::Deactivation() {
OnDeactivation();
}
/**
@brief That function is for when the state is shown.
*/
void Scene::Shown() {
OnShown();
}
/**
@brief That function is for when the state is shown.
*/
void Scene::Hidden() {
OnHidden();
}
/**
@brief Get the name of a scene gameobject.
@param[in] name - the name of the searched scene.
@return nullptr if the name doesn't match any gameobject, or the scene name found.
*/
GameObject *Scene::GetGameObject(std::string name) {
//Run through the gameobjects vector, and get one gameobject by the given name.
for (auto it : m_gameObjects) {
if (it->GetName() == name) {
return it;
}
}
return nullptr;
}
| 26.753333 | 124 | 0.646898 | fgagamedev |
3c1284f50c80fd96a1e7cafd8ec9a1abdc8af140 | 1,734 | cpp | C++ | part-01/2_22_search-a-2d-matrix-ii_DNC.cpp | abhijeetbodas2001/DSA | ff244dea639a4a5c203e21df3efa47ff079f452a | [
"MIT"
] | null | null | null | part-01/2_22_search-a-2d-matrix-ii_DNC.cpp | abhijeetbodas2001/DSA | ff244dea639a4a5c203e21df3efa47ff079f452a | [
"MIT"
] | null | null | null | part-01/2_22_search-a-2d-matrix-ii_DNC.cpp | abhijeetbodas2001/DSA | ff244dea639a4a5c203e21df3efa47ff079f452a | [
"MIT"
] | null | null | null | // Problem: https://leetcode.com/problems/search-a-2d-matrix-ii/
// Recursive binary (3/4 -ary?) search
// Be super-careful with boundaries!
class Solution {
private:
bool searchInSubmatrix(vector<vector<int>>& matrix, int top, int right, int bottom, int left, int target) {
// Searches for target in submatrix between top&bottom rows and left&right columns (both included)
if (top > bottom || left > right) {
return false;
}
if (top == bottom && right == left) {
return matrix[top][right] == target;
}
int rows = matrix.size();
int columns = matrix[0].size();
int mid_row = (top + bottom) / 2;
int mid_column = (right + left) / 2;
int mid_elem = matrix[mid_row][mid_column];
if (mid_elem == target) {
return true;
} else if (mid_elem > target) {
return (
searchInSubmatrix(matrix, top, mid_column - 1, mid_row - 1, left, target) || // top-left part
searchInSubmatrix(matrix, top, right, mid_row - 1, mid_column, target) || // top right part
searchInSubmatrix(matrix, mid_row, mid_column - 1, bottom, left, target) // bottom left part
);
} else {
assert(mid_elem < target);
return (
searchInSubmatrix(matrix, mid_row + 1, right, bottom, mid_column + 1, target) || // bottom right part
searchInSubmatrix(matrix, top, right, mid_row, mid_column + 1, target) || // top right part
searchInSubmatrix(matrix, mid_row + 1, mid_column, bottom, left, target) // bottom left part
);
}
}
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rows = matrix.size();
int columns = matrix[0].size();
return searchInSubmatrix(matrix, 0, columns - 1, rows - 1, 0, target);
}
}; | 36.893617 | 109 | 0.641292 | abhijeetbodas2001 |
3c1864c3caff41d766817db973b450ba55085c0c | 759 | cpp | C++ | leetcode/problemset-algorithms/binary-reversal.cpp | riteshkumar99/coding-for-placement | b45f90f662808bf4bf038ff98a016d49b9d71f71 | [
"MIT"
] | null | null | null | leetcode/problemset-algorithms/binary-reversal.cpp | riteshkumar99/coding-for-placement | b45f90f662808bf4bf038ff98a016d49b9d71f71 | [
"MIT"
] | null | null | null | leetcode/problemset-algorithms/binary-reversal.cpp | riteshkumar99/coding-for-placement | b45f90f662808bf4bf038ff98a016d49b9d71f71 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <bitset>
using namespace std;
string BinaryReversal(string str) {
long num = stol(str);
long result = 0;
if(num < (1u<<8)) {
const bitset<8> b(num);
for(int i = 0; i<8; i++) {
if(b[i]) {
result += (1 << (7-i));
}
}
} else if(num < (1u<<16)) {
const bitset<16> b(num);
for(int i = 0; i<16; i++) {
if(b[i]) {
result += (1 << (15-i));
}
}
} else {
const bitset<32> b(num);
for(int i = 0; i<32; i++) {
if(b[i]) {
result += (1 << (31-i));
}
}
}
return to_string(result);
}
int main(void) {
// keep this function call here
cout << BinaryReversal("213");
return 0;
}
| 18.512195 | 36 | 0.457181 | riteshkumar99 |
3c19af5f78d5e910e731f3b4dace0b8588aad747 | 1,498 | hpp | C++ | support/boost/fusion/container/map/detail/extract_keys.hpp | rogard/boost_sandbox_statistics | 16aacbc716a31a9f7bb6c535b1c90dc343282a23 | [
"BSL-1.0"
] | null | null | null | support/boost/fusion/container/map/detail/extract_keys.hpp | rogard/boost_sandbox_statistics | 16aacbc716a31a9f7bb6c535b1c90dc343282a23 | [
"BSL-1.0"
] | null | null | null | support/boost/fusion/container/map/detail/extract_keys.hpp | rogard/boost_sandbox_statistics | 16aacbc716a31a9f7bb6c535b1c90dc343282a23 | [
"BSL-1.0"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// extract_keys.hpp //
// //
// Copyright 2010 Erwann Rogard. 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 BOOST_FUSION_CONTAINER_MAP_DETAIL_EXTRACT_KEYS_HPP_ER_2010
#define BOOST_FUSION_CONTAINER_MAP_DETAIL_EXTRACT_KEYS_HPP_ER_2010
#include <boost/mpl/fold.hpp>
#include <boost/mpl/vector/vector0.hpp>
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/fusion/mpl.hpp> // likely to be needed by client
namespace boost {
namespace fusion{
namespace detail{
template<typename Map>
struct extract_keys{
template<typename P>
struct extract_first{
typedef typename P::first_type type;
};
typedef typename Map::storage_type storage_;
typedef typename boost::mpl::fold<
storage_,
boost::mpl::vector0<>,
boost::mpl::push_back<
boost::mpl::_1,
extract_first<boost::mpl::_2>
>
>::type type;
};
}// detail
}// fusion
}// boost
#endif
| 34.045455 | 79 | 0.506676 | rogard |
3c1aaf2d73e3fa5ae1a520e194dbb2379c077604 | 270 | cpp | C++ | tests/SplitArrayLargestSumTest.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 43 | 2015-10-10T12:59:52.000Z | 2018-07-11T18:07:00.000Z | tests/SplitArrayLargestSumTest.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | null | null | null | tests/SplitArrayLargestSumTest.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 11 | 2015-10-10T14:41:11.000Z | 2018-07-28T06:03:16.000Z | #include "catch.hpp"
#include "SplitArrayLargestSum.hpp"
TEST_CASE("Split Array Largest Sum") {
SplitArrayLargestSum s;
SECTION("Sample test") {
vector<int> nums{7, 2, 5, 10, 8};
int m = 2;
REQUIRE(s.splitArray(nums, m) == 18);
}
}
| 20.769231 | 45 | 0.596296 | yanzhe-chen |
3c1e2638ba6f16c528bd1973d3e45b45d3073989 | 915 | cpp | C++ | 5.Inheritance/i-Design/Q4/Truck.cpp | Concept-Team/e-box-UTA018 | a6caf487c9f27a5ca30a00847ed49a163049f67e | [
"MIT"
] | 26 | 2021-03-17T03:15:22.000Z | 2021-06-09T13:29:41.000Z | 5.Inheritance/i-Design/Q4/Truck.cpp | Servatom/e-box-UTA018 | a6caf487c9f27a5ca30a00847ed49a163049f67e | [
"MIT"
] | 6 | 2021-03-16T19:04:05.000Z | 2021-06-03T13:41:04.000Z | 5.Inheritance/i-Design/Q4/Truck.cpp | Concept-Team/e-box-UTA018 | a6caf487c9f27a5ca30a00847ed49a163049f67e | [
"MIT"
] | 42 | 2021-03-17T03:16:22.000Z | 2021-06-14T21:11:20.000Z | #include<iostream>
#include<string>
using namespace std;
#include "FourWheeler.h"
#include "Vehicle.h"
class Truck: public FourWheeler, public Vehicle{
private:
int cargoCapacity;
string size;
public:
Truck(){}
Truck(string m,int y,string manu,string gt,string ft,int cc,string size):Vehicle(m,y,manu),FourWheeler(gt,ft){
cargoCapacity=cc;
this->size=size;
}
void displayDetails()
{
cout<<"Truck Details"<<endl;
cout<<"Model : "<<model<<endl;
cout<<"Year : "<<year<<endl;
cout<<"Manufacturer : "<<manufacturer<<endl;
cout<<"Gear Type : "<<gearType<<endl;
cout<<"Fuel Type : "<<fuelType<<endl;
cout<<"Cargo Capacity : "<<cargoCapacity<<" MT"<<endl;
cout<<"Size : "<<size<<endl;
}
};
| 29.516129 | 119 | 0.523497 | Concept-Team |
3c229528c16576f5b1651c766e18a2874c6ac269 | 1,215 | cpp | C++ | Binary Search/MedianOfArray.cpp | dk-verma/Interviewbit | b1a9bfe45a6238f5ca864773133730c856619704 | [
"MIT"
] | null | null | null | Binary Search/MedianOfArray.cpp | dk-verma/Interviewbit | b1a9bfe45a6238f5ca864773133730c856619704 | [
"MIT"
] | null | null | null | Binary Search/MedianOfArray.cpp | dk-verma/Interviewbit | b1a9bfe45a6238f5ca864773133730c856619704 | [
"MIT"
] | null | null | null | /*
There are two sorted arrays A and B of size m and n respectively.
Find the median of the two sorted arrays ( The median of the array formed by merging both the arrays ).
The overall run time complexity should be O(log (m+n)).
- Sample Input
A : [1 4 5]
B : [2 3]
- Sample Output
3
*/
double Solution::findMedianSortedArrays(const vector<int> &a, const vector<int> &b)
{
int n1 = a.size(), n2 = b.size();
if(n1 > n2)
return findMedianSortedArrays(b, a); // time complexity = O(log(min(n1,n2)
int start = 0, end = n1;
while(start <= end)
{
int partX = (start+end)/2;
int leftX = partX == 0 ? INT_MIN: a[partX-1];
int rightX = partX == n1 ? INT_MAX: a[partX];
int partY = (n1 + n2 + 1)/2 - partX;
int leftY = partY == 0 ? INT_MIN: b[partY-1];
int rightY = partY == n2 ? INT_MAX: b[partY];
if(leftX <= rightY && leftY <= rightX)
{
if((n1+n2)&1)
return double(max(leftX, leftY));
else
return double( max(leftX, leftY) + min(rightX, rightY) )*(0.5);
}
else if(leftX > rightY)
end = partX-1;
else
start = partX+1;
}
return 0.0;
}
| 28.928571 | 103 | 0.555556 | dk-verma |
3c26f467eeab4581042dc20724467379335d0bd1 | 7,158 | cpp | C++ | packages/dScene/dMaterialNodeInfo.cpp | wivlaro/newton-dynamics | 2bafd29aea919f237e56784510db1cb8011d0f40 | [
"Zlib"
] | null | null | null | packages/dScene/dMaterialNodeInfo.cpp | wivlaro/newton-dynamics | 2bafd29aea919f237e56784510db1cb8011d0f40 | [
"Zlib"
] | null | null | null | packages/dScene/dMaterialNodeInfo.cpp | wivlaro/newton-dynamics | 2bafd29aea919f237e56784510db1cb8011d0f40 | [
"Zlib"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////
// Name: dMaterialNodeInfo.h
// Purpose:
// Author: Julio Jerez
// Modified by:
// Created: 22/05/2010 08:02:08
// RCS-ID:
// Copyright: Copyright (c) <2010> <Newton Game Dynamics>
// License:
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely
/////////////////////////////////////////////////////////////////////////////
#include "dSceneStdafx.h"
#include "dMaterialNodeInfo.h"
D_IMPLEMENT_CLASS_NODE(dMaterialNodeInfo);
dMaterialNodeInfo::dMaterialNodeInfo()
:dNodeInfo (),
m_ambientColor (0.8f, 0.8f, 0.8f, 1.0f),
m_diffuseColor(0.8f, 0.8f, 0.8f, 1.0f),
m_specularColor (0.0f, 0.0f, 0.0f, 1.0f),
m_emissiveColor (0.0f, 0.0f, 0.0f, 1.0f),
m_shininess (0.0f),
m_opacity (1.0f),
m_ambientTexId (-1),
m_diffuseTexId (-1),
m_specularTexId (-1),
m_emissiveTexId(-1),
m_id(0)
{
SetName ("material");
}
dMaterialNodeInfo::dMaterialNodeInfo(dScene* const world)
:dNodeInfo (),
m_ambientColor (0.8f, 0.8f, 0.8f, 1.0f),
m_diffuseColor(0.8f, 0.8f, 0.8f, 1.0f),
m_specularColor (0.0f, 0.0f, 0.0f, 1.0f),
m_emissiveColor (0.0f, 0.0f, 0.0f, 1.0f),
m_shininess (0.0f),
m_opacity (1.0f),
m_ambientTexId (-1),
m_diffuseTexId (-1),
m_specularTexId (-1),
m_emissiveTexId(-1),
m_id(0)
{
SetName ("material");
}
dMaterialNodeInfo::dMaterialNodeInfo(int id)
:dNodeInfo (),
m_ambientColor (0.8f, 0.8f, 0.8f, 1.0f),
m_diffuseColor(0.8f, 0.8f, 0.8f, 1.0f),
m_specularColor (0.0f, 0.0f, 0.0f, 1.0f),
m_emissiveColor (0.0f, 0.0f, 0.0f, 1.0f),
m_shininess (0.0f),
m_opacity (1.0f),
m_ambientTexId (-1),
m_diffuseTexId (-1),
m_specularTexId (-1),
m_emissiveTexId(-1),
m_id(id)
{
SetName ("material");
}
dMaterialNodeInfo::~dMaterialNodeInfo(void)
{
}
/*
void dMaterialNodeInfo::InitFrom (const dMaterialNodeInfo& src, )
{
m_ambientColor = src.m_ambientColor;
m_diffuseColor = src.m_diffuseColor;
m_specularColor = src.m_specularColor;
m_emissiveColor = src.m_emissiveColor;
m_shininess = src.m_shininess;
m_opacity = src.m_opacity;
m_ambientTexId = src.m_ambientTexId;
m_diffuseTexId = src.m_diffuseTexId;
m_specularTexId = src.m_specularTexId;
m_emissiveTexId = src.m_emissiveTexId;
}
*/
dCRCTYPE dMaterialNodeInfo::CalculateSignature() const
{
dCRCTYPE signature = 0;
signature = dCRC64 (&m_ambientColor, sizeof (m_ambientColor), signature);
signature = dCRC64 (&m_diffuseColor, sizeof (m_diffuseColor), signature);
signature = dCRC64 (&m_specularColor, sizeof (m_specularColor), signature);
signature = dCRC64 (&m_emissiveColor, sizeof (m_emissiveColor), signature);
signature = dCRC64 (&m_shininess, sizeof (m_shininess), signature);
signature = dCRC64 (&m_opacity, sizeof (m_opacity), signature);
signature = dCRC64 (&m_ambientTexId, sizeof (m_ambientTexId), signature);
signature = dCRC64 (&m_diffuseTexId, sizeof (m_diffuseTexId), signature);
signature = dCRC64 (&m_specularTexId, sizeof (m_specularTexId), signature);
signature = dCRC64 (&m_emissiveTexId, sizeof (m_emissiveTexId), signature);
return signature;
}
void dMaterialNodeInfo::Serialize (TiXmlElement* const rootNode) const
{
SerialiseBase(dNodeInfo, rootNode);
char buffer[4096];
// itoa64____ (m_id, id, 10);
// rootNode->SetAttribute("id", id);
rootNode->SetAttribute("id", m_id);
// char id[256];
TiXmlElement* const ambient = new TiXmlElement ("ambient");
rootNode->LinkEndChild(ambient);
dFloatArrayToString(&m_ambientColor[0], 4, buffer, sizeof (buffer));
//itoa64____ (m_ambientTexId, id, 10);
dString id (m_ambientTexId);
ambient->SetAttribute("textureId", id.GetStr());
ambient->SetAttribute("color", buffer);
TiXmlElement* const diffuse = new TiXmlElement ("diffuse");
rootNode->LinkEndChild(diffuse);
dFloatArrayToString(&m_diffuseColor[0], 4, buffer, sizeof (buffer));
//itoa64____ (m_diffuseTexId, id, 10);
id = dString (m_diffuseTexId);
diffuse->SetAttribute("textureId", id.GetStr());
diffuse->SetAttribute("color", buffer);
TiXmlElement* const specular = new TiXmlElement ("specular");
rootNode->LinkEndChild(specular);
dFloatArrayToString(&m_specularColor[0], 4, buffer, sizeof (buffer));
//itoa64____ (m_specularTexId, id, 10);
id = dString (m_specularTexId);
specular->SetAttribute("textureId", id.GetStr());
specular->SetAttribute("color", buffer);
TiXmlElement* const emissive = new TiXmlElement ("emissive");
rootNode->LinkEndChild(emissive);
dFloatArrayToString(&m_emissiveColor[0], 4, buffer, sizeof (buffer));
//itoa64____ (m_emissiveTexId, id, 10);
id = dString (m_emissiveTexId);
emissive->SetAttribute("textureId", id.GetStr());
emissive->SetAttribute("color", buffer);
TiXmlElement* const shininess = new TiXmlElement ("shininess");
rootNode->LinkEndChild(shininess);
shininess->SetDoubleAttribute ("float", m_shininess);
TiXmlElement* const opacity = new TiXmlElement ("opacity");
rootNode->LinkEndChild(opacity);
opacity->SetDoubleAttribute ("float", m_opacity);
}
bool dMaterialNodeInfo::Deserialize (const dScene* const scene, TiXmlElement* const rootNode)
{
DeserialiseBase(scene, dNodeInfo, rootNode);
char text[1024];
rootNode->Attribute("id", &m_id);
TiXmlElement* const ambient = (TiXmlElement*) rootNode->FirstChild ("ambient");
sprintf (text, "%s", ambient->Attribute("textureId"));
m_ambientTexId = dString((const char*)text).ToInteger64();
dStringToFloatArray (ambient->Attribute("color"), &m_ambientColor[0], 4);
TiXmlElement* const diffuse = (TiXmlElement*) rootNode->FirstChild ("diffuse");
sprintf (text, "%s", diffuse->Attribute("textureId"));
m_diffuseTexId = dString((const char*)text).ToInteger64();
dStringToFloatArray (diffuse->Attribute("color"), &m_diffuseColor[0], 4);
TiXmlElement* const specular = (TiXmlElement*) rootNode->FirstChild ("specular");
sprintf (text, "%s", specular->Attribute("textureId"));
m_emissiveTexId = dString((const char*)text).ToInteger64();
dStringToFloatArray (specular->Attribute("color"), &m_specularColor[0], 4);
TiXmlElement* const emissive = (TiXmlElement*) rootNode->FirstChild ("emissive");
sprintf (text, "%s", emissive->Attribute("textureId"));
m_emissiveTexId = dString((const char*)text).ToInteger64();
dStringToFloatArray (emissive->Attribute("color"), &m_emissiveColor[0], 4);
TiXmlElement* const shininess = (TiXmlElement*) rootNode->FirstChild ("shininess");
double value;
shininess->Attribute("float", &value);
m_shininess = dFloat (value);
TiXmlElement* const opacity = (TiXmlElement*) rootNode->FirstChild ("opacity");
opacity->Attribute("float", &value);
m_opacity = dFloat (value);
return true;
}
| 33.448598 | 95 | 0.687203 | wivlaro |
3c27a6803599d840ce0c329a159b1a9663f37f03 | 3,347 | cpp | C++ | trees/BinaryTree.cpp | JOSUERV99/DataStructuresFromScratch | 99724659fd70a5717346dcc93fddb51ee69d4846 | [
"MIT"
] | 1 | 2020-11-22T04:48:53.000Z | 2020-11-22T04:48:53.000Z | trees/BinaryTree.cpp | JOSUERV99/DataStructuresFromScratch | 99724659fd70a5717346dcc93fddb51ee69d4846 | [
"MIT"
] | null | null | null | trees/BinaryTree.cpp | JOSUERV99/DataStructuresFromScratch | 99724659fd70a5717346dcc93fddb51ee69d4846 | [
"MIT"
] | null | null | null | #ifndef __BT__
#include"BinaryTree.h"
#endif
#ifndef __LL__
#include"../canonical/LinkedList.h"
#endif
#ifndef __TN__
#include"../nodes/TreeNode.h"
#endif
template <class T>
int BinaryTree<T>::size() {
return nodesAmount;
}
template <class T>
void BinaryTree<T>::remove(T value) {
_remove(this->root, value);
}
template <class T>
TreeNode<T>* BinaryTree<T>::_changeRoot_Right(TreeNode<T>*& node) {
auto *iter = node->right;
while (iter->left) iter = iter->left;
if (iter == node->right) {
iter->left = node->left;
}
else {
iter->parent->left = iter->right;
iter->right = node->right;
iter->left = node->left;
}
return iter;
}
template <class T>
TreeNode<T>* BinaryTree<T>::_changeRoot_Left(TreeNode<T>*& node) {
auto *iter = node->left;
while (iter->right) iter = iter->right;
if (iter == node->left) {
iter->right = node->right;
}
else {
iter->parent->right = iter->left;
iter->left = node->left;
iter->right = node->right;
}
return iter;
}
template <class T>
void BinaryTree<T>::_remove(TreeNode<T>* &node, T value) {
if (!node) {
return;
}
if (node->val() == value) {
TreeNode<T> *iter = nullptr;
if (node->left || node->right) {
if (node->right)
iter = _changeRoot_Right(node);
else
iter = _changeRoot_Left(node);
}
delete node;
node = iter;
nodesAmount--;
return;
}
if (node->val() < value) {
_remove( node->right, value );
} else {
_remove( node->left, value );
}
}
template <class T>
bool BinaryTree<T>::search(T value) {
return _search(this->root, value);
}
template <class T>
bool BinaryTree<T>::_search(TreeNode<T>*& node, T value) {
if (!node)
return false;
if (node->val() == value)
return true;
if ( node->val() > value )
return _search( node->left, value );
else
return _search( node->right, value );
}
template <class T>
void BinaryTree<T>::insert(T value) {
TreeNode<T> *node = new TreeNode<T>(value);
_insert(this->root, nullptr, node);
}
template <class T>
void BinaryTree<T>::_insert(TreeNode<T>*& node, TreeNode<T>* parent, TreeNode<T>* value) {
if (!node) {
node = value;
node->parent = parent;
nodesAmount++;
return;
}
if ( node->val() > value->val() )
_insert( node->left, node, value );
else
_insert( node->right, node, value );
}
template <class T>
LinkedList<T> BinaryTree<T>::preOrder() {
LinkedList<T> list;
_preOrder(root, list);
return list;
}
template <class T>
void BinaryTree<T>::_preOrder(TreeNode<T>*&root, LinkedList<T> &list) {
if (!root) {
return;
} else {
list.push_back(root->val());
_preOrder(root->left, list);
_preOrder(root->right, list);
}
}
template <class T>
LinkedList<T> BinaryTree<T>::postOrder() {
LinkedList<T> list;
_postOrder(root, list);
return list;
}
template <class T>
void BinaryTree<T>::_postOrder(TreeNode<T>*& root, LinkedList<T>& list) {
if (!root) {
return;
} else {
_postOrder(root->left, list);
_postOrder(root->right, list);
list.push_back(root->val());
}
}
template <class T>
LinkedList<T> BinaryTree<T>::inOrder() {
LinkedList<T> list;
_inOrder(root, list);
return list;
}
template <class T>
void BinaryTree<T>::_inOrder(TreeNode<T>*&root, LinkedList<T> &list) {
if (!root) {
return;
} else {
_inOrder(root->left, list);
list.push_back(root->val());
_inOrder(root->right, list);
}
} | 18.698324 | 91 | 0.639976 | JOSUERV99 |
3c2e24a33581a9d61cc002352c0a0ee1b73c55b6 | 1,032 | cpp | C++ | src/math.cpp | AnttiVainio/Ray-tracer | 0843aeb490b14417d47b844ebaa4174617833568 | [
"Unlicense"
] | null | null | null | src/math.cpp | AnttiVainio/Ray-tracer | 0843aeb490b14417d47b844ebaa4174617833568 | [
"Unlicense"
] | null | null | null | src/math.cpp | AnttiVainio/Ray-tracer | 0843aeb490b14417d47b844ebaa4174617833568 | [
"Unlicense"
] | null | null | null | /** math.cpp **/
#include <cmath>
float clampi(const int value, const int min, const int max) {
if(value < min) return min;
else if(value > max) return max;
else return value;
}
float clampf(const float value, const float min, const float max) {
if(value < min) return min;
else if(value > max) return max;
else return value;
}
float calc_distance(const float x1, const float y1, const float x2, const float y2) {
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
float calc_distance_fast(const float x1, const float y1, const float x2, const float y2) {
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}
float mix(const float x1, const float x2, const float y1, const float y2, const float x) {
return (y1 - y2) / (x1 - x2) * (x - x1) + y1;
}
float calc_angle(const float x1, const float y1, const float x2, const float y2) {
return atan2(y2 - y1, x2 - x1);
}
float min(const float a, const float b) {
return a < b ? a : b;
}
float max(const float a, const float b) {
return a > b ? a : b;
}
| 25.8 | 90 | 0.643411 | AnttiVainio |
3c2f76aed48ae929f69cc8cce2578b324b81d5f4 | 4,549 | cpp | C++ | dali-toolkit/internal/text/color-segmentation.cpp | zyndor/dali-toolkit | 9e3fd659c4d25706ab65345bc7c562ac27248325 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | dali-toolkit/internal/text/color-segmentation.cpp | zyndor/dali-toolkit | 9e3fd659c4d25706ab65345bc7c562ac27248325 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2020-10-19T15:47:43.000Z | 2020-10-19T15:47:43.000Z | dali-toolkit/internal/text/color-segmentation.cpp | zyndor/dali-toolkit | 9e3fd659c4d25706ab65345bc7c562ac27248325 | [
"Apache-2.0",
"BSD-3-Clause"
] | 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.
*
*/
// FILE HEADER
#include <dali-toolkit/internal/text/color-segmentation.h>
// EXTERNAL INCLUDES
// INTERNAL INCLUDES
#include <iostream>
namespace Dali
{
namespace Toolkit
{
namespace Text
{
/**
* @brief Finds a color in the vector of colors.
* It inserts the color in the vector if it's not in.
*
* @param[in,out] colors The vector of colors.
* @param[in] color The color to find.
*
* @return The index + 1 where the color is in the vector. The index zero is reserved for the default color.
*/
ColorIndex FindColor( Vector<Vector4>& colors,
const Vector4& color )
{
ColorIndex index = 1u; // The index zero is reserved for the default color.
for( Vector<Vector4>::Iterator it = colors.Begin(),
endIt = colors.End();
it != endIt;
++it )
{
if( color == *it )
{
return index;
}
++index;
}
colors.PushBack( color );
return index;
}
void SetColorSegmentationInfo( const Vector<ColorRun>& colorRuns,
const Vector<GlyphIndex>& charactersToGlyph,
const Vector<Length>& glyphsPerCharacter,
CharacterIndex startCharacterIndex,
GlyphIndex startGlyphIndex,
Length numberOfCharacters,
Vector<Vector4>& colors,
Vector<ColorIndex>& colorIndices )
{
if( 0u == charactersToGlyph.Count() )
{
// Nothing to do if there is no text.
return;
}
// Get pointers to the buffers.
const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
// Calculate the number of glyphs to insert.
const CharacterIndex lastCharacterIndex = startCharacterIndex + numberOfCharacters - 1u;
const Length numberOfNewGlyphs = *( charactersToGlyphBuffer + lastCharacterIndex ) + *( glyphsPerCharacterBuffer + lastCharacterIndex ) - *( charactersToGlyphBuffer + startCharacterIndex );
// Reserve space for the new color indices.
Vector<ColorIndex> newColorIndices;
newColorIndices.Resize( numberOfNewGlyphs );
ColorIndex* newColorIndicesBuffer = newColorIndices.Begin();
// Convert from characters to glyphs.
Length index = 0u;
for( Vector<ColorRun>::ConstIterator it = colorRuns.Begin(),
endIt = colorRuns.End();
it != endIt;
++it, ++index )
{
const ColorRun& colorRun = *it;
if( ( startCharacterIndex < colorRun.characterRun.characterIndex + colorRun.characterRun.numberOfCharacters ) &&
( colorRun.characterRun.characterIndex < startCharacterIndex + numberOfCharacters ) )
{
if( 0u < colorRun.characterRun.numberOfCharacters )
{
// Find the color index.
const ColorIndex colorIndex = FindColor( colors, colorRun.color );
// Get the index to the last character of the run.
const CharacterIndex lastIndex = colorRun.characterRun.characterIndex + colorRun.characterRun.numberOfCharacters - 1u;
const GlyphIndex glyphIndex = std::max( startGlyphIndex, *( charactersToGlyphBuffer + colorRun.characterRun.characterIndex ) ) - startGlyphIndex;
// Get the number of glyphs of the run.
const Length lastGlyphIndexPlusOne = std::min( numberOfNewGlyphs, *( charactersToGlyphBuffer + lastIndex ) + *( glyphsPerCharacterBuffer + lastIndex ) - startGlyphIndex );
// Set the indices.
for( GlyphIndex i = glyphIndex; i < lastGlyphIndexPlusOne; ++i )
{
*( newColorIndicesBuffer + i ) = colorIndex;
}
}
}
}
// Insert the new indices.
colorIndices.Insert( colorIndices.Begin() + startGlyphIndex,
newColorIndices.Begin(),
newColorIndices.End() );
}
} // namespace Text
} // namespace Toolkit
} // namespace Dali
| 32.492857 | 191 | 0.659925 | zyndor |
3c312619085b24fa40f523785a0851f23a99d672 | 735 | cpp | C++ | jni/exnihilope/items/tools/HammerBase.cpp | SmartDEVTeam/ExNihiloPE | 8a3636ff72456a6ae156f23ea79d871fa3721754 | [
"Apache-2.0"
] | 5 | 2017-03-02T18:58:02.000Z | 2017-07-14T06:26:52.000Z | jni/exnihilope/items/tools/HammerBase.cpp | Virtualoso/ExNihiloPE | 8a3636ff72456a6ae156f23ea79d871fa3721754 | [
"Apache-2.0"
] | 3 | 2017-03-06T19:37:43.000Z | 2017-06-09T17:48:39.000Z | jni/exnihilope/items/tools/HammerBase.cpp | Virtualoso/ExNihiloPE | 8a3636ff72456a6ae156f23ea79d871fa3721754 | [
"Apache-2.0"
] | 5 | 2017-03-05T03:50:19.000Z | 2017-06-12T09:57:31.000Z | #include "HammerBase.h"
#include "../ENItems.h"
#include "database/HammerDatabase.h"
#include "../../registries/HammerRegistry.h"
HammerBase::HammerBase(const std::string& name, int id, int maxUses, Item::Tier material)
: ToolItem(name, id, 0.0F, material, {}) {
setMaxDamage(maxUses);
miningLevel = material.harvestLevel;
HammerDatabase::registerHammer(this);
}
int HammerBase::getMiningLevel(const ItemInstance& item) {
return miningLevel;
}
float HammerBase::getDestroySpeed(const ItemInstance& item, const Block& block) const {
return HammerRegistry::registered(&block) ? efficiencyOnProperMaterial : 1.0F;
}
bool HammerBase::canDestroySpecial(Block const& block) const {
return HammerRegistry::registered(&block);
}
| 27.222222 | 89 | 0.757823 | SmartDEVTeam |
3c39917678cf0fe690056f0f0246befd7a865b6c | 2,571 | cpp | C++ | Equinox/MeshComponent.cpp | jowie94/EquinoxEngine | 45f5efaa00e35a264bf3537ec3bdfe8b221325bf | [
"MIT"
] | null | null | null | Equinox/MeshComponent.cpp | jowie94/EquinoxEngine | 45f5efaa00e35a264bf3537ec3bdfe8b221325bf | [
"MIT"
] | null | null | null | Equinox/MeshComponent.cpp | jowie94/EquinoxEngine | 45f5efaa00e35a264bf3537ec3bdfe8b221325bf | [
"MIT"
] | 1 | 2018-10-16T20:12:59.000Z | 2018-10-16T20:12:59.000Z | #include "MeshComponent.h"
#include "GameObject.h"
#include <GL/glew.h>
#include "IMGUI/imgui.h"
#include "ProgramManager.h"
MeshComponent::MeshComponent()
{
_programManager = App->GetModule<ProgramManager>();
_shaderUnlit = _programManager->GetProgramByName("Unlit");
}
MeshComponent::~MeshComponent()
{
}
void MeshComponent::Update(float dt)
{
if (Parent->VisibleOnCamera)
{
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
for (Mesh* mesh : Meshes)
{
glColor3f(1.f, 1.f, 1.f);
Material* mat = MaterialComponent->Materials[mesh->materialInComponent];
glMaterialfv(GL_FRONT, GL_AMBIENT, reinterpret_cast<GLfloat*>(&mat->ambient));
glMaterialfv(GL_FRONT, GL_DIFFUSE, reinterpret_cast<GLfloat*>(&mat->diffuse));
glMaterialfv(GL_FRONT, GL_SPECULAR, reinterpret_cast<GLfloat*>(&mat->specular));
glMaterialf(GL_FRONT, GL_SHININESS, mat->shininess);
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertexID);
glVertexPointer(3, GL_FLOAT, 0, nullptr);
if (mesh->normalID != 0)
{
glBindBuffer(GL_ARRAY_BUFFER, mesh->normalID);
glNormalPointer(GL_FLOAT, 0, nullptr);
}
_programManager->UseProgram(_shaderUnlit);
int diffuse_id = glGetUniformLocation(_shaderUnlit->id, "diffuse");
int useColor_id = glGetUniformLocation(_shaderUnlit->id, "useColor");
if (mesh->textureCoordsID && 0 != mat->texture)
{
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, mesh->textureCoordsID);
glTexCoordPointer(3, GL_FLOAT, 0, nullptr);
glUniform1i(useColor_id, 0);
}
else
{
glUniform1i(useColor_id, 1);
}
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mat->texture);
glUniform1i(diffuse_id, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->indexesID);
glDrawElements(GL_TRIANGLES, mesh->num_indices, GL_UNSIGNED_INT, nullptr);
glMaterialfv(GL_FRONT, GL_AMBIENT, DEFAULT_GL_AMBIENT);
glMaterialfv(GL_FRONT, GL_DIFFUSE, DEFAULT_GL_DIFFUSE);
glMaterialfv(GL_FRONT, GL_SPECULAR, DEFAULT_GL_SPECULAR);
glMaterialf(GL_FRONT, GL_SHININESS, DEFAULT_GL_SHININESS);
_programManager->UseDefaultProgram();
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_COLOR_MATERIAL);
glDisable(GL_LIGHTING);
}
}
void MeshComponent::EditorUpdate(float dt)
{
Update(dt);
}
| 27.351064 | 83 | 0.74718 | jowie94 |
3c3dcaadef89a8378ca111b478ca84babc1a94a4 | 303 | cpp | C++ | soj/1967.cpp | huangshenno1/project_euler | 8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d | [
"MIT"
] | null | null | null | soj/1967.cpp | huangshenno1/project_euler | 8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d | [
"MIT"
] | null | null | null | soj/1967.cpp | huangshenno1/project_euler | 8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d | [
"MIT"
] | null | null | null | #include <stdio.h>
int main()
{
double a,b,c,d,e;
scanf("%lf%lf%lf%lf%lf",&a,&b,&c,&d,&e);
while (a||b||c||d||e)
{
double s=a+b+c+d+e;
if (s<0&&s>-0.001)
s=0;
printf("%.3lf\n",s);
scanf("%lf%lf%lf%lf%lf",&a,&b,&c,&d,&e);
}
return 0;
} | 18.9375 | 48 | 0.40264 | huangshenno1 |
3c3e0a8e63feabc4fbe6d4270570a5552f451fa6 | 1,116 | cpp | C++ | test/test_shared_ptr.cpp | jb--/luaponte | 06bfe551bce23e411e75895797b8bb84bb662ed2 | [
"BSL-1.0"
] | 3 | 2015-08-30T10:02:10.000Z | 2018-08-27T06:54:44.000Z | test/test_shared_ptr.cpp | halmd-org/luaponte | 165328485954a51524a0b1aec27518861c6be719 | [
"BSL-1.0"
] | null | null | null | test/test_shared_ptr.cpp | halmd-org/luaponte | 165328485954a51524a0b1aec27518861c6be719 | [
"BSL-1.0"
] | null | null | null | // Luaponte library
// Copyright (c) 2012 Peter Colberg
// Luaponte is based on Luabind, a library, inspired by and similar to
// Boost.Python, that helps you create bindings between C++ and Lua,
// Copyright (c) 2003-2010 Daniel Wallin and Arvid Norberg.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "test.hpp"
#include <luaponte/luaponte.hpp>
#include <luaponte/shared_ptr_converter.hpp>
struct X
{
X(int value)
: value(value)
{}
int value;
};
int get_value(std::shared_ptr<X> const& p)
{
return p->value;
}
std::shared_ptr<X> filter(std::shared_ptr<X> const& p)
{
return p;
}
void test_main(lua_State* L)
{
using namespace luaponte;
module(L) [
class_<X>("X")
.def(constructor<int>()),
def("get_value", &get_value),
def("filter", &filter)
];
DOSTRING(L,
"x = X(1)\n"
"assert(get_value(x) == 1)\n"
);
DOSTRING(L,
"assert(x == filter(x))\n"
);
}
| 19.928571 | 79 | 0.625448 | jb-- |
3c3ef6207336367e931eeb52c2fb1d47207557f9 | 591 | cxx | C++ | source/boomhs/skybox.cxx | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | 2 | 2016-07-22T10:09:21.000Z | 2017-09-16T06:50:01.000Z | source/boomhs/skybox.cxx | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | 14 | 2016-08-13T22:45:56.000Z | 2018-12-16T03:56:36.000Z | source/boomhs/skybox.cxx | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | null | null | null | #include <boomhs/frame_time.hpp>
#include <boomhs/math.hpp>
#include <boomhs/skybox.hpp>
#include <opengl/shader.hpp>
#include <opengl/texture.hpp>
#include <cassert>
namespace boomhs
{
static constexpr float SKYBOX_SCALE_SIZE = 1000.0f;
///////////////////////////////////////////////////////////////////////////////////////////////////
// Skybox
Skybox::Skybox()
: speed_(10.0f)
{
transform_.scale = glm::vec3{SKYBOX_SCALE_SIZE};
}
void
Skybox::update(FrameTime const& ft)
{
transform_.rotate_degrees(speed_ * ft.delta_millis(), math::EulerAxis::Y);
}
} // namespace boomhs
| 19.7 | 99 | 0.604061 | bjadamson |
3c3faedcaa1fef265e6932d968441b1a43936539 | 18,259 | cpp | C++ | Grbl_Esp32/src/Motors/Dynamixel2.cpp | ghjklzx/ESP32-E-support | 03e081d3f6df613ff1f215ba311bec3fb7baa8ed | [
"MIT"
] | null | null | null | Grbl_Esp32/src/Motors/Dynamixel2.cpp | ghjklzx/ESP32-E-support | 03e081d3f6df613ff1f215ba311bec3fb7baa8ed | [
"MIT"
] | null | null | null | Grbl_Esp32/src/Motors/Dynamixel2.cpp | ghjklzx/ESP32-E-support | 03e081d3f6df613ff1f215ba311bec3fb7baa8ed | [
"MIT"
] | null | null | null | /*
Dynamixel2.cpp
This allows an Dynamixel sero to be used like any other motor. Servos
do have limitation in travel and speed, so you do need to respect that.
Protocol 2
Part of Grbl_ESP32
2020 - Bart Dring
https://emanual.robotis.com/docs/en/dxl/protocol2/
Grbl_ESP32 is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Grbl is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Grbl. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Dynamixel2.h"
namespace Motors {
bool Motors::Dynamixel2::uart_ready = false;
uint8_t Motors::Dynamixel2::ids[MAX_N_AXIS][2] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
Dynamixel2::Dynamixel2(uint8_t axis_index, uint8_t id, uint8_t tx_pin, uint8_t rx_pin, uint8_t rts_pin) :
Servo(axis_index), _id(id), _tx_pin(tx_pin), _rx_pin(rx_pin), _rts_pin(rts_pin) {
if (_tx_pin == UNDEFINED_PIN || _rx_pin == UNDEFINED_PIN || _rts_pin == UNDEFINED_PIN) {
grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "Dynamixel Error. Missing pin definitions");
_has_errors = true;
} else {
_has_errors = false; // The motor can be used
}
}
void Dynamixel2::init() {
init_uart(_id, _axis_index, _dual_axis_index); // static and only allows one init
read_settings();
config_message(); // print the config
if (!test()) { // ping the motor
_has_errors = true;
return;
}
set_disable(true); // turn off torque so we can set EEPROM registers
set_operating_mode(DXL_CONTROL_MODE_POSITION); // set it in the right control mode
// servos will blink in axis order for reference
LED_on(true);
vTaskDelay(100);
LED_on(false);
startUpdateTask();
}
void Dynamixel2::config_message() {
grbl_msg_sendf(CLIENT_SERIAL,
MsgLevel::Info,
"%s Dynamixel Servo ID:%d Count(%5.0f,%5.0f) %s",
reportAxisNameMsg(_axis_index, _dual_axis_index),
_id,
_dxl_count_min,
_dxl_count_max,
reportAxisLimitsMsg(_axis_index));
}
bool Dynamixel2::test() {
uint16_t len = 3;
_dxl_tx_message[DXL_MSG_INSTR] = DXL_INSTR_PING;
dxl_finish_message(_id, _dxl_tx_message, len);
len = dxl_get_response(PING_RSP_LEN); // wait for and get response
if (len == PING_RSP_LEN) {
uint16_t model_num = _dxl_rx_message[10] << 8 | _dxl_rx_message[9];
if (model_num == 1060) {
grbl_msg_sendf(CLIENT_SERIAL,
MsgLevel::Info,
"%s Dynamixel Detected ID %d Model XL430-W250 F/W Rev %x",
reportAxisNameMsg(_axis_index, _dual_axis_index),
_id,
_dxl_rx_message[11]);
} else {
grbl_msg_sendf(CLIENT_SERIAL,
MsgLevel::Info,
"%s Dynamixel Detected ID %d M/N %d F/W Rev %x",
reportAxisNameMsg(_axis_index, _dual_axis_index),
_id,
model_num,
_dxl_rx_message[11]);
}
} else {
grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "%s Dynamixel Servo ID %d Ping failed", reportAxisNameMsg(_axis_index, _dual_axis_index),
_id);
return false;
}
return true;
}
void Dynamixel2::read_settings() {
_dxl_count_min = DXL_COUNT_MIN;
_dxl_count_max = DXL_COUNT_MAX;
if (bitnum_istrue(dir_invert_mask->get(), _axis_index)) // normal direction
swap(_dxl_count_min, _dxl_count_min);
}
// sets the PWM to zero. This allows most servos to be manually moved
void Dynamixel2::set_disable(bool disable) {
uint8_t param_count = 1;
if (_disabled == disable)
return;
_disabled = disable;
dxl_write(DXL_ADDR_TORQUE_EN, param_count, !_disabled);
}
void Dynamixel2::set_operating_mode(uint8_t mode) {
uint8_t param_count = 1;
dxl_write(DXL_OPERATING_MODE, param_count, mode);
}
void Dynamixel2::update() {
if (_has_errors) {
return;
}
if (_disabled) {
dxl_read_position();
} else {
dxl_bulk_goal_position(); // call the static method that updates all at once
}
}
/*
Static
This will be called by each axis, but only the first call will setup the serial port.
It will store the IDs and Axes in an array for later group processing
*/
void Dynamixel2::init_uart(uint8_t id, uint8_t axis_index, uint8_t dual_axis_index) {
ids[axis_index][dual_axis_index] = id; // learn all the ids
if (uart_ready)
return; // UART already setup
grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "Dynamixel UART TX:%d RX:%d RTS:%d", DYNAMIXEL_TXD, DYNAMIXEL_RXD, DYNAMIXEL_RTS);
uart_driver_delete(UART_NUM_2);
// setup the comm port as half duplex
uart_config_t uart_config = {
.baud_rate = DYNAMIXEL_BAUD_RATE,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
.rx_flow_ctrl_thresh = 122,
};
// Configure UART parameters
uart_param_config(UART_NUM_2, &uart_config);
uart_set_pin(UART_NUM_2, DYNAMIXEL_TXD, DYNAMIXEL_RXD, DYNAMIXEL_RTS, UART_PIN_NO_CHANGE);
uart_driver_install(UART_NUM_2, DYNAMIXEL_BUF_SIZE * 2, 0, 0, NULL, 0);
uart_set_mode(UART_NUM_2, UART_MODE_RS485_HALF_DUPLEX);
uart_ready = true;
}
void Dynamixel2::set_location() {}
// This motor will not do a standard home to a limit switch (maybe future)
// If it is in the homing mask it will a quick move to $<axis>/Home/Mpos
bool Dynamixel2::set_homing_mode(bool isHoming) {
if (_has_errors) {
return false;
}
sys_position[_axis_index] =
axis_settings[_axis_index]->home_mpos->get() * axis_settings[_axis_index]->steps_per_mm->get(); // convert to steps
set_disable(false);
set_location(); // force the PWM to update now
return false; // Cannot do conventional homing
}
void Dynamixel2::dxl_goal_position(int32_t position) {
uint8_t param_count = 4;
dxl_write(DXL_GOAL_POSITION,
param_count,
(position & 0xFF),
(position & 0xFF00) >> 8,
(position & 0xFF0000) >> 16,
(position & 0xFF000000) >> 24);
}
uint32_t Dynamixel2::dxl_read_position() {
uint8_t data_len = 4;
dxl_read(DXL_PRESENT_POSITION, data_len);
data_len = dxl_get_response(15);
if (data_len == 15) {
uint32_t dxl_position = _dxl_rx_message[9] | (_dxl_rx_message[10] << 8) | (_dxl_rx_message[11] << 16) |
(_dxl_rx_message[12] << 24);
read_settings();
int32_t pos_min_steps = lround(limitsMinPosition(_axis_index) * axis_settings[_axis_index]->steps_per_mm->get());
int32_t pos_max_steps = lround(limitsMaxPosition(_axis_index) * axis_settings[_axis_index]->steps_per_mm->get());
int32_t temp = map(dxl_position, DXL_COUNT_MIN, DXL_COUNT_MAX, pos_min_steps, pos_max_steps);
sys_position[_axis_index] = temp;
plan_sync_position();
return dxl_position;
} else {
return 0;
}
}
void Dynamixel2::dxl_read(uint16_t address, uint16_t data_len) {
uint8_t msg_len = 3 + 4;
_dxl_tx_message[DXL_MSG_INSTR] = DXL_READ;
_dxl_tx_message[DXL_MSG_START] = (address & 0xFF); // low-order address value
_dxl_tx_message[DXL_MSG_START + 1] = ((address & 0xFF00) >> 8); // High-order address value
_dxl_tx_message[DXL_MSG_START + 2] = (data_len & 0xFF); // low-order data length value
_dxl_tx_message[DXL_MSG_START + 3] = ((data_len & 0xFF00) >> 8); // high-order address value
dxl_finish_message(_id, _dxl_tx_message, msg_len);
}
void Dynamixel2::LED_on(bool on) {
uint8_t param_count = 1;
if (on)
dxl_write(DXL_ADDR_LED_ON, param_count, 1);
else
dxl_write(DXL_ADDR_LED_ON, param_count, 0);
}
// wait for and get the servo response
uint16_t Dynamixel2::dxl_get_response(uint16_t length) {
length = uart_read_bytes(UART_NUM_2, _dxl_rx_message, length, DXL_RESPONSE_WAIT_TICKS);
return length;
}
void Dynamixel2::dxl_write(uint16_t address, uint8_t paramCount, ...) {
_dxl_tx_message[DXL_MSG_INSTR] = DXL_WRITE;
_dxl_tx_message[DXL_MSG_START] = (address & 0xFF); // low-order address value
_dxl_tx_message[DXL_MSG_START + 1] = ((address & 0xFF00) >> 8); // High-order address value
uint8_t msg_offset = 1; // this is the offset from DXL_MSG_START in the message
va_list valist;
/* Initializing arguments */
va_start(valist, paramCount);
for (int x = 0; x < paramCount; x++) {
msg_offset++;
_dxl_tx_message[DXL_MSG_START + msg_offset] = (uint8_t)va_arg(valist, int);
}
va_end(valist); // Cleans up the list
dxl_finish_message(_id, _dxl_tx_message, msg_offset + 4);
uint16_t len = 11; // response length
len = dxl_get_response(len);
if (len == 11) {
uint8_t err = _dxl_rx_message[8];
switch (err) {
case 1:
grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "Dynamixel Servo ID %d Write fail error", _id);
break;
case 2:
grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "Dynamixel Servo ID %d Write instruction error", _id);
break;
case 3:
grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "Dynamixel Servo ID %d Write access error", _id);
break;
case 4:
grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "Dynamixel Servo ID %d Write data range error", _id);
break;
case 5:
grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "Dynamixel Servo ID %d Write data length error", _id);
break;
case 6:
grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "Dynamixel Servo ID %d Write data limit error", _id);
break;
case 7:
grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "Dynamixel Servo ID %d Write access error", _id);
break;
default:
break;
}
} else {
// timeout
grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "Dynamixel Servo ID %d Timeout", _id);
}
}
/*
Static
This will sync all the motors in one command
It looks for IDs in the array of axes
*/
void Dynamixel2::dxl_bulk_goal_position() {
char tx_message[100]; // outgoing to dynamixel
float position_min, position_max;
float dxl_count_min, dxl_count_max;
uint16_t msg_index = DXL_MSG_INSTR; // index of the byte in the message we are currently filling
uint32_t dxl_position;
uint8_t count = 0;
uint8_t current_id;
tx_message[msg_index] = DXL_SYNC_WRITE;
tx_message[++msg_index] = DXL_GOAL_POSITION & 0xFF; // low order address
tx_message[++msg_index] = (DXL_GOAL_POSITION & 0xFF00) >> 8; // high order address
tx_message[++msg_index] = 4; // low order data length
tx_message[++msg_index] = 0; // high order data length
auto n_axis = number_axis->get();
for (uint8_t axis = X_AXIS; axis < n_axis; axis++) {
for (uint8_t gang_index = 0; gang_index < 2; gang_index++) {
current_id = ids[axis][gang_index];
if (current_id != 0) {
count++; // keep track of the count for the message length
//determine the location of the axis
float target = system_convert_axis_steps_to_mpos(sys_position, axis); // get the axis machine position in mm
dxl_count_min = DXL_COUNT_MIN;
dxl_count_max = DXL_COUNT_MAX;
if (bitnum_istrue(dir_invert_mask->get(), axis)) // normal direction
swap(dxl_count_min, dxl_count_max);
// map the mm range to the servo range
dxl_position = (uint32_t)mapConstrain(target, limitsMinPosition(axis), limitsMaxPosition(axis), dxl_count_min, dxl_count_max);
tx_message[++msg_index] = current_id; // ID of the servo
tx_message[++msg_index] = dxl_position & 0xFF; // data
tx_message[++msg_index] = (dxl_position & 0xFF00) >> 8; // data
tx_message[++msg_index] = (dxl_position & 0xFF0000) >> 16; // data
tx_message[++msg_index] = (dxl_position & 0xFF000000) >> 24; // data
}
}
}
dxl_finish_message(DXL_BROADCAST_ID, tx_message, (count * 5) + 7);
}
/*
Static
This is a helper function to complete and send the message
The body of the message should be in msg, at the correct location
before calling this function.
This function will add the header, length bytes and CRC
It will then send the message
*/
void Dynamixel2::dxl_finish_message(uint8_t id, char* msg, uint16_t msg_len) {
//uint16_t msg_len;
uint16_t crc = 0;
// header
msg[DXL_MSG_HDR1] = 0xFF;
msg[DXL_MSG_HDR2] = 0xFF;
msg[DXL_MSG_HDR3] = 0xFD;
//
// reserved
msg[DXL_MSG_RSRV] = 0x00;
msg[DXL_MSG_ID] = id;
// length
msg[DXL_MSG_LEN_L] = msg_len & 0xFF;
msg[DXL_MSG_LEN_H] = (msg_len & 0xFF00) >> 8;
// the message should already be here
crc = dxl_update_crc(crc, msg, 5 + msg_len);
msg[msg_len + 5] = crc & 0xFF; // CRC_L
msg[msg_len + 6] = (crc & 0xFF00) >> 8;
uart_flush(UART_NUM_2);
uart_write_bytes(UART_NUM_2, msg, msg_len + 7);
}
// from http://emanual.robotis.com/docs/en/dxl/crc/
uint16_t Dynamixel2::dxl_update_crc(uint16_t crc_accum, char* data_blk_ptr, uint8_t data_blk_size) {
uint16_t i, j;
uint16_t crc_table[256] = {
0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011, 0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022,
0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072, 0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041,
0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2, 0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1,
0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1, 0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082,
0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192, 0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1,
0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1, 0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2,
0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151, 0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162,
0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132, 0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101,
0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312, 0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321,
0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371, 0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342,
0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1, 0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2,
0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2, 0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381,
0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291, 0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2,
0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2, 0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1,
0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252, 0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261,
0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231, 0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202
};
for (j = 0; j < data_blk_size; j++) {
i = ((uint16_t)(crc_accum >> 8) ^ data_blk_ptr[j]) & 0xFF;
crc_accum = (crc_accum << 8) ^ crc_table[i];
}
return crc_accum;
}
}
| 41.216704 | 147 | 0.589189 | ghjklzx |
3c47a2f5710b42cd42e747b2c78939397130f039 | 2,249 | cpp | C++ | part-17-vulkan-android/main/src/application/vulkan/vulkan-context.cpp | tanzle-aames/a-simple-triangle | 3cf7d76e8e8a3b5d42c6db35d3cbfef91b139ab0 | [
"MIT"
] | 52 | 2019-11-30T04:45:02.000Z | 2022-03-10T17:17:57.000Z | part-19-vulkan-windows/main/src/application/vulkan/vulkan-context.cpp | eugenebokhan/a-simple-triangle | 3cf7d76e8e8a3b5d42c6db35d3cbfef91b139ab0 | [
"MIT"
] | null | null | null | part-19-vulkan-windows/main/src/application/vulkan/vulkan-context.cpp | eugenebokhan/a-simple-triangle | 3cf7d76e8e8a3b5d42c6db35d3cbfef91b139ab0 | [
"MIT"
] | 10 | 2020-03-30T16:18:30.000Z | 2022-01-30T14:53:45.000Z | #include "vulkan-context.hpp"
#include "../../core/graphics-wrapper.hpp"
#include "../../core/log.hpp"
#include "vulkan-common.hpp"
using ast::VulkanContext;
namespace
{
vk::UniqueInstance createInstance()
{
vk::ApplicationInfo applicationInfo{
"A Simple Triangle", // Application name
VK_MAKE_VERSION(1, 0, 0), // Application version
"A Simple Triangle", // Engine name
VK_MAKE_VERSION(1, 0, 0), // Engine version
VK_MAKE_VERSION(1, 0, 0) // Vulkan API version
};
// Find out what the mandatory Vulkan extensions are on the current device,
// by this stage we would have already determined that the extensions are
// available via the 'ast::vulkan::isVulkanAvailable()' call in our main engine.
std::vector<std::string> requiredExtensionNames{
ast::vulkan::getRequiredVulkanExtensionNames()};
// Pack the extension names into a data format consumable by Vulkan.
std::vector<const char*> extensionNames;
for (const auto& extension : requiredExtensionNames)
{
extensionNames.push_back(extension.c_str());
}
// Define the info for creating our Vulkan instance.
vk::InstanceCreateInfo instanceCreateInfo{
vk::InstanceCreateFlags(), // Flags
&applicationInfo, // Application info
0, // Enabled layer count
nullptr, // Enabled layer names
static_cast<uint32_t>(extensionNames.size()), // Enabled extension count
extensionNames.data() // Enabled extension names
};
// Build a new Vulkan instance from the configuration.
return vk::createInstanceUnique(instanceCreateInfo);
}
} // namespace
struct VulkanContext::Internal
{
const vk::UniqueInstance instance;
Internal() : instance(::createInstance())
{
ast::log("ast::VulkanContext", "Initialized Vulkan context successfully.");
}
};
VulkanContext::VulkanContext() : internal(ast::make_internal_ptr<Internal>()) {}
| 38.118644 | 88 | 0.59671 | tanzle-aames |
3c4a1565dc866cd5a9fad9faed0d4aa721d1d50c | 1,270 | hpp | C++ | src/channel_access/server/cas/async.hpp | delta-accelerator/channel_access.server | 21a7707da1f3421ed38773095e577f48b798daac | [
"MIT"
] | null | null | null | src/channel_access/server/cas/async.hpp | delta-accelerator/channel_access.server | 21a7707da1f3421ed38773095e577f48b798daac | [
"MIT"
] | null | null | null | src/channel_access/server/cas/async.hpp | delta-accelerator/channel_access.server | 21a7707da1f3421ed38773095e577f48b798daac | [
"MIT"
] | null | null | null | #ifndef INCLUDE_GUARD_89374487_8D33_448E_B992_AA6B5C8548A5
#define INCLUDE_GUARD_89374487_8D33_448E_B992_AA6B5C8548A5
#include <Python.h>
#include <casdef.h>
namespace cas {
/** Create the AsyncContext type.
* Returns new reference.
*/
PyObject* create_async_context_type();
/** Destroy the AsyncContext type.
*/
void destroy_async_context_type();
/** Create the AsyncRead type.
* Returns new reference.
*/
PyObject* create_async_read_type();
/** Destroy the AsyncRead type.
*/
void destroy_async_read_type();
/** Create the AsyncWrite type.
* Returns new reference.
*/
PyObject* create_async_write_type();
/** Destroy the AsyncWrite type.
*/
void destroy_async_write_type();
/** Create an asnyc context object.
* Returns new reference.
*/
PyObject* create_async_context(casCtx const& ctx, gdd* prototype, aitEnum type);
/** Try to give an async read handler object to the server.
*
* Returns:
* ``True`` if the object is an async read object and is given to the server.
*/
bool give_async_read_to_server(PyObject* obj);
/** Try to give an async write handler object to the server.
*
* Returns:
* ``True`` if the object is an async write object and is given to the server.
*/
bool give_async_write_to_server(PyObject* obj);
}
#endif
| 20.819672 | 80 | 0.740945 | delta-accelerator |
3c4e3c8e5c4edeccd4edbed3badcff012df59271 | 115 | cpp | C++ | hts_CutTrim/src/hts_CutTrim.cpp | s4hts/HTStream | 7dffe3ed890996b3e83676d8a25fbbb3a85b81ff | [
"Apache-2.0"
] | 19 | 2020-06-01T17:25:37.000Z | 2022-03-17T04:54:03.000Z | hts_CutTrim/src/hts_CutTrim.cpp | ibest/HTStream | b2d7b408de79e643f560214536985e25a7153510 | [
"Apache-2.0"
] | 167 | 2016-07-31T23:34:59.000Z | 2020-05-31T15:07:16.000Z | hts_CutTrim/src/hts_CutTrim.cpp | ibest/HTStream | b2d7b408de79e643f560214536985e25a7153510 | [
"Apache-2.0"
] | 7 | 2017-06-08T17:10:26.000Z | 2020-04-03T20:54:55.000Z | #include "hts_CutTrim.h"
int main(int argc, char** argv)
{
CutTrim ct;
return ct.main_func(argc, argv);
}
| 14.375 | 36 | 0.652174 | s4hts |
3c4eaadf9318c2cb43717d624b112de0116a76fe | 1,082 | cpp | C++ | 洛谷/线性表/P1540.cpp | codehuanglei/- | 933a55b5c5a49163f12e0c39b4edfa9c4f01678f | [
"MIT"
] | null | null | null | 洛谷/线性表/P1540.cpp | codehuanglei/- | 933a55b5c5a49163f12e0c39b4edfa9c4f01678f | [
"MIT"
] | null | null | null | 洛谷/线性表/P1540.cpp | codehuanglei/- | 933a55b5c5a49163f12e0c39b4edfa9c4f01678f | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll m, n;
queue<int> q1;
bool findNum = false;
int main(){
cin >> m >> n;
int cnt = 0;
for(int i = 1; i <= n; i++){
int num;
cin >> num;
if(q1.empty()){
q1.push(num);
cnt++;
}else{
queue<int> q2, temp;
for(int i = 0; i <= q1.size(); i++){
int search = q1.front();
if(num == search){// 如果队列中找到了
findNum = true;
}
q2.push(q1.front());
q1.pop();
}
temp = q2;
q2 = q1;
q1 = temp;
if(q1.size() < 3 && findNum == false){
q1.push(num);
cnt++;
}else if(q1.size() == 3 && findNum == false){
q1.pop();
q1.push(num);
cnt++;
}
findNum = false;
}
cout<<q1.size()<<" "<<q1.front()<<" "<<q1.back()<<endl;
}
cout<<cnt;
return 0;
}// 1 2 | 25.162791 | 63 | 0.357671 | codehuanglei |
3c4ee5d7c6e46a12a88f062cdc33832ade97488e | 1,106 | cpp | C++ | Array/easy/628_Maximum_Product_of_Three_Numbers/MaxProductOfThree.cpp | quq99/Leetcode_notes | eb3bee5ed161a0feb4ce1d48b682c000c95b4be3 | [
"MIT"
] | 1 | 2019-05-16T23:18:17.000Z | 2019-05-16T23:18:17.000Z | Array/easy/628_Maximum_Product_of_Three_Numbers/MaxProductOfThree.cpp | quq99/Leetcode_notes | eb3bee5ed161a0feb4ce1d48b682c000c95b4be3 | [
"MIT"
] | null | null | null | Array/easy/628_Maximum_Product_of_Three_Numbers/MaxProductOfThree.cpp | quq99/Leetcode_notes | eb3bee5ed161a0feb4ce1d48b682c000c95b4be3 | [
"MIT"
] | null | null | null | // MaxProductOfThree
#include<vector>
#include<algorithm>
using std::max;
using std::vector;
class MaxProductOfThree {
public:
int maximumProduct(vector<int>& nums) {
int max1 = INT_MIN; // biggest
int max2 = INT_MIN; // second biggest
int max3 = INT_MIN; // third biggest
int min1 = INT_MAX; // smallest
int min2 = INT_MAX; // second smallest
for (int num : nums) {
if (num > max1) {
max3 = max2;
max2 = max1;
max1 = num;
}
else if (num > max2) {
max3 = max2;
max2 = num;
}
else if (num > max3) {
max3 = num;
}
if (num < min1) {
min2 = min1;
min1 = num;
}
else if (num < min2) {
min2 = num;
}
}
return max(max1*max2*max3, min1*min2*max1);
}
};
| 25.72093 | 55 | 0.382459 | quq99 |
3c4f3dea70e05232404797bf0e045771f477d4f6 | 1,207 | hpp | C++ | afin/contiglist.hpp | kemendle/Fast-Plast | 2ed15a87192ea3423915cccba3fc0d970c8c672e | [
"MIT"
] | 31 | 2016-08-15T20:54:16.000Z | 2021-11-22T08:16:06.000Z | afin/contiglist.hpp | kemendle/Fast-Plast | 2ed15a87192ea3423915cccba3fc0d970c8c672e | [
"MIT"
] | 46 | 2016-08-16T19:25:11.000Z | 2021-04-12T13:05:03.000Z | afin/contiglist.hpp | kemendle/Fast-Plast | 2ed15a87192ea3423915cccba3fc0d970c8c672e | [
"MIT"
] | 20 | 2016-08-19T16:05:00.000Z | 2021-11-22T08:16:10.000Z |
#ifndef CONTIGLIST_HPP
#define CONTIGLIST_HPP
#include "contig.hpp"
#include <vector>
#include <string>
class Contiglist{
private:
Readlist *reads;
std::vector<Contig> contigs;
std::vector<Contig> contigs_fused;
std::string outfile;
public:
Contiglist( Readlist *reads, std::string contigsfiles, std::string outfile );
// return contig at index ind
Contig get_contig( int ind );
// return contig at index ind
Contig *get_contig_ref( int ind );
// return conitg list size
int get_list_size();
// remove contig at index ind
void remove_contig( int ind );
// append contig to contigs
void append_contig( int list_num, Contig cont );
// cycles through each contig and parses out the first section of the id
void parse_ids();
// put contigs from contfile into contlist
void add_contigs( std::string contigsfiles );
// print contigs
void output_contigs( int list_num, std::string file, std::string id_suffix );
// prints results to fasta file with outfile prefix and additional information is printed to a text based file with outfile prefix
void create_final_fasta( int current_iteration );
};
#endif
| 24.632653 | 134 | 0.70174 | kemendle |
3c54ad8053a919f340a1c52f08a27d3a9f3a5ac5 | 7,074 | cpp | C++ | components/CalEPD/models/color/gdew075c64.cpp | markbirss/cale-idf | a2271062504907a57333ea9615c115fbda809e19 | [
"Apache-2.0"
] | 148 | 2020-05-21T23:14:27.000Z | 2022-03-23T14:26:45.000Z | components/CalEPD/models/color/gdew075c64.cpp | markbirss/cale-idf | a2271062504907a57333ea9615c115fbda809e19 | [
"Apache-2.0"
] | 48 | 2020-05-19T07:23:48.000Z | 2022-03-19T11:04:02.000Z | components/CalEPD/models/color/gdew075c64.cpp | markbirss/cale-idf | a2271062504907a57333ea9615c115fbda809e19 | [
"Apache-2.0"
] | 17 | 2020-09-15T18:04:45.000Z | 2022-03-16T20:26:34.000Z | #include "gdew075c64.h"
#include <stdio.h>
#include <stdlib.h>
#include "esp_log.h"
#include "freertos/task.h"
// Controller: GD7965 (EK79655)
// Specification: https://www.scribd.com/document/448888338/GDEW075C64-V1-0-Specification
// 0x07 (2nd) VGH=20V,VGL=-20V
// 0x3f (1st) VDH= 15V
// 0x3f (2nd) VDH=-15V
DRAM_ATTR const epd_power_4 Gdew075C64::epd_wakeup_power = {
0x01, {0x07, 0x07, 0x3f, 0x3f}, 4};
DRAM_ATTR const epd_init_4 Gdew075C64::epd_resolution = {
0x61, {0x03, //source 800
0x20,
0x01, //gate 480
0xE0},
4};
// Note: Played with this settings. If is too high (In specs says 0x17) then
// yellow will get out from right side. Too low and won't be yellow enough (But is sill not 100% right)
// For me it looks more yellow on the top and more dark yellow on the bottom
DRAM_ATTR const epd_init_4 Gdew075C64::epd_boost={
0x06,{
0x17,
0x17,
0x25, /* Top part of the display get's more color on 0x16. On 0x18 get's too yellow and desbords on left side. On 0x17 is shit */
0x17},4
};
// Constructor
Gdew075C64::Gdew075C64(EpdSpi &dio) : Adafruit_GFX(GDEW075C64_WIDTH, GDEW075C64_HEIGHT),
Epd(GDEW075C64_WIDTH, GDEW075C64_HEIGHT), IO(dio)
{
printf("Gdew075C64() constructor injects IO and extends Adafruit_GFX(%d,%d) Pix Buffer[%d]\n",
GDEW075C64_WIDTH, GDEW075C64_HEIGHT, GDEW075C64_BUFFER_SIZE);
printf("\nAvailable heap after Epd bootstrap:%d\n", xPortGetFreeHeapSize());
}
//Initialize the display
void Gdew075C64::init(bool debug)
{
debug_enabled = debug;
if (debug_enabled)
printf("Gdew075C64::init(debug:%d)\n", debug);
//Initialize SPI at 4MHz frequency. true for debug
IO.init(4, false);
fillScreen(EPD_WHITE);
}
void Gdew075C64::fillScreen(uint16_t color)
{
uint8_t black = 0x00;
uint8_t red = 0x00;
if (color == EPD_WHITE);
else if (color == EPD_BLACK) black = 0xFF;
else if (color == EPD_RED) red = 0xFF;
else if ((color & 0xF100) > (0xF100 / 2)) red = 0xFF;
else if ((((color & 0xF100) >> 11) + ((color & 0x07E0) >> 5) + (color & 0x001F)) < 3 * 255 / 2) black = 0xFF;
for (uint16_t x = 0; x < sizeof(_buffer); x++)
{
_buffer[x] = black;
_color[x] = red;
}
}
void Gdew075C64::_wakeUp()
{
IO.reset(10);
//IMPORTANT: Some EPD controllers like to receive data byte per byte
//So this won't work:
//IO.data(epd_wakeup_power.data,epd_wakeup_power.databytes);
IO.cmd(epd_wakeup_power.cmd);
for (int i = 0; i < epd_wakeup_power.databytes; ++i)
{
IO.data(epd_wakeup_power.data[i]);
}
IO.cmd(0x04);
_waitBusy("_wakeUp power on");
// Panel setting
IO.cmd(0x00);
IO.data(0x0f); //KW: 3f, KWR: 2F, BWROTP: 0f, BWOTP: 1f
// PLL
IO.cmd(0x30);
IO.data(0x06);
// Resolution setting
IO.cmd(epd_resolution.cmd);
for (int i = 0; i < epd_resolution.databytes; ++i)
{
IO.data(epd_resolution.data[i]);
}
printf("Boost\n"); // Handles the intensity of the colors displayed
IO.cmd(epd_boost.cmd);
for (int i=0;i<sizeof(epd_boost.data);++i) {
IO.data(epd_boost.data[i]);
}
// Not sure if 0x15 is really needed, seems to work the same without it too
IO.cmd(0x15); // Dual SPI
IO.data(0x00); // MM_EN, DUSPI_EN
IO.cmd(0x50); // VCOM AND DATA INTERVAL SETTING
IO.data(0x11); // LUTKW, N2OCP: copy new to old
IO.data(0x07);
IO.cmd(0x60); // TCON SETTING
IO.data(0x22);
}
void Gdew075C64::update()
{
uint64_t startTime = esp_timer_get_time();
_using_partial_mode = false;
_wakeUp();
IO.cmd(0x10);
printf("Sending a %d bytes buffer via SPI\n", sizeof(_buffer));
// v2 SPI optimizing. Check: https://github.com/martinberlin/cale-idf/wiki/About-SPI-optimization
uint16_t i = 0;
uint8_t xLineBytes = GDEW075C64_WIDTH / 8;
uint8_t x1buf[xLineBytes];
for (uint16_t y = 1; y <= GDEW075C64_HEIGHT; y++)
{
for (uint16_t x = 1; x <= xLineBytes; x++)
{
uint8_t data = i < sizeof(_buffer) ? ~_buffer[i] : 0x00;
x1buf[x - 1] = data;
if (x == xLineBytes)
{ // Flush the X line buffer to SPI
IO.data(x1buf, sizeof(x1buf));
}
++i;
}
}
IO.cmd(0x13);
i = 0;
for (uint16_t y = 1; y <= GDEW075C64_HEIGHT; y++)
{
for (uint16_t x = 1; x <= xLineBytes; x++)
{
uint8_t data = i < sizeof(_color) ? _color[i] : 0x00;
x1buf[x - 1] = data;
if (x == xLineBytes)
{ // Flush the X line buffer to SPI
IO.data(x1buf, sizeof(x1buf));
}
++i;
}
}
uint64_t endTime = esp_timer_get_time();
IO.cmd(0x12);
_waitBusy("update");
uint64_t updateTime = esp_timer_get_time();
printf("\n\nSTATS (ms)\n%llu _wakeUp settings+send Buffer\n%llu update \n%llu total time in millis\n",
(endTime - startTime) / 1000, (updateTime - endTime) / 1000, (updateTime - startTime) / 1000);
_sleep();
}
void Gdew075C64::updateWindow(uint16_t x, uint16_t y, uint16_t w, uint16_t h, bool using_rotation)
{
printf("updateWindow: Not for color epapers of Goodisplay. Launching full update\n");
update();
}
void Gdew075C64::_waitBusy(const char *message)
{
if (debug_enabled)
{
ESP_LOGI(TAG, "_waitBusy for %s", message);
}
int64_t time_since_boot = esp_timer_get_time();
while (1)
{
if (gpio_get_level((gpio_num_t)CONFIG_EINK_BUSY) == 1)
break;
vTaskDelay(1);
if (esp_timer_get_time() - time_since_boot > 2000000)
{
if (debug_enabled)
ESP_LOGI(TAG, "Busy Timeout");
break;
}
}
}
void Gdew075C64::_sleep()
{
IO.cmd(0x02);
_waitBusy("power_off");
IO.cmd(0x07); // Deep sleep
IO.data(0xA5);
}
void Gdew075C64::_rotate(uint16_t &x, uint16_t &y, uint16_t &w, uint16_t &h)
{
switch (getRotation())
{
case 1:
swap(x, y);
swap(w, h);
x = GDEW075C64_WIDTH - x - w - 1;
break;
case 2:
x = GDEW075C64_WIDTH - x - w - 1;
y = GDEW075C64_HEIGHT - y - h - 1;
break;
case 3:
swap(x, y);
swap(w, h);
y = GDEW075C64_HEIGHT - y - h - 1;
break;
}
}
void Gdew075C64::drawPixel(int16_t x, int16_t y, uint16_t color)
{
if ((x < 0) || (x >= width()) || (y < 0) || (y >= height()))
return;
switch (getRotation())
{
case 1:
swap(x, y);
x = GDEW075C64_WIDTH - x - 1;
break;
case 2:
x = GDEW075C64_WIDTH - x - 1;
y = GDEW075C64_HEIGHT - y - 1;
break;
case 3:
swap(x, y);
y = GDEW075C64_HEIGHT - y - 1;
break;
}
uint16_t i = x / 8 + y * GDEW075C64_WIDTH / 8;
_buffer[i] = (_buffer[i] & (0xFF ^ (1 << (7 - x % 8)))); // white
_color[i] = (_color[i] & (0xFF ^ (1 << (7 - x % 8)))); // white
if (color == EPD_WHITE) return;
else if (color == EPD_BLACK) _buffer[i] = (_buffer[i] | (1 << (7 - x % 8)));
else if (color == EPD_RED) _color[i] = (_color[i] | (1 << (7 - x % 8)));
else
{
if ((color & 0xF100) > (0xF100 / 2)) _color[i] = (_color[i] | (1 << (7 - x % 8)));
else if ((((color & 0xF100) >> 11) + ((color & 0x07E0) >> 5) + (color & 0x001F)) < 3 * 255 / 2)
{
_buffer[i] = (_buffer[i] | (1 << (7 - x % 8)));
}
}
}
| 26.69434 | 131 | 0.612666 | markbirss |
3c5c8b9a09a4e522bf82789b1cd6bd172f1da236 | 14,683 | cc | C++ | src/arch/x86/32/encoder.cc | nash-project/nashalib | 730a2d9ae6acfba3c51d6c0e50a315fe55065bf1 | [
"MIT"
] | 3 | 2022-03-12T03:09:16.000Z | 2022-03-18T22:12:15.000Z | src/arch/x86/32/encoder.cc | nash-project/nashalib | 730a2d9ae6acfba3c51d6c0e50a315fe55065bf1 | [
"MIT"
] | 2 | 2022-03-18T22:12:39.000Z | 2022-03-18T22:13:26.000Z | src/arch/x86/32/encoder.cc | nash-project/nashalib | 730a2d9ae6acfba3c51d6c0e50a315fe55065bf1 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <nashalib/arch/x86/32/encoder.hpp>
#include <nashalib/registers.hpp>
#include <nashalib/arch/x86/32/opcodes.hpp>
#include <nashalib/endianess.hpp>
#include <seegul/seegul.h>
#include <fstream>
#include <iostream>
#include <nashalib/settings.hpp>
namespace nashalib{
struct modrm{
unsigned char rm: 3;
unsigned char reg: 3;
unsigned char mod: 2;
}__attribute__((packed));
struct imm{
int imm;
bool needs_imm;
int size;
}__attribute__((packed));
static int find_opcode(struct inst* inst_){
bool all_operands_valid = false;
for (int i = 0; i < OPCODE_TABLE_SIZE; i++){
if (opcode_table[i].mnemonic != inst_->mnemonic){
continue;
}
if (opcode_table[i].Noperands != inst_->operands.size()){
continue;
}
if (opcode_table[i].Noperands == 0 && inst_->operands.size() == 0){
return i;
}
for (int ii = 0; ii < inst_->operands.size(); ii++){
if (
(inst_->operands[ii]->size == 32) &&
(inst_->operands[ii]->type == INST_OPERAND_TYPE_LABEL &&
(opcode_table[i].operands[ii].type == INST_OPERAND_TYPE_IMM))
)
{
all_operands_valid = true;
}
else if ( (inst_->operands[ii]->size == opcode_table[i].operands[ii].size) &&
(inst_->operands[ii]->type == opcode_table[i].operands[ii].type)){
if ( (opcode_table[i].operands[ii].use_literal_value)) {
if (opcode_table[i].operands[ii].value == inst_->operands[ii]->val.value){
all_operands_valid = true;
}
else{
all_operands_valid = false;
//printf("Incorrect operand value %d\n", ii);
break;
}
}else{
all_operands_valid = true;
}
}
else{
all_operands_valid = false;
//printf("Incorrent operand size %d\n", ii);
break;
}
}
if (all_operands_valid)
return i;
}
return -1;
}
static inline void set_mod_in_modrm(struct modrm *modrm_, unsigned char mod){
modrm_->mod = mod;
}
static inline bool add_reg_2_modrm(int opcode_index, struct inst_operand* operand, struct modrm* _modrm, struct imm *imm){
switch (operand->type){
case INST_OPERAND_TYPE_REG:
_modrm->reg = registers_table[operand->val.value].reg;
return false;
break;
case INST_OPERAND_TYPE_IMM:
imm->imm = operand->val.value;
imm->needs_imm = true;
imm->size = operand->size;
if (opcode_table[opcode_index].rm_extends_opcode){
_modrm->rm = opcode_table[opcode_index].rm;
}
return false;
break;
default:
break;
}
}
static inline void set_rm_in_modrm(struct modrm *modrm_, unsigned char rm){
modrm_->rm = rm;
}
static inline bool add_rm_2_modrm(int opcode_index, struct modrm * _modrm, struct inst_operand* operand, struct imm *imm){
switch (operand->type){
case INST_OPERAND_TYPE_SREG:
return false;
break;
case INST_OPERAND_TYPE_IMM:
imm->imm = operand->val.value;
imm->needs_imm = true;
imm->size = operand->size;
_modrm->mod = 0b11;
if (opcode_table[opcode_index].rm_extends_opcode){
_modrm->rm = opcode_table[opcode_index].rm;
}
return true;
break;
case INST_OPERAND_TYPE_REG:
_modrm->mod = 0b11;
_modrm->rm = registers_table[operand->val.value].reg;
return true;
break;
case INST_OPERAND_TYPE_MEM:
_modrm->mod = 0b00;
_modrm->rm = registers_table[operand->val.value].reg;
return true;
break;
default:
return false;
break;
}
}
void x86_32_Encoder::encode(struct nashalib::inst* inst_){
unsigned char opcode;
struct modrm modrm_ = {0};
unsigned char modrm_byte = 0;
int modrm_index = 0;
bool skip_rm = false;
bool needs_sib = false;
unsigned char sib_byte;
std::string c_label;
bool label_relative = false;
bool label = false;
struct imm imm = {0};
bool already_done_66_prefix = false;
int opcode_index = find_opcode(inst_);
if (opcode_index == -1){
printf("Failed to find correct opcode for instruction\n");
return;
}
opcode = opcode_table[opcode_index].opcode;
for (int i = 0; i < inst_->operands.size(); i++){
if (!already_done_66_prefix && opcode_table[opcode_index].operands[i].needs_66_prefix){
add_byte(0x66);
already_done_66_prefix = true;
}
if (opcode_table[opcode_index].operands[i].use_literal_value);
else if(inst_->operands[i]->type == INST_OPERAND_TYPE_SCALE){
if (inst_->operands[i]->sib_info.base->type == INST_OPERAND_TYPE_REG){
needs_sib = true;
set_rm_in_modrm(&modrm_,0b100);
if (registers_table[(int)inst_->operands[i]->sib_info.base->reg].reg == 0b101){
imm.imm = 0x0;
imm.size = 8;
imm.needs_imm = true;
set_mod_in_modrm(&modrm_, 0b01);
}
else{
set_mod_in_modrm(&modrm_, 0b00);
}
inst_->operands[i]->sib_info.sib_byte.base = registers_table[(int)inst_->operands[i]->sib_info.base->val.value].reg;
sib_byte = *(unsigned char*)&inst_->operands[i]->sib_info.sib_byte;
modrm_index++;
skip_rm = true;
}
else if(inst_->operands[i]->sib_info.base->type == INST_OPERAND_TYPE_IMM){
needs_sib = true;
set_rm_in_modrm(&modrm_,0b100);
inst_->operands[i]->sib_info.sib_byte.base = 0b101;
imm.needs_imm = true;
imm.imm = inst_->operands[i]->sib_info.base->val.value;
switch (inst_->operands[i]->sib_info.base->size){
case 32:{
imm.size = 32;
set_mod_in_modrm(&modrm_, 0b00);
break;
}
case 8:{
imm.size = 8;
set_mod_in_modrm(&modrm_, 0b01);
break;
}
default:
printf("Incorrect size for displacement\n");
return;
}
sib_byte = *(unsigned char*)&inst_->operands[i]->sib_info.sib_byte;
modrm_index++;
skip_rm = true;
}
}
else if (inst_->operands[i]->type == INST_OPERAND_TYPE_LABEL){
c_label = inst_->operands[i]->val.label;
int lt = opcode_table[opcode_index].operands[i].label_type;
if (lt == RELATIVE){
label_relative = true;
}
label = true;
imm.needs_imm = true;
}
else{
if (opcode_table[opcode_index].which_does_rm_field_point_to == 0){
if (modrm_index == 0) {
if (!skip_rm){
if (add_rm_2_modrm(opcode_index, &modrm_, inst_->operands[i], &imm))
modrm_index++;
}
}
else if (modrm_index == 1){
if (add_reg_2_modrm(opcode_index, inst_->operands[i], &modrm_, &imm))
modrm_index++;
}
}
else{
if (modrm_index == 1){
if (!skip_rm){
if (add_rm_2_modrm(opcode_index, &modrm_, inst_->operands[i], &imm))
modrm_index++;
}
}
else if (modrm_index == 0){
if (add_reg_2_modrm(opcode_index, inst_->operands[i], &modrm_, &imm))
modrm_index++;
}
}
}
}
add_byte(opcode);
modrm_byte = *(unsigned char*)&modrm_;
if (modrm_index != 0 && opcode_table[opcode_index].needs_modrm){
add_byte(modrm_byte);
}
if (needs_sib){
add_byte(sib_byte);
}
if (imm.needs_imm){
if (label){
add_label(c_label, label_relative);
}
else{
add_imm(imm.imm, imm.size, ENDIANESS__BIG_ENDIAN__);
}
}
}
void x86_32_Encoder::gen_elf32(std::string name){
Elf32_Sym *csym;
Elf32 * elf = new Elf32();
std::fstream tfile("temp.out", std::ios::in | std::ios::binary);
if (!tfile.is_open()) return;
std::vector<char> instructions(std::istreambuf_iterator<char>{tfile}, std::istreambuf_iterator<char>{});
struct Elf32_section * shstrtab_section;
struct Elf32_section * text_section;
struct Elf32_section * strtab_section;
struct Elf32_section * symtab_section;
struct Elf32_section * data_section;
struct Elf32_section * rel_text_section;
SymTab32 * symbol_table = new SymTab32();
StrTab32 * strtab = new StrTab32();
StrTab32 * shstrtab = new StrTab32();
RelTab32 * rel_tab = new RelTab32();
elf->new_section(); // NULL
text_section = elf->new_section(); // .text
shstrtab_section = elf->new_section(); // .shstrtab
symtab_section = elf->new_section(); // .symtab
strtab_section = elf->new_section(); // .strtab
data_section = elf->new_section(); // .data
rel_text_section = elf->new_section(); // .rel.text
elf->eheader->e_shstrndx = shstrtab_section->index;
// .shstrtab
// ===============================================
shstrtab->new_string(".shstrtab");
shstrtab->new_string(".text");
shstrtab->new_string(".strtab");
shstrtab->new_string(".symtab");
shstrtab->new_string(".data");
shstrtab->new_string(".rel.text");
// ===============================================
// .text
text_section->data = (void*)instructions.data();
text_section->data_sz = instructions.size();
text_section->section->sh_name = shstrtab->get_string(".text");
text_section->section->sh_type = SHT_PROGBITS;
text_section->section->sh_flags = SHF_ALLOC | SHF_EXECINSTR;
text_section->section->sh_addralign = 4;
int size_of__data_data = 0;
int _data_data_index = 0;
for ( Data* data_ : data){
size_of__data_data += data_->size;
}
unsigned char * _data_data = (unsigned char*)malloc(size_of__data_data);
for (Data* data_ : data){
for (int y = 0; y < data_->size; y++){
_data_data[_data_data_index] = data_->data[y];
_data_data_index++;
}
}
data_section->data = (void*)_data_data;
data_section->data_sz = size_of__data_data;
data_section->section->sh_name = shstrtab->get_string(".data");
data_section->section->sh_type = SHT_PROGBITS;
data_section->section->sh_flags = SHF_ALLOC | SHF_WRITE;
data_section->section->sh_addralign = 4;
// .strtab
strtab->new_string("temp.nash");
// .symtab
symtab_section->section->sh_name = shstrtab->get_string(".symtab");
symtab_section->section->sh_link = strtab_section->index;
symbol_table->new_symbol(0, 0 ,0, SHN_UNDEF);
symbol_table->new_symbol(strtab->get_string("temp.nash"), STB_LOCAL, STT_FILE, SHN_ABS);
symbol_table->new_symbol(0, STB_LOCAL, STT_SECTION, text_section->index);
auto label_iter = labels.begin();
while (label_iter != labels.end()) {
strtab->new_string(label_iter->first); // add the label name to strtab
if (label_iter->second->visibility == local_label){
if (label_iter->second->_section == section::_text){
csym = symbol_table->new_symbol(strtab->get_string(label_iter->first), STB_LOCAL, STT_NOTYPE, text_section->index);
csym->st_value = label_iter->second->offset;
}
else if(label_iter->second->_section == section::_data){
csym = symbol_table->new_symbol(strtab->get_string(label_iter->first), STB_LOCAL, STT_NOTYPE, data_section->index);
csym->st_value = label_iter->second->offset;
}
}
else{
if (label_iter->second->_section == section::_text){
csym = symbol_table->new_symbol(strtab->get_string(label_iter->first), STB_GLOBAL, STT_NOTYPE, text_section->index);
csym->st_value = label_iter->second->offset;
}
else if(label_iter->second->_section == section::_data){
csym = symbol_table->new_symbol(strtab->get_string(label_iter->first), STB_GLOBAL, STT_NOTYPE, data_section->index);
csym->st_value = label_iter->second->offset;
}
}
label_iter++;
}
shstrtab->add_strtab(shstrtab_section);
shstrtab_section->section->sh_name = shstrtab->get_string(".shstrtab");
strtab->add_strtab(strtab_section);
strtab_section->section->sh_name = shstrtab->get_string(".strtab");
symbol_table->add_symtab(symtab_section);
for (auto entry : reloctable_table){
if (entry->section == section::_data){
rel_tab->new_relocation(entry->offset, ELF32_R_INFO(symtab_section->index, R_386_32));
}
else{
// we don't need relocation if its in text
}
}
rel_tab->add_reltab(rel_text_section);
rel_text_section->section->sh_name = shstrtab->get_string(".rel.text");
rel_text_section->section->sh_link = symtab_section->index;
rel_text_section->section->sh_info = text_section->index;
elf->write(name);
elf->done();
delete elf;
delete symbol_table;
delete shstrtab;
delete strtab;
free(_data_data);
}
void x86_32_Encoder::gen_bin(std::string name){
if (_format == format::elf32){
gen_elf32(name);
}
else{
std::cout << "x86_32 encoder does not support that format\n";
return;
}
}
} | 30.781971 | 133 | 0.551318 | nash-project |
3c5d6912528fd82c5f138fd6ae4d3d10b2a92d73 | 1,253 | cpp | C++ | src/geometry/2d-geometry/intersection-of-a-polygon-and-a-circle.cpp | Nisiyama-Suzune/LMR | 16325b9efcb71240111ac12ea55c0cb45b0c5834 | [
"MIT"
] | 48 | 2018-08-15T11:58:28.000Z | 2022-02-08T23:38:29.000Z | src/geometry/2d-geometry/intersection-of-a-polygon-and-a-circle.cpp | Nisiyama-Suzune/LMR | 16325b9efcb71240111ac12ea55c0cb45b0c5834 | [
"MIT"
] | null | null | null | src/geometry/2d-geometry/intersection-of-a-polygon-and-a-circle.cpp | Nisiyama-Suzune/LMR | 16325b9efcb71240111ac12ea55c0cb45b0c5834 | [
"MIT"
] | 8 | 2019-07-18T10:27:50.000Z | 2021-06-08T13:03:47.000Z | struct polygon_circle_intersect {
double sector_area (cp a, cp b, const double &r) {
double c = (2.0 * r * r - dis2 (a, b)) / (2.0 * r * r);
return r * r * acos (c) / 2.0; }
double area (cp a, cp b, const double &r) {
double dA = dot (a, a), dB = dot (b, b), dC = point_to_segment (point (), line (a, b));
if (sgn (dA - r * r) <= 0 && sgn (dB - r * r) <= 0) return det (a, b) / 2.0;
point tA = a.unit () * r, tB = b.unit () * r;
if (sgn (dC - r) > 0) return sector_area (tA, tB, r);
std::vector <point> ret = line_circle_intersect (line (a, b), circle (point (), r));
if (sgn (dA - r * r) > 0 && sgn (dB - r * r) > 0)
return sector_area (tA, ret[0], r) + det (ret[0], ret[1]) / 2.0 + sector_area (ret[1], tB, r);
if (sgn (dA - r * r) > 0) return det (ret[0], b) / 2.0 + sector_area (tA, ret[0], r);
else return det (a, ret[1]) / 2.0 + sector_area (ret[1], tB, r); }
double solve (const std::vector <point> &p, cc c) {
double ret = 0.0;
for (int i = 0; i < (int) p.size (); ++i) {
int s = sgn (det (p[i] - c.c, p[(i + 1) % p.size ()] - c.c));
if (s > 0) ret += area (p[i] - c.c, p[(i + 1) % p.size ()] - c.c, c.r);
else ret -= area (p[(i + 1) % p.size ()] - c.c, p[i] - c.c, c.r); }
return std::abs (ret); } };
| 54.478261 | 97 | 0.501197 | Nisiyama-Suzune |
3c63ffae83532be57e2ddce56cb40b9a827c8100 | 6,271 | cpp | C++ | jswinrt/Function.cpp | proog128/jswin | 3c288ef2ad4b815a01c0931a1757cf10e44ccc1d | [
"BSD-2-Clause-FreeBSD"
] | 41 | 2015-02-07T07:25:21.000Z | 2022-03-25T00:33:48.000Z | jswinrt/Function.cpp | proog128/jswin | 3c288ef2ad4b815a01c0931a1757cf10e44ccc1d | [
"BSD-2-Clause-FreeBSD"
] | 2 | 2015-10-16T17:17:23.000Z | 2021-07-21T18:28:51.000Z | jswinrt/Function.cpp | proog128/jswin | 3c288ef2ad4b815a01c0931a1757cf10e44ccc1d | [
"BSD-2-Clause-FreeBSD"
] | 16 | 2015-04-21T18:08:22.000Z | 2022-03-25T00:33:35.000Z | #include "Function.h"
#include <vector>
#include "V8SafeCall.h"
#include "V8ArrayBufferUtils.h"
#include "V8StringUtils.h"
v8::Persistent<v8::FunctionTemplate> Function::V8Constructor;
Function::Function(const std::string& signature, CallingConvention callingConvention, void* address)
: signature(signature), callingConvention(callingConvention), address(address)
{
}
Function::~Function()
{
}
void Function::call(const v8::FunctionCallbackInfo<v8::Value>& args)
{
void* addressLocal = address;
std::vector<char*> strings;
std::vector<wchar_t*> wstrings;
for(int i=signature.size()-2; i>=0; --i)
{
if(i > args.Length()-1)
{
throw std::runtime_error("Invalid argument count");
}
char type = signature[i+1];
if(type == 'i')
{
int a = args[i]->Int32Value();
_asm push a
}
else if(type == 'u')
{
int a = args[i]->Uint32Value();
_asm push a
}
else if(type == 'c')
{
char* a = NULL;
if(!args[i]->IsNull())
{
a = _strdup(ToAnsi(args[i]->ToString()).data());
strings.push_back(a);
}
_asm push a
}
else if(type == 'w')
{
wchar_t* a = NULL;
if(!args[i]->IsNull())
{
a = _wcsdup(ToWideChar(args[i]->ToString()).data());
wstrings.push_back(a);
}
_asm push a
}
else if(type == 's')
{
void* a = NULL;
if(!args[i]->IsNull())
{
if(!args[i]->IsArrayBuffer())
{
throw std::runtime_error("Argument is not an array buffer");
}
v8::Handle<v8::ArrayBuffer> arrayBuffer = v8::Handle<v8::ArrayBuffer>::Cast(args[i]);
a = ExternalizeAutoDelete(arrayBuffer);
}
_asm push a
}
else
{
throw std::runtime_error("Unknown argument type");
}
}
unsigned int r = 0;
_asm call dword ptr[addressLocal]
_asm mov [r], eax
if(callingConvention == CDecl)
{
// Clean up stack
for(int i=signature.size()-2; i>=0; --i)
{
_asm pop eax
}
}
for(std::vector<char*>::iterator it = strings.begin(); it != strings.end(); ++it)
{
free(*it);
}
for(std::vector<wchar_t*>::iterator it = wstrings.begin(); it != wstrings.end(); ++it)
{
free(*it);
}
if(signature[0] == 'u')
{
args.GetReturnValue().Set(static_cast<unsigned int>(r));
}
else if(signature[0] == 'i')
{
args.GetReturnValue().Set(static_cast<int>(r));
}
else if(signature[0] == 'v')
{
args.GetReturnValue().Set(v8::Undefined());
}
else
{
throw std::runtime_error("Unknown return type");
}
}
void Function::V8Init()
{
v8::Handle<v8::FunctionTemplate> V8ConstructorLocal = v8::FunctionTemplate::New();
V8ConstructorLocal->InstanceTemplate()->SetInternalFieldCount(1);
V8ConstructorLocal->InstanceTemplate()->SetCallAsFunctionHandler(V8Call);
V8ConstructorLocal->PrototypeTemplate()->Set("getAddress", v8::FunctionTemplate::New(V8SafeCall<V8GetAddress>));
V8Constructor.Reset(v8::Isolate::GetCurrent(), V8ConstructorLocal);
}
void Function::V8ConstructorFunction(const v8::FunctionCallbackInfo<v8::Value>& args)
{
if(!args.IsConstructCall())
{
throw std::runtime_error("Constructor was called without 'new'");
}
if(args.Length() < 3)
{
throw std::runtime_error("Invalid argument count");
}
v8::String::Utf8Value argSignature(args[0]);
v8::String::Utf8Value argCallingConventionStr(args[1]);
void* argAddress = (void*)args[2]->Int32Value();
Function::CallingConvention argCallingConvention;
if(!strcmp(*argCallingConventionStr, "stdcall"))
{
argCallingConvention = Function::StdCall;
}
else if(!strcmp(*argCallingConventionStr, "cdecl"))
{
argCallingConvention = Function::CDecl;
}
else
{
throw std::runtime_error("Invalid calling convention");
}
std::string signature = "i"; // Set 'i' as default for now (compatibility)
signature += *argSignature;
if(args.Length() > 3)
{
v8::String::Utf8Value argReturnType(args[3]);
if(argReturnType.length() != 1)
{
throw std::runtime_error("Invalid length of return type specifier");
}
signature[0] = (*argReturnType)[0];
}
Function* func = new Function(signature, argCallingConvention, argAddress);
v8::Persistent<v8::Object> funcObj;
V8Wrap(func, funcObj);
args.GetReturnValue().Set(funcObj);
}
void Function::V8Wrap(Function* function, v8::Persistent<v8::Object>& wrappedObj)
{
v8::Handle<v8::FunctionTemplate> V8ConstructorLocal = v8::Handle<v8::FunctionTemplate>::New(v8::Isolate::GetCurrent(), V8Constructor);
v8::Handle<v8::Object> obj = V8ConstructorLocal->InstanceTemplate()->NewInstance();
obj->SetInternalField(0, v8::External::New(function));
v8::Persistent<v8::Object> persistentObj(v8::Isolate::GetCurrent(), obj);
persistentObj.MakeWeak(function, V8WeakCallback);
wrappedObj.Reset(v8::Isolate::GetCurrent(), persistentObj);
}
void Function::V8WeakCallback(v8::Isolate* isolate, v8::Persistent<v8::Object>* object, Function* parameter)
{
delete parameter;
object->Dispose();
object->Clear();
}
void Function::V8Call(const v8::FunctionCallbackInfo<v8::Value>& args)
{
v8::Local<v8::Object> self = args.Holder();
v8::Local<v8::External> wrap = v8::Local<v8::External>::Cast(self->GetInternalField(0));
Function* function = (Function*)wrap->Value();
function->call(args);
}
void Function::V8GetAddress(const v8::FunctionCallbackInfo<v8::Value>& args)
{
v8::Local<v8::Object> self = args.Holder();
v8::Local<v8::External> wrap = v8::Local<v8::External>::Cast(self->GetInternalField(0));
Function* func = (Function*)wrap->Value();
void* address = func->getAddress();
args.GetReturnValue().Set(v8::Uint32::New((unsigned int)address));
}
| 28.121076 | 138 | 0.595758 | proog128 |
3c666f3f4cc828d67ddf481d84fb87d7495c43e3 | 2,314 | cpp | C++ | csgocheat/hooks/c_net_channel_.cpp | garryhvh420/e_xyz | 668d8c8c2b7ccfc3bae9e321b1a50379a5e33ec9 | [
"Apache-2.0"
] | null | null | null | csgocheat/hooks/c_net_channel_.cpp | garryhvh420/e_xyz | 668d8c8c2b7ccfc3bae9e321b1a50379a5e33ec9 | [
"Apache-2.0"
] | null | null | null | csgocheat/hooks/c_net_channel_.cpp | garryhvh420/e_xyz | 668d8c8c2b7ccfc3bae9e321b1a50379a5e33ec9 | [
"Apache-2.0"
] | null | null | null | #include "c_net_channel_.h"
#include "../hacks/c_fake_ping.h"
void c_net_channel_::hook()
{
//static uint32_t dummy[1] = { reinterpret_cast<uint32_t>(c_net_channel::get_vtable()) };
//hk = std::make_unique<c_hook<uint32_t>>(dummy);
//_process_packet = hk->apply<process_packet_t>(39, process_packet);
//_send_netmsg = hk->apply<send_netmsg_t>(40, send_netmsg);
//_send_datagram = hk->apply<send_datagram_t>(46, send_datagram);
}
void c_net_channel_::apply_to_net_chan(c_net_channel* channel)
{
/*bandaid fix, started throwing vgui2.dll nullptrs with patchpointer - ML*/
hk = std::make_unique<c_hook<uint32_t>>((uint32_t*)channel);
//hk = std::make_unique<c_hook<uint32_t>>((uint32_t*)channel);
_send_datagram = hk->apply<send_datagram_t>(46, send_datagram);
//hk->patch_pointer(reinterpret_cast<uintptr_t*>(channel));
}
void __fastcall c_net_channel_::process_packet(c_net_channel* channel, uint32_t, void* packet, bool header)
{
_process_packet(channel, packet, header);
const auto local = c_cs_player::get_local_player();
if (engine_client()->is_ingame() && local && local->is_alive())
fake_ping->flip_state(channel);
}
bool c_net_channel_::send_netmsg(c_net_channel* channel, uint32_t, c_net_msg* msg, const bool reliable, const bool voice)
{
return _send_netmsg(channel, msg, reliable, msg->get_group() == 9 ? true : voice);
}
void c_net_channel_::UpdateIncomingSequences(c_net_channel* channel) {
static int lastseq = -1;
//if (lastseq == channel->in_sequence_nr)return;
c_net_channel_::sequences.push_front(CIncomingSequence(channel->in_reliable_state, 0, 0, channel->in_sequence_nr, global_vars_base->curtime));
if (c_net_channel_::sequences.size() > 2048)
c_net_channel_::sequences.pop_back();
}
int c_net_channel_::send_datagram(c_net_channel* channel, uint32_t, void* buffer){
if (!engine_client()->is_ingame()|| !c_cs_player::get_local_player() || buffer)
return _send_datagram(channel, buffer);
UpdateIncomingSequences(channel);
const auto backup_in_seq = channel->in_sequence_nr;
const auto backup_reliable = channel->in_reliable_state;//new
fake_ping->set_suitable_in_sequence(channel);
const auto original = _send_datagram(channel, buffer);
channel->in_sequence_nr = backup_in_seq;
channel->in_reliable_state = backup_reliable;//new
return original;
}
| 37.322581 | 143 | 0.763613 | garryhvh420 |
3c67aa40f0ca8954c224bd434f6c799c4eaff358 | 567 | hpp | C++ | include/ShaderAST/Expr/ExprModulo.hpp | Praetonus/ShaderWriter | 1c5b3961e3e1b91cb7158406998519853a4add07 | [
"MIT"
] | null | null | null | include/ShaderAST/Expr/ExprModulo.hpp | Praetonus/ShaderWriter | 1c5b3961e3e1b91cb7158406998519853a4add07 | [
"MIT"
] | null | null | null | include/ShaderAST/Expr/ExprModulo.hpp | Praetonus/ShaderWriter | 1c5b3961e3e1b91cb7158406998519853a4add07 | [
"MIT"
] | null | null | null | /*
See LICENSE file in root folder
*/
#ifndef ___AST_ExprModulo_H___
#define ___AST_ExprModulo_H___
#pragma once
#include "ExprBinary.hpp"
namespace ast::expr
{
class Modulo
: public Binary
{
public:
Modulo( type::TypePtr type
, ExprPtr lhs
, ExprPtr rhs );
void accept( VisitorPtr vis )override;
};
using ModuloPtr = std::unique_ptr< Modulo >;
inline ModuloPtr makeModulo( type::TypePtr type
, ExprPtr lhs
, ExprPtr rhs )
{
return std::make_unique< Modulo >( std::move( type )
, std::move( lhs )
, std::move( rhs ) );
}
}
#endif
| 16.2 | 54 | 0.677249 | Praetonus |
3c6ca5a41bf813e01f68cb2e362c85df5ecf4498 | 2,239 | hxx | C++ | src/ana_tools/VALORModelClassifier.hxx | TWLord/DUNEPrismTools | bde52eb1331ac10ba81cdf1bf63488707bfe5496 | [
"MIT"
] | null | null | null | src/ana_tools/VALORModelClassifier.hxx | TWLord/DUNEPrismTools | bde52eb1331ac10ba81cdf1bf63488707bfe5496 | [
"MIT"
] | null | null | null | src/ana_tools/VALORModelClassifier.hxx | TWLord/DUNEPrismTools | bde52eb1331ac10ba81cdf1bf63488707bfe5496 | [
"MIT"
] | 3 | 2018-01-09T20:57:33.000Z | 2019-11-24T03:48:28.000Z | #ifndef VALORMODELCLASSIFIER_HXX_SEEN
#define VALORMODELCLASSIFIER_HXX_SEEN
#include "InteractionModel.hxx"
#include "DepositsSummaryTreeReader.hxx"
#include <iostream>
#include <utility>
#include <vector>
namespace VALORModel {
enum class TrueClass;
}
#define VARLIST \
X(kNu_QE_1, 0.082) \
X(kNu_QE_2, 0.23) \
X(kNu_QE_3, 0.48) \
X(kNuBar_QE_1, 0.087) \
X(kNuBar_QE_2, 0.24) \
X(kNuBar_QE_3, 0.40) \
X(kNu_MEC, 1) \
X(kNuBar_MEC, 1) \
X(kNu_1Pi0_1, 0.13) \
X(kNu_1Pi0_2, 0.23) \
X(kNu_1Pi0_3, 0.35) \
X(kNu_1PiC_1, 0.13) \
X(kNu_1PiC_2, 0.24) \
X(kNu_1PiC_3, 0.40) \
X(kNuBar_1Pi0_1, 0.16) \
X(kNuBar_1Pi0_2, 0.27) \
X(kNuBar_1Pi0_3, 0.35) \
X(kNuBar_1PiC_1, 0.16) \
X(kNuBar_1PiC_2, 0.3) \
X(kNuBar_1PiC_3, 0.4) \
X(kNu_2Pi, 0.22) \
X(kNuBar_2Pi, 0.22) \
X(kNu_DIS_1, 0.035) \
X(kNu_DIS_2, 0.035) \
X(kNu_DIS_3, 0.027) \
X(kNuBar_DIS_1, 0.01) \
X(kNuBar_DIS_2, 0.017) \
X(kNuBar_DIS_3, 0.017) \
X(kNu_COH, 1.28) \
X(kNuBar_COH, 1.34) \
X(kNu_NC, 0.16) \
X(kNuBar_NC, 0.16) \
X(kNuMu_E_Ratio, 0.03) \
X(kNVALORDials,0)
#define X(A, B) A,
enum class VALORModel::TrueClass { VARLIST };
#undef X
#define X(A, B) \
case VALORModel::TrueClass::A: { \
return os << #A; \
}
inline std::ostream &operator<<(std::ostream &os, VALORModel::TrueClass te) {
switch (te) { VARLIST }
return os;
}
#undef X
#define X(A, B) \
case VALORModel::TrueClass::A: { \
return B; \
}
inline double GetDefaultDialTweak(VALORModel::TrueClass te) {
switch (te) { VARLIST }
return 0;
}
#undef X
#define X(A, B) dv.push_back(std::make_tuple(VALORModel::TrueClass::A, 1, B));
inline std::vector<std::tuple<VALORModel::TrueClass, double, double> >
GetDialValueVector(VALORModel::TrueClass te) {
std::vector<std::tuple<VALORModel::TrueClass, double, double> > dv;
VARLIST
return dv;
}
#undef X
#undef VARLIST
std::vector<VALORModel::TrueClass> GetApplicableDials(DepositsSummary const &ed);
double GetVALORWeight(VALORModel::TrueClass te, double value, DepositsSummary const &ed);
#endif
| 25.157303 | 89 | 0.618133 | TWLord |
3c6e69d522fae6dc64880fef1e166002fe57e6b9 | 3,522 | cpp | C++ | src/classify/classifier/naive_bayes.cpp | Lolik111/meta | c7019401185cdfa15e1193aad821894c35a83e3f | [
"MIT"
] | 615 | 2015-01-31T17:14:03.000Z | 2022-03-27T03:03:02.000Z | src/classify/classifier/naive_bayes.cpp | Lolik111/meta | c7019401185cdfa15e1193aad821894c35a83e3f | [
"MIT"
] | 167 | 2015-01-20T17:48:16.000Z | 2021-12-20T00:15:29.000Z | src/classify/classifier/naive_bayes.cpp | Lolik111/meta | c7019401185cdfa15e1193aad821894c35a83e3f | [
"MIT"
] | 264 | 2015-01-30T00:08:01.000Z | 2022-03-02T17:19:11.000Z | /**
* @file naive_bayes.cpp
* @author Sean Massung
*/
#include <cassert>
#include "cpptoml.h"
#include "meta/classify/classifier/naive_bayes.h"
#include "meta/io/packed.h"
namespace meta
{
namespace classify
{
const util::string_view naive_bayes::id = "naive-bayes";
const constexpr double naive_bayes::default_alpha;
const constexpr double naive_bayes::default_beta;
naive_bayes::naive_bayes(dataset_view_type docs, double alpha, double beta)
: class_probs_{stats::dirichlet<class_label>{beta, docs.total_labels()}}
{
stats::dirichlet<term_id> term_prior{alpha, docs.total_features()};
std::vector<class_label> labels(docs.total_labels());
std::transform(docs.labels_begin(), docs.labels_end(), labels.begin(),
[](const std::pair<const class_label, label_id>& pr)
{
return pr.first;
});
std::sort(labels.begin(), labels.end());
term_probs_.reserve(labels.size());
for (const auto& lbl : labels)
term_probs_.emplace_back(lbl, term_prior);
train(docs);
}
naive_bayes::naive_bayes(std::istream& in)
{
uint64_t size;
auto bytes = io::packed::read(in, size);
if (bytes == 0)
throw naive_bayes_exception{
"failed reading term probability file (no size written)"};
term_probs_.clear();
term_probs_.reserve(size);
for (uint64_t i = 0; i < size; ++i)
{
class_label label;
io::packed::read(in, label);
term_probs_[label].load(in);
}
class_probs_.load(in);
}
void naive_bayes::save(std::ostream& os) const
{
io::packed::write(os, id);
io::packed::write(os, term_probs_.size());
for (const auto& dist : term_probs_)
{
const auto& label = dist.first;
const auto& probs = dist.second;
io::packed::write(os, label);
probs.save(os);
}
class_probs_.save(os);
}
void naive_bayes::train(const dataset_view_type& docs)
{
for (const auto& instance : docs)
{
for (const auto& p : instance.weights)
{
term_probs_[docs.label(instance)].increment(p.first, p.second);
assert(term_probs_[docs.label(instance)].probability(p.first) > 0);
}
class_probs_.increment(docs.label(instance), 1);
}
}
class_label naive_bayes::classify(const feature_vector& instance) const
{
class_label label;
double best = std::numeric_limits<double>::lowest();
// calculate prob of test doc for each class
for (const auto& cls : term_probs_)
{
const auto& lbl = cls.first;
const auto& term_dist = cls.second;
double sum = 0.0;
assert(class_probs_.probability(lbl) > 0);
sum += std::log(class_probs_.probability(lbl));
for (const auto& t : instance)
{
assert(term_dist.probability(t.first) > 0);
sum += t.second * std::log(term_dist.probability(t.first));
}
if (sum > best)
{
best = sum;
label = cls.first;
}
}
return label;
}
template <>
std::unique_ptr<classifier>
make_classifier<naive_bayes>(const cpptoml::table& config,
multiclass_dataset_view training)
{
auto alpha
= config.get_as<double>("alpha").value_or(naive_bayes::default_alpha);
auto beta
= config.get_as<double>("beta").value_or(naive_bayes::default_beta);
return make_unique<naive_bayes>(std::move(training), alpha, beta);
}
}
}
| 26.681818 | 79 | 0.619818 | Lolik111 |
3c6ee7e3835ea14158d1ac3828fec0766f523859 | 1,062 | hh | C++ | core/inc/com/centreon/broker/extcmd/internal.hh | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | core/inc/com/centreon/broker/extcmd/internal.hh | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | core/inc/com/centreon/broker/extcmd/internal.hh | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | /*
** Copyright 2013 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#ifndef CCB_EXTCMD_INTERNAL_HH
# define CCB_EXTCMD_INTERNAL_HH
# include "com/centreon/broker/namespace.hh"
CCB_BEGIN()
// Forward declarations.
namespace io {
class data;
class event_info;
}
namespace mapping {
class entry;
}
namespace extcmd {
// Load the command file endpoints.
void load();
void unload();
}
CCB_END()
#endif // !CCB_EXTCMD_INTERNAL_HH
| 24.136364 | 75 | 0.70339 | sdelafond |
3c70cb43d6f7be322c897075afdf7bac89b7bfb9 | 478 | cpp | C++ | Char_2D-Arrays/all_Substrings.cpp | Talat12/coding-ninjas-cpp-inception | a15a7bada0c8d6ca9e9d9da20c1951114e75b246 | [
"MIT"
] | 2 | 2019-06-11T16:31:52.000Z | 2019-06-20T14:34:18.000Z | Char_2D-Arrays/all_Substrings.cpp | shermisaurus/coding-ninjas-cpp-inception | cb93017a9683a92373f53d787b20a6944383e273 | [
"MIT"
] | null | null | null | Char_2D-Arrays/all_Substrings.cpp | shermisaurus/coding-ninjas-cpp-inception | cb93017a9683a92373f53d787b20a6944383e273 | [
"MIT"
] | 3 | 2020-04-15T00:38:56.000Z | 2020-10-20T06:08:29.000Z | #include <string.h>
void printSubstrings(char str[]){
/* Don't write main().
* Don't read input, it is passed as function argument.
* Print output as specified in the question.
*/
int n = strlen(str);
for(int len = 1; len <= n; len++)
{
for(int i = 0; i <= n - len; i++) //set starting index
{
int j = i + len - 1; //set anding index
for(int k = i; k <= j; k++)
{
cout<<str[k];
}
cout<<endl;
}
}
}
| 20.782609 | 58 | 0.5 | Talat12 |
3c713b53f2d308dff9809bb38c214a8b000003c9 | 1,191 | hpp | C++ | include/HttpClient.hpp | RalfOGit/libgoecharger | 368ce3ccf032a07b717bdad25f2626e5eade2230 | [
"MIT"
] | null | null | null | include/HttpClient.hpp | RalfOGit/libgoecharger | 368ce3ccf032a07b717bdad25f2626e5eade2230 | [
"MIT"
] | null | null | null | include/HttpClient.hpp | RalfOGit/libgoecharger | 368ce3ccf032a07b717bdad25f2626e5eade2230 | [
"MIT"
] | null | null | null | #ifndef __LIBGOECHARGER_HTTPCLIENT_HPP__
#define __LIBGOECHARGER_HTTPCLIENT_HPP__
#include <string>
namespace libgoecharger {
/**
* Class implementing a very basic http client.
*/
class HttpClient {
public:
HttpClient(void);
int sendHttpGetRequest(const std::string& url, std::string& response, std::string& content);
int sendHttpPutRequest(const std::string& url, std::string& response, std::string& content);
protected:
int connect_to_server(const std::string& url, std::string& host, std::string& path);
int communicate_with_server(const int socket_fd, const std::string& request, std::string& response, std::string& content);
size_t recv_http_response(int socket_fd, char* buffer, int buffer_size);
int parse_http_response(const std::string& answer, std::string& http_response, std::string& http_content);
int get_http_return_code(char* buffer, size_t buffer_size);
size_t get_content_length(char* buffer, size_t buffer_size);
size_t get_content_offset(char* buffer, size_t buffer_size);
};
} // namespace libgoecharger
#endif
| 36.090909 | 131 | 0.686818 | RalfOGit |
3c724e815381eaf03606a39e232d267780539161 | 941 | cpp | C++ | cpp/atcoder/abc052.cpp | KeiichiHirobe/algorithms | 8de082dab33054f3e433330a2cf5d06bd770bd04 | [
"Apache-2.0"
] | null | null | null | cpp/atcoder/abc052.cpp | KeiichiHirobe/algorithms | 8de082dab33054f3e433330a2cf5d06bd770bd04 | [
"Apache-2.0"
] | null | null | null | cpp/atcoder/abc052.cpp | KeiichiHirobe/algorithms | 8de082dab33054f3e433330a2cf5d06bd770bd04 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
#include <cmath>
#include <map>
using namespace std;
vector<pair<long long, long long> > prime_factorize(long long N)
{
vector<pair<long long, long long> > res;
for (long long a = 2; a * a <= N; ++a)
{
if (N % a != 0)
continue;
long long ex = 0;
while (N % a == 0)
{
++ex;
N /= a;
}
res.push_back({a, ex});
}
// 素数
if (N != 1)
res.push_back({N, 1});
return res;
}
int main()
{
long long n;
cin >> n;
long long ret = 1;
map<int, int> m;
for (int i = 1; i <= n; i++)
{
const auto &pf = prime_factorize(i);
for (auto p : pf)
{
m[p.first] += p.second;
}
}
for (auto itr = m.begin(); itr != m.end(); ++itr)
{
ret *= (itr->second + 1);
ret %= 1000000007;
}
cout << ret << endl;
}
| 18.096154 | 64 | 0.435707 | KeiichiHirobe |
3c739564d1f0fcae776fbb80b48b5e7be4bc8c87 | 3,704 | cpp | C++ | aws-cpp-sdk-cloudsearch/source/model/DocumentSuggesterOptions.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 2 | 2019-03-11T15:50:55.000Z | 2020-02-27T11:40:27.000Z | aws-cpp-sdk-cloudsearch/source/model/DocumentSuggesterOptions.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 18 | 2018-05-15T16:41:07.000Z | 2018-05-21T00:46:30.000Z | aws-cpp-sdk-cloudsearch/source/model/DocumentSuggesterOptions.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 1 | 2019-01-18T13:03:55.000Z | 2019-01-18T13:03:55.000Z | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/cloudsearch/model/DocumentSuggesterOptions.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
namespace Aws
{
namespace CloudSearch
{
namespace Model
{
DocumentSuggesterOptions::DocumentSuggesterOptions() :
m_sourceFieldHasBeenSet(false),
m_fuzzyMatching(SuggesterFuzzyMatching::NOT_SET),
m_fuzzyMatchingHasBeenSet(false),
m_sortExpressionHasBeenSet(false)
{
}
DocumentSuggesterOptions::DocumentSuggesterOptions(const XmlNode& xmlNode) :
m_sourceFieldHasBeenSet(false),
m_fuzzyMatching(SuggesterFuzzyMatching::NOT_SET),
m_fuzzyMatchingHasBeenSet(false),
m_sortExpressionHasBeenSet(false)
{
*this = xmlNode;
}
DocumentSuggesterOptions& DocumentSuggesterOptions::operator =(const XmlNode& xmlNode)
{
XmlNode resultNode = xmlNode;
if(!resultNode.IsNull())
{
XmlNode sourceFieldNode = resultNode.FirstChild("SourceField");
if(!sourceFieldNode.IsNull())
{
m_sourceField = StringUtils::Trim(sourceFieldNode.GetText().c_str());
m_sourceFieldHasBeenSet = true;
}
XmlNode fuzzyMatchingNode = resultNode.FirstChild("FuzzyMatching");
if(!fuzzyMatchingNode.IsNull())
{
m_fuzzyMatching = SuggesterFuzzyMatchingMapper::GetSuggesterFuzzyMatchingForName(StringUtils::Trim(fuzzyMatchingNode.GetText().c_str()).c_str());
m_fuzzyMatchingHasBeenSet = true;
}
XmlNode sortExpressionNode = resultNode.FirstChild("SortExpression");
if(!sortExpressionNode.IsNull())
{
m_sortExpression = StringUtils::Trim(sortExpressionNode.GetText().c_str());
m_sortExpressionHasBeenSet = true;
}
}
return *this;
}
void DocumentSuggesterOptions::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
if(m_sourceFieldHasBeenSet)
{
oStream << location << index << locationValue << ".SourceField=" << StringUtils::URLEncode(m_sourceField.c_str()) << "&";
}
if(m_fuzzyMatchingHasBeenSet)
{
oStream << location << index << locationValue << ".FuzzyMatching=" << SuggesterFuzzyMatchingMapper::GetNameForSuggesterFuzzyMatching(m_fuzzyMatching) << "&";
}
if(m_sortExpressionHasBeenSet)
{
oStream << location << index << locationValue << ".SortExpression=" << StringUtils::URLEncode(m_sortExpression.c_str()) << "&";
}
}
void DocumentSuggesterOptions::OutputToStream(Aws::OStream& oStream, const char* location) const
{
if(m_sourceFieldHasBeenSet)
{
oStream << location << ".SourceField=" << StringUtils::URLEncode(m_sourceField.c_str()) << "&";
}
if(m_fuzzyMatchingHasBeenSet)
{
oStream << location << ".FuzzyMatching=" << SuggesterFuzzyMatchingMapper::GetNameForSuggesterFuzzyMatching(m_fuzzyMatching) << "&";
}
if(m_sortExpressionHasBeenSet)
{
oStream << location << ".SortExpression=" << StringUtils::URLEncode(m_sortExpression.c_str()) << "&";
}
}
} // namespace Model
} // namespace CloudSearch
} // namespace Aws
| 31.65812 | 163 | 0.733531 | curiousjgeorge |
3c73bbc35edf39505a5a6b411298da53c0325fe9 | 1,552 | hpp | C++ | calamity/src/event/internal/dispatcher.hpp | ClayCore/calamity | ddc9226648e4457531db33c27d67229f6f538455 | [
"BSD-3-Clause"
] | 1 | 2021-07-30T07:37:14.000Z | 2021-07-30T07:37:14.000Z | calamity/src/event/internal/dispatcher.hpp | ClayCore/calamity | ddc9226648e4457531db33c27d67229f6f538455 | [
"BSD-3-Clause"
] | null | null | null | calamity/src/event/internal/dispatcher.hpp | ClayCore/calamity | ddc9226648e4457531db33c27d67229f6f538455 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "event.hpp"
#include "listener.hpp"
namespace Calamity::EventSystem
{
class BaseDispatcher
{
// Constructors //
// ---------------------- //
public:
BaseDispatcher();
BaseDispatcher(Ref<BaseListener>& listener);
virtual ~BaseDispatcher() = default;
// Accessors and mutators //
// -------------------------------- //
virtual Ref<Event> get_event(usize index) const;
virtual Ref<BaseListener> get_listener() const;
virtual void set_event(Scope<Event> event, usize index);
virtual void add_event(Scope<Event> event);
virtual void bind(Ref<BaseListener> listener);
// Dispatcher functions //
// ------------------------------ //
virtual void dispatch(Scope<Event> event);
virtual void dispatch(Scope<Event> event, Ref<BaseListener> listener);
// Debugging methods //
// --------------------------- //
std::string to_string() const;
friend inline std::ostream& operator<<(std::ostream& os, const BaseDispatcher& ds)
{
return os << ds.to_string();
}
// Bound variables //
// ------------------------- //
private:
Ref<BaseListener> m_listener;
// TODO: make this a queue or a map
// since we might have distinct listener for many events
std::vector<Ref<Event>> m_events;
};
} // namespace Calamity::EventSystem
| 28.218182 | 90 | 0.516753 | ClayCore |
3c77b489f4e96f20c925811acbeebcc5cc2b5143 | 14,791 | cpp | C++ | aws-cpp-sdk-route53/source/Route53Errors.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 2 | 2019-03-11T15:50:55.000Z | 2020-02-27T11:40:27.000Z | aws-cpp-sdk-route53/source/Route53Errors.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 18 | 2018-05-15T16:41:07.000Z | 2018-05-21T00:46:30.000Z | aws-cpp-sdk-route53/source/Route53Errors.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 1 | 2019-01-18T13:03:55.000Z | 2019-01-18T13:03:55.000Z | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/core/client/AWSError.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/route53/Route53Errors.h>
using namespace Aws::Client;
using namespace Aws::Route53;
using namespace Aws::Utils;
namespace Aws
{
namespace Route53
{
namespace Route53ErrorMapper
{
static const int TOO_MANY_TRAFFIC_POLICY_INSTANCES_HASH = HashingUtils::HashString("TooManyTrafficPolicyInstances");
static const int DELEGATION_SET_ALREADY_CREATED_HASH = HashingUtils::HashString("DelegationSetAlreadyCreated");
static const int CONCURRENT_MODIFICATION_HASH = HashingUtils::HashString("ConcurrentModification");
static const int HOSTED_ZONE_NOT_FOUND_HASH = HashingUtils::HashString("HostedZoneNotFound");
static const int NO_SUCH_DELEGATION_SET_HASH = HashingUtils::HashString("NoSuchDelegationSet");
static const int LAST_V_P_C_ASSOCIATION_HASH = HashingUtils::HashString("LastVPCAssociation");
static const int TOO_MANY_HOSTED_ZONES_HASH = HashingUtils::HashString("TooManyHostedZones");
static const int NO_SUCH_CHANGE_HASH = HashingUtils::HashString("NoSuchChange");
static const int QUERY_LOGGING_CONFIG_ALREADY_EXISTS_HASH = HashingUtils::HashString("QueryLoggingConfigAlreadyExists");
static const int CONFLICTING_TYPES_HASH = HashingUtils::HashString("ConflictingTypes");
static const int TOO_MANY_TRAFFIC_POLICY_VERSIONS_FOR_CURRENT_POLICY_HASH = HashingUtils::HashString("TooManyTrafficPolicyVersionsForCurrentPolicy");
static const int INVALID_TRAFFIC_POLICY_DOCUMENT_HASH = HashingUtils::HashString("InvalidTrafficPolicyDocument");
static const int LIMITS_EXCEEDED_HASH = HashingUtils::HashString("LimitsExceeded");
static const int NO_SUCH_TRAFFIC_POLICY_HASH = HashingUtils::HashString("NoSuchTrafficPolicy");
static const int CONFLICTING_DOMAIN_EXISTS_HASH = HashingUtils::HashString("ConflictingDomainExists");
static const int NO_SUCH_QUERY_LOGGING_CONFIG_HASH = HashingUtils::HashString("NoSuchQueryLoggingConfig");
static const int DELEGATION_SET_IN_USE_HASH = HashingUtils::HashString("DelegationSetInUse");
static const int INVALID_DOMAIN_NAME_HASH = HashingUtils::HashString("InvalidDomainName");
static const int INVALID_INPUT_HASH = HashingUtils::HashString("InvalidInput");
static const int HEALTH_CHECK_ALREADY_EXISTS_HASH = HashingUtils::HashString("HealthCheckAlreadyExists");
static const int HOSTED_ZONE_ALREADY_EXISTS_HASH = HashingUtils::HashString("HostedZoneAlreadyExists");
static const int HEALTH_CHECK_IN_USE_HASH = HashingUtils::HashString("HealthCheckInUse");
static const int INVALID_V_P_C_ID_HASH = HashingUtils::HashString("InvalidVPCId");
static const int PRIOR_REQUEST_NOT_COMPLETE_HASH = HashingUtils::HashString("PriorRequestNotComplete");
static const int TOO_MANY_V_P_C_ASSOCIATION_AUTHORIZATIONS_HASH = HashingUtils::HashString("TooManyVPCAssociationAuthorizations");
static const int INCOMPATIBLE_VERSION_HASH = HashingUtils::HashString("IncompatibleVersion");
static const int V_P_C_ASSOCIATION_NOT_FOUND_HASH = HashingUtils::HashString("VPCAssociationNotFound");
static const int NO_SUCH_GEO_LOCATION_HASH = HashingUtils::HashString("NoSuchGeoLocation");
static const int DELEGATION_SET_NOT_AVAILABLE_HASH = HashingUtils::HashString("DelegationSetNotAvailable");
static const int NO_SUCH_TRAFFIC_POLICY_INSTANCE_HASH = HashingUtils::HashString("NoSuchTrafficPolicyInstance");
static const int INVALID_ARGUMENT_HASH = HashingUtils::HashString("InvalidArgument");
static const int V_P_C_ASSOCIATION_AUTHORIZATION_NOT_FOUND_HASH = HashingUtils::HashString("VPCAssociationAuthorizationNotFound");
static const int PUBLIC_ZONE_V_P_C_ASSOCIATION_HASH = HashingUtils::HashString("PublicZoneVPCAssociation");
static const int NO_SUCH_HOSTED_ZONE_HASH = HashingUtils::HashString("NoSuchHostedZone");
static const int DELEGATION_SET_NOT_REUSABLE_HASH = HashingUtils::HashString("DelegationSetNotReusable");
static const int TRAFFIC_POLICY_IN_USE_HASH = HashingUtils::HashString("TrafficPolicyInUse");
static const int TOO_MANY_HEALTH_CHECKS_HASH = HashingUtils::HashString("TooManyHealthChecks");
static const int INVALID_CHANGE_BATCH_HASH = HashingUtils::HashString("InvalidChangeBatch");
static const int NOT_AUTHORIZED_HASH = HashingUtils::HashString("NotAuthorizedException");
static const int HOSTED_ZONE_NOT_PRIVATE_HASH = HashingUtils::HashString("HostedZoneNotPrivate");
static const int HEALTH_CHECK_VERSION_MISMATCH_HASH = HashingUtils::HashString("HealthCheckVersionMismatch");
static const int INVALID_PAGINATION_TOKEN_HASH = HashingUtils::HashString("InvalidPaginationToken");
static const int TRAFFIC_POLICY_INSTANCE_ALREADY_EXISTS_HASH = HashingUtils::HashString("TrafficPolicyInstanceAlreadyExists");
static const int HOSTED_ZONE_NOT_EMPTY_HASH = HashingUtils::HashString("HostedZoneNotEmpty");
static const int NO_SUCH_CLOUD_WATCH_LOGS_LOG_GROUP_HASH = HashingUtils::HashString("NoSuchCloudWatchLogsLogGroup");
static const int TOO_MANY_TRAFFIC_POLICIES_HASH = HashingUtils::HashString("TooManyTrafficPolicies");
static const int DELEGATION_SET_ALREADY_REUSABLE_HASH = HashingUtils::HashString("DelegationSetAlreadyReusable");
static const int INSUFFICIENT_CLOUD_WATCH_LOGS_RESOURCE_POLICY_HASH = HashingUtils::HashString("InsufficientCloudWatchLogsResourcePolicy");
static const int TRAFFIC_POLICY_ALREADY_EXISTS_HASH = HashingUtils::HashString("TrafficPolicyAlreadyExists");
static const int NO_SUCH_HEALTH_CHECK_HASH = HashingUtils::HashString("NoSuchHealthCheck");
AWSError<CoreErrors> GetErrorForName(const char* errorName)
{
int hashCode = HashingUtils::HashString(errorName);
if (hashCode == TOO_MANY_TRAFFIC_POLICY_INSTANCES_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::TOO_MANY_TRAFFIC_POLICY_INSTANCES), false);
}
else if (hashCode == DELEGATION_SET_ALREADY_CREATED_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::DELEGATION_SET_ALREADY_CREATED), false);
}
else if (hashCode == CONCURRENT_MODIFICATION_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::CONCURRENT_MODIFICATION), false);
}
else if (hashCode == HOSTED_ZONE_NOT_FOUND_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::HOSTED_ZONE_NOT_FOUND), false);
}
else if (hashCode == NO_SUCH_DELEGATION_SET_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::NO_SUCH_DELEGATION_SET), false);
}
else if (hashCode == LAST_V_P_C_ASSOCIATION_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::LAST_V_P_C_ASSOCIATION), false);
}
else if (hashCode == TOO_MANY_HOSTED_ZONES_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::TOO_MANY_HOSTED_ZONES), false);
}
else if (hashCode == NO_SUCH_CHANGE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::NO_SUCH_CHANGE), false);
}
else if (hashCode == QUERY_LOGGING_CONFIG_ALREADY_EXISTS_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::QUERY_LOGGING_CONFIG_ALREADY_EXISTS), false);
}
else if (hashCode == CONFLICTING_TYPES_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::CONFLICTING_TYPES), false);
}
else if (hashCode == TOO_MANY_TRAFFIC_POLICY_VERSIONS_FOR_CURRENT_POLICY_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::TOO_MANY_TRAFFIC_POLICY_VERSIONS_FOR_CURRENT_POLICY), false);
}
else if (hashCode == INVALID_TRAFFIC_POLICY_DOCUMENT_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::INVALID_TRAFFIC_POLICY_DOCUMENT), false);
}
else if (hashCode == LIMITS_EXCEEDED_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::LIMITS_EXCEEDED), false);
}
else if (hashCode == NO_SUCH_TRAFFIC_POLICY_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::NO_SUCH_TRAFFIC_POLICY), false);
}
else if (hashCode == CONFLICTING_DOMAIN_EXISTS_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::CONFLICTING_DOMAIN_EXISTS), false);
}
else if (hashCode == NO_SUCH_QUERY_LOGGING_CONFIG_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::NO_SUCH_QUERY_LOGGING_CONFIG), false);
}
else if (hashCode == DELEGATION_SET_IN_USE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::DELEGATION_SET_IN_USE), false);
}
else if (hashCode == INVALID_DOMAIN_NAME_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::INVALID_DOMAIN_NAME), false);
}
else if (hashCode == INVALID_INPUT_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::INVALID_INPUT), false);
}
else if (hashCode == HEALTH_CHECK_ALREADY_EXISTS_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::HEALTH_CHECK_ALREADY_EXISTS), false);
}
else if (hashCode == HOSTED_ZONE_ALREADY_EXISTS_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::HOSTED_ZONE_ALREADY_EXISTS), false);
}
else if (hashCode == HEALTH_CHECK_IN_USE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::HEALTH_CHECK_IN_USE), false);
}
else if (hashCode == INVALID_V_P_C_ID_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::INVALID_V_P_C_ID), false);
}
else if (hashCode == PRIOR_REQUEST_NOT_COMPLETE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::PRIOR_REQUEST_NOT_COMPLETE), false);
}
else if (hashCode == TOO_MANY_V_P_C_ASSOCIATION_AUTHORIZATIONS_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::TOO_MANY_V_P_C_ASSOCIATION_AUTHORIZATIONS), false);
}
else if (hashCode == INCOMPATIBLE_VERSION_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::INCOMPATIBLE_VERSION), false);
}
else if (hashCode == V_P_C_ASSOCIATION_NOT_FOUND_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::V_P_C_ASSOCIATION_NOT_FOUND), false);
}
else if (hashCode == NO_SUCH_GEO_LOCATION_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::NO_SUCH_GEO_LOCATION), false);
}
else if (hashCode == DELEGATION_SET_NOT_AVAILABLE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::DELEGATION_SET_NOT_AVAILABLE), false);
}
else if (hashCode == NO_SUCH_TRAFFIC_POLICY_INSTANCE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::NO_SUCH_TRAFFIC_POLICY_INSTANCE), false);
}
else if (hashCode == INVALID_ARGUMENT_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::INVALID_ARGUMENT), false);
}
else if (hashCode == V_P_C_ASSOCIATION_AUTHORIZATION_NOT_FOUND_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::V_P_C_ASSOCIATION_AUTHORIZATION_NOT_FOUND), false);
}
else if (hashCode == PUBLIC_ZONE_V_P_C_ASSOCIATION_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::PUBLIC_ZONE_V_P_C_ASSOCIATION), false);
}
else if (hashCode == NO_SUCH_HOSTED_ZONE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::NO_SUCH_HOSTED_ZONE), false);
}
else if (hashCode == DELEGATION_SET_NOT_REUSABLE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::DELEGATION_SET_NOT_REUSABLE), false);
}
else if (hashCode == TRAFFIC_POLICY_IN_USE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::TRAFFIC_POLICY_IN_USE), false);
}
else if (hashCode == TOO_MANY_HEALTH_CHECKS_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::TOO_MANY_HEALTH_CHECKS), false);
}
else if (hashCode == INVALID_CHANGE_BATCH_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::INVALID_CHANGE_BATCH), false);
}
else if (hashCode == NOT_AUTHORIZED_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::NOT_AUTHORIZED), false);
}
else if (hashCode == HOSTED_ZONE_NOT_PRIVATE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::HOSTED_ZONE_NOT_PRIVATE), false);
}
else if (hashCode == HEALTH_CHECK_VERSION_MISMATCH_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::HEALTH_CHECK_VERSION_MISMATCH), false);
}
else if (hashCode == INVALID_PAGINATION_TOKEN_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::INVALID_PAGINATION_TOKEN), false);
}
else if (hashCode == TRAFFIC_POLICY_INSTANCE_ALREADY_EXISTS_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::TRAFFIC_POLICY_INSTANCE_ALREADY_EXISTS), false);
}
else if (hashCode == HOSTED_ZONE_NOT_EMPTY_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::HOSTED_ZONE_NOT_EMPTY), false);
}
else if (hashCode == NO_SUCH_CLOUD_WATCH_LOGS_LOG_GROUP_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::NO_SUCH_CLOUD_WATCH_LOGS_LOG_GROUP), false);
}
else if (hashCode == TOO_MANY_TRAFFIC_POLICIES_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::TOO_MANY_TRAFFIC_POLICIES), false);
}
else if (hashCode == DELEGATION_SET_ALREADY_REUSABLE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::DELEGATION_SET_ALREADY_REUSABLE), false);
}
else if (hashCode == INSUFFICIENT_CLOUD_WATCH_LOGS_RESOURCE_POLICY_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::INSUFFICIENT_CLOUD_WATCH_LOGS_RESOURCE_POLICY), false);
}
else if (hashCode == TRAFFIC_POLICY_ALREADY_EXISTS_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::TRAFFIC_POLICY_ALREADY_EXISTS), false);
}
else if (hashCode == NO_SUCH_HEALTH_CHECK_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(Route53Errors::NO_SUCH_HEALTH_CHECK), false);
}
return AWSError<CoreErrors>(CoreErrors::UNKNOWN, false);
}
} // namespace Route53ErrorMapper
} // namespace Route53
} // namespace Aws
| 50.481229 | 149 | 0.806234 | curiousjgeorge |
3c7bc997967043880a0651a17560520b98852b2d | 5,397 | hh | C++ | src/corbaExample/src/cpp/Exception.hh | jahlborn/rmiio | 58c05f29e6dbc44c0f18c9a2247aff113d487c71 | [
"Apache-2.0"
] | 7 | 2016-04-05T15:58:01.000Z | 2020-10-30T18:38:05.000Z | src/corbaExample/src/cpp/Exception.hh | jahlborn/rmiio | 58c05f29e6dbc44c0f18c9a2247aff113d487c71 | [
"Apache-2.0"
] | 2 | 2016-07-04T01:32:56.000Z | 2020-12-11T02:54:56.000Z | src/corbaExample/src/cpp/Exception.hh | jahlborn/rmiio | 58c05f29e6dbc44c0f18c9a2247aff113d487c71 | [
"Apache-2.0"
] | 6 | 2016-04-05T15:58:16.000Z | 2020-04-27T21:45:47.000Z | // This file is generated by omniidl (C++ backend)- omniORB_4_1. Do not edit.
#ifndef __Exception_hh__
#define __Exception_hh__
#ifndef __CORBA_H_EXTERNAL_GUARD__
#include <omniORB4/CORBA.h>
#endif
#ifndef USE_stub_in_nt_dll
# define USE_stub_in_nt_dll_NOT_DEFINED_Exception
#endif
#ifndef USE_core_stub_in_nt_dll
# define USE_core_stub_in_nt_dll_NOT_DEFINED_Exception
#endif
#ifndef USE_dyn_stub_in_nt_dll
# define USE_dyn_stub_in_nt_dll_NOT_DEFINED_Exception
#endif
#ifndef __seq1__StackTraceElement_hh_EXTERNAL_GUARD__
#define __seq1__StackTraceElement_hh_EXTERNAL_GUARD__
#include <seq1_StackTraceElement.hh>
#endif
#ifndef __corbaidl_hh_EXTERNAL_GUARD__
#define __corbaidl_hh_EXTERNAL_GUARD__
#include <corbaidl.hh>
#endif
#ifndef __boxes_hh_EXTERNAL_GUARD__
#define __boxes_hh_EXTERNAL_GUARD__
#include <boxes.hh>
#endif
#ifndef __StackTraceElement_hh_EXTERNAL_GUARD__
#define __StackTraceElement_hh_EXTERNAL_GUARD__
#include <StackTraceElement.hh>
#endif
#ifndef __Throwable_hh_EXTERNAL_GUARD__
#define __Throwable_hh_EXTERNAL_GUARD__
#include <Throwable.hh>
#endif
#ifdef USE_stub_in_nt_dll
# ifndef USE_core_stub_in_nt_dll
# define USE_core_stub_in_nt_dll
# endif
# ifndef USE_dyn_stub_in_nt_dll
# define USE_dyn_stub_in_nt_dll
# endif
#endif
#ifdef _core_attr
# error "A local CPP macro _core_attr has already been defined."
#else
# ifdef USE_core_stub_in_nt_dll
# define _core_attr _OMNIORB_NTDLL_IMPORT
# else
# define _core_attr
# endif
#endif
#ifdef _dyn_attr
# error "A local CPP macro _dyn_attr has already been defined."
#else
# ifdef USE_dyn_stub_in_nt_dll
# define _dyn_attr _OMNIORB_NTDLL_IMPORT
# else
# define _dyn_attr
# endif
#endif
_CORBA_MODULE java
_CORBA_MODULE_BEG
_CORBA_MODULE lang
_CORBA_MODULE_BEG
#ifndef __java_mlang_mException__
#define __java_mlang_mException__
class Exception;
class Exception_Helper {
public:
static void add_ref(Exception*);
static void remove_ref(Exception*);
static void marshal(Exception*, cdrStream&);
static Exception* unmarshal(cdrStream&);
};
typedef _CORBA_Value_Var <Exception,Exception_Helper> Exception_var;
typedef _CORBA_Value_Member <Exception,Exception_Helper> Exception_member;
typedef _CORBA_Value_OUT_arg<Exception,Exception_Helper> Exception_out;
#endif // __java_mlang_mException__
class Exception :
public virtual Throwable
{
public:
// Standard mapping
typedef Exception* _ptr_type;
typedef Exception_var _var_type;
static _ptr_type _downcast (CORBA::ValueBase*);
#ifdef OMNI_HAVE_COVARIANT_RETURNS
virtual Exception* _copy_value();
#else
virtual CORBA::ValueBase* _copy_value();
#endif
// Definitions in this scope
// Operations and attributes
// Accessors for public members
protected:
// Accessors for private members
public:
// omniORB internal
virtual const char* _NP_repositoryId() const;
virtual const char* _NP_repositoryId(CORBA::ULong& _hashval) const;
virtual const _omni_ValueIds* _NP_truncatableIds() const;
virtual CORBA::Boolean _NP_custom() const;
virtual void* _ptrToValue(const char* id);
static void _NP_marshal(Exception*, cdrStream&);
static Exception* _NP_unmarshal(cdrStream&);
virtual void _PR_marshal_state(cdrStream&) const;
virtual void _PR_unmarshal_state(cdrStream&);
virtual void _PR_copy_state(Exception*);
static _core_attr const char* _PD_repoId;
protected:
Exception();
virtual ~Exception();
private:
// Not implemented
Exception(const Exception &);
void operator=(const Exception &);
};
class Exception_init : public CORBA::ValueFactoryBase
{
public:
virtual ~Exception_init();
virtual Exception* create__() = 0;
virtual Exception* create__CORBA_WStringValue(CORBA::WStringValue* arg0) = 0;
virtual Exception* create__CORBA_WStringValue__java_lang_Throwable(CORBA::WStringValue* arg0, Throwable* arg1) = 0;
virtual Exception* create__java_lang_Throwable(Throwable* arg0) = 0;
static Exception_init* _downcast(CORBA::ValueFactory _v);
virtual void* _ptrToFactory(const char* _id);
protected:
Exception_init();
};
_CORBA_MODULE_END
_CORBA_MODULE_END
_CORBA_MODULE POA_java
_CORBA_MODULE_BEG
_CORBA_MODULE lang
_CORBA_MODULE_BEG
_CORBA_MODULE_END
_CORBA_MODULE_END
_CORBA_MODULE OBV_java
_CORBA_MODULE_BEG
_CORBA_MODULE lang
_CORBA_MODULE_BEG
class Exception :
public virtual java::lang::Exception,
public virtual Throwable
{
protected:
Exception();
virtual ~Exception();
public:
protected:
private:
};
_CORBA_MODULE_END
_CORBA_MODULE_END
#undef _core_attr
#undef _dyn_attr
#ifdef USE_stub_in_nt_dll_NOT_DEFINED_Exception
# undef USE_stub_in_nt_dll
# undef USE_stub_in_nt_dll_NOT_DEFINED_Exception
#endif
#ifdef USE_core_stub_in_nt_dll_NOT_DEFINED_Exception
# undef USE_core_stub_in_nt_dll
# undef USE_core_stub_in_nt_dll_NOT_DEFINED_Exception
#endif
#ifdef USE_dyn_stub_in_nt_dll_NOT_DEFINED_Exception
# undef USE_dyn_stub_in_nt_dll
# undef USE_dyn_stub_in_nt_dll_NOT_DEFINED_Exception
#endif
#endif // __Exception_hh__
| 21.248031 | 121 | 0.753011 | jahlborn |
3c84d57cd85e58a9908b30b4bddfa64d26c7276f | 806 | cpp | C++ | source/419.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | 2 | 2017-02-28T11:39:13.000Z | 2019-12-07T17:23:20.000Z | source/419.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | source/419.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | //
// 419.cpp
// LeetCode
//
// Created by Narikbi on 15.02.17.
// Copyright © 2017 app.leetcode.kz. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <deque>
#include <queue>
#include <set>
using namespace std;
int countBattleships(vector<vector<char>>& board) {
if (board.size() == 0) return 0;
int count = 0;
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[i].size(); j++) {
if (board[i][j] == '.') continue;
if (i > 0 && board[i-1][j] == 'X') continue;
if (j > 0 && board[i][j-1] == 'X') continue;
count++;
}
}
return count;
}
//int main(int argc, const char * argv[]) {
//
// return 0;
//}
//
| 19.190476 | 58 | 0.51861 | narikbi |
3c84de4c76c7ddfcb7da0b8105f517d26dcd8567 | 3,276 | hpp | C++ | kernel/pci.hpp | hapo31/My-MikanOS | a21720980a0c1557320ca321f446451819529c54 | [
"Apache-2.0"
] | null | null | null | kernel/pci.hpp | hapo31/My-MikanOS | a21720980a0c1557320ca321f446451819529c54 | [
"Apache-2.0"
] | null | null | null | kernel/pci.hpp | hapo31/My-MikanOS | a21720980a0c1557320ca321f446451819529c54 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <stdint.h>
#include <array>
#include "error.hpp"
namespace pci {
class ClassCode {
public:
ClassCode() = default;
ClassCode(uint32_t reg) {
base = (reg >> 24) & 0xffu;
sub = (reg >> 16) & 0xffu;
interface = (reg >> 8) & 0xffu;
}
uint8_t base, sub, interface;
bool Match(uint8_t b) const { return b == base; }
bool Match(uint8_t b, uint8_t s) const { return b == base && s == sub; }
bool Match(uint8_t b, uint8_t s, uint8_t i) const {
return Match(b, s) && i == interface;
}
};
struct Device {
uint8_t bus, device, function, header_type;
ClassCode class_code;
};
const uint16_t kConfigAddress = 0x0cf8;
const uint16_t kConfigData = 0x0cfc;
void WriteAddress(uint32_t address);
void WriteData(uint32_t value);
uint32_t ReadData();
uint16_t ReadVendorId(uint8_t bus, uint8_t device, uint8_t function);
inline uint16_t ReadVendorId(const Device &dev) {
return ReadVendorId(dev.bus, dev.device, dev.function);
}
uint16_t ReadDeviceId(uint8_t bus, uint8_t device, uint8_t function);
uint8_t ReadHeaderType(uint8_t bus, uint8_t device, uint8_t function);
ClassCode ReadClassCode(uint8_t bus, uint8_t device, uint8_t function);
uint32_t ReadBusNumbers(uint8_t bus, uint8_t device, uint8_t function);
uint32_t ReadConfReg(const Device &dev, uint8_t reg_addr);
void WriteConfReg(const Device &dev, uint8_t reg_addr, uint32_t value);
bool IsSingleFunctionDevice(uint8_t header_type);
inline std::array<Device, 32> devices;
inline int num_devices;
Error ScanAllBus();
constexpr uint8_t CalcBarAddress(unsigned int bar_index) {
return 0x10 + 4 * bar_index;
}
WithError<uint64_t> ReadBar(Device &device, unsigned int bar_index);
union CapabilityHeader {
uint32_t data;
struct {
uint32_t cap_id : 8;
uint32_t next_ptr : 8;
uint32_t cap : 16;
} __attribute__((packed)) bits;
} __attribute__((packed));
const uint8_t kCapabilityMSI = 0x05;
const uint8_t kCapabilityMSIX = 0x11;
CapabilityHeader ReadCapabilityHeader(const Device &dev, uint8_t addr);
struct MSICapability {
union {
uint32_t data;
struct {
uint32_t cap_id : 8;
uint32_t next_ptr : 8;
uint32_t msi_enable : 1;
uint32_t multi_msg_capable : 3;
uint32_t multi_msg_enable : 3;
uint32_t addr_64_capable : 1;
uint32_t per_vector_mask_capable : 1;
uint32_t : 7;
} __attribute__((packed)) bits;
} __attribute__((packed)) header;
uint32_t msg_addr;
uint32_t msg_upper_addr;
uint32_t msg_data;
uint32_t mask_bits;
uint32_t pending_bits;
} __attribute__((packed));
Error ConfigureMSI(const Device &dev, uint32_t msg_addr, uint32_t msg_data,
unsigned int num_vector_exponent);
enum class MSITriggerMode { kEdge = 0, kLevel = 1 };
enum class MSIDeliveryMode {
kFixed = 0b000,
kLowestPriority = 0b001,
kSMI = 0b010,
kNMI = 0b100,
kINIT = 0b101,
kExtINT = 0b111,
};
Error ConfigureMSIFixedDestination(const Device &dev, uint8_t apic_id,
MSITriggerMode trigger_mode,
MSIDeliveryMode delivery_mode,
uint8_t vector,
unsigned int num_vector_exponent);
} // namespace pci
void InitializePCI(); | 26.208 | 75 | 0.693834 | hapo31 |
3c89628a3db25c2d06783adcfb0d07140b78c985 | 2,435 | cpp | C++ | glfw-ftgl/main.cpp | Wandao123/ising_model | 36c1beafaffb4dd03cb7658d951a9e049532fc74 | [
"MIT"
] | 3 | 2019-10-24T07:25:30.000Z | 2020-07-14T10:42:02.000Z | glfw-ftgl/main.cpp | Wandao123/ising_model | 36c1beafaffb4dd03cb7658d951a9e049532fc74 | [
"MIT"
] | null | null | null | glfw-ftgl/main.cpp | Wandao123/ising_model | 36c1beafaffb4dd03cb7658d951a9e049532fc74 | [
"MIT"
] | null | null | null | //#include <iostream>
#include <cstdlib>
#include "ising_model.h"
IsingModel isingModel(std::pow(IsingModel::SideLength, 2) * (2.e0 + 0.5 * IsingModel::SideLength));
static bool IsUpdating = false;
void idle()
{
if (IsUpdating)
isingModel.Update();
}
void display(GLFWwindow* window)
{
glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
isingModel.Draw();
glfwSwapBuffers(window);
//glFlush();
}
void mouseButton(GLFWwindow*, int button, int action, int)
{
if (action == GLFW_PRESS) {
switch (button) {
case GLFW_MOUSE_BUTTON_LEFT:
case GLFW_MOUSE_BUTTON_MIDDLE:
case GLFW_MOUSE_BUTTON_RIGHT:
isingModel.Update();
break;
}
}
}
void keyboard(GLFWwindow* window, int key, int, int action, int)
{
if (action == GLFW_RELEASE) {
switch (key) {
case GLFW_KEY_Q:
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GL_TRUE);
}
} else {
switch (key) {
case GLFW_KEY_A:
isingModel.SwitchAutoCooling();
break;
case GLFW_KEY_C:
isingModel.ChangeAlgorithm();
break;
case GLFW_KEY_SPACE:
if (IsUpdating) {
IsUpdating = false;
} else {
IsUpdating = true;
}
break;
case GLFW_KEY_UP:
isingModel.Increase();
break;
case GLFW_KEY_DOWN:
isingModel.Decrease();
break;
}
}
}
int main()
{
// Initialization
if (!glfwInit())
return -1;
//glfwWindowHint(GLFW_DOUBLEBUFFER, GL_FALSE);
GLFWwindow* window = glfwCreateWindow(ScreenWidth, ScreenHeight, "Ising model", nullptr, nullptr);
if (!window) {
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSwapInterval(0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, ScreenWidth, ScreenHeight, 0.0, -1.0, 1.0);
// Setting call back functions
glfwSetMouseButtonCallback(window, mouseButton);
glfwSetKeyCallback(window, keyboard);
// Event loop
unsigned long int frameCount = 0;
//double previousTime = glfwGetTime(); unsigned long int previousFrame = 0;
while (!glfwWindowShouldClose(window)) {
++frameCount;
// Calculate FPS
/*double currentTime = glfwGetTime();
if (currentTime - previousTime >= 1.0) {
std::cout << frameCount - previousFrame << std::endl;
previousTime = currentTime;
previousFrame = frameCount;
}*/
idle();
display(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
| 21.936937 | 100 | 0.663655 | Wandao123 |
3c8eab51d9c2005d051f2aca370bea1a25eeac88 | 1,406 | cpp | C++ | Interviewbit/SubstringConcatenation.cpp | acheiveer/CPP-Questions-and-Solutions | 17097bfb25a75568122ce313d571cb473d55fdf3 | [
"MIT"
] | 42 | 2021-09-26T18:02:52.000Z | 2022-03-15T01:52:15.000Z | Interviewbit/SubstringConcatenation.cpp | acheiveer/CPP-Questions-and-Solutions | 17097bfb25a75568122ce313d571cb473d55fdf3 | [
"MIT"
] | 404 | 2021-09-24T19:55:10.000Z | 2021-11-03T05:47:47.000Z | Interviewbit/SubstringConcatenation.cpp | acheiveer/CPP-Questions-and-Solutions | 17097bfb25a75568122ce313d571cb473d55fdf3 | [
"MIT"
] | 140 | 2021-09-22T20:50:04.000Z | 2022-01-22T16:59:09.000Z | /**
Instead of Dynamic programming approach i sticked to hashing approach
- Create a map for all the string in list of string array with count/frequency
- No start iterating strings with L(length of each string) as the addition in each
- Maintain the count of string appread in the substring from (that start to totallength of big string)
- for Each iteraration see if both the hashmao match and have same frequncy of word
- If same add the starting index to result ArrayList
**/
vector<int> Solution::findSubstring(string A, const vector<string> &B) {
unordered_map<string, int> map;
unordered_map<string, int> tempMap;
int n = B.size();
vector<int> result;
if(n == 0) return result;
int m = B[0].length();
if(A.length() < m*n) return result;
for(int i=0;i<n;i++)
map[B[i]]++;
for(int i=0;i<=A.length()-(m*n);i++){
tempMap = map;
bool available =false;
for(int j=0;j<n;j++){
int var = i+(j*m);
string str = A.substr(var, m);
if(tempMap.find(str) != tempMap.end()){
if(j == n-1) available = true;
tempMap[str]--;
if(tempMap[str] == 0)
tempMap.erase(str);
} else
break;
}
if(available)
result.push_back(i);
}
return result;
}
| 31.954545 | 107 | 0.565434 | acheiveer |
3c91f3078dba773e033d0fd5a28a2c446aaccd55 | 4,392 | cpp | C++ | CentipedeGame_gageoconnor/Game Components/CentipedeHead.cpp | Shaditto/centipede-teal | f078b11eaecddae17709dc9f917348b7b0733d56 | [
"MIT"
] | null | null | null | CentipedeGame_gageoconnor/Game Components/CentipedeHead.cpp | Shaditto/centipede-teal | f078b11eaecddae17709dc9f917348b7b0733d56 | [
"MIT"
] | null | null | null | CentipedeGame_gageoconnor/Game Components/CentipedeHead.cpp | Shaditto/centipede-teal | f078b11eaecddae17709dc9f917348b7b0733d56 | [
"MIT"
] | 1 | 2019-11-13T19:26:34.000Z | 2019-11-13T19:26:34.000Z | /* CentipedeHead.cpp - Gage O'Connor, October 2017 */
#include "CentipedeHead.h"
#include "Centipede_HeadFactory.h"
#include "Centipede_SegmentFactory.h"
#include "Head_MoveFSM.h"
CentipedeHead::CentipedeHead()
: SCORE(Score::Centipede_Head),
pHead(this),
MAX_HEALTH(1)
{
// Initialize remaining variables
health = MAX_HEALTH;
pNext = 0;
// Grab the bitmap and assign it to MainSprite
bitmap = ResourceManager::GetTextureBitmap("centipede_head");
MainSprite = AnimatedSprite(ResourceManager::GetTexture("centipede_head"), 8, 2);
// Set the animation to loop
MainSprite.SetLoopSpeed(8);
MainSprite.SetAnimation(0, 7, true, true);
// Set origin and scale
MainSprite.setOrigin(MainSprite.getTextureRect().width / 2.0f, MainSprite.getTextureRect().height / 2.0f);
MainSprite.setScale(2, 2);
// Sets and registers collision
SetCollider(MainSprite, bitmap);
MainSprite.setPosition(Pos);
}
void CentipedeHead::Initialize(Tile* pTile, sf::Vector2f pos, int index, const HeadMoveState* state, int num, CentipedeSegment* seg)
{
this->pNext = seg;
if (seg != 0)
seg->setPrev(this);
this->pTile = pTile; //(0, 14)
this->pOldTile = this->pTile;
this->index = index;
this->Pos = pos;
this->oldPos = Pos;
this->pCurrentState = state;
health = MAX_HEALTH;
/* Fixes rotation due to recycling */
if (pCurrentState == &HeadMoveFSM::StateMoveLeftAndDown || pCurrentState == &HeadMoveFSM::StateMoveLeftAndUp)
MainSprite.setRotation(0);
if (pCurrentState == &HeadMoveFSM::StateMoveRightAndDown || pCurrentState == &HeadMoveFSM::StateMoveRightAndUp)
MainSprite.setRotation(-180);
// Creates new Centipede Segments
if (num > 0)
CreateSegments(num);
WaveManager::SetCenti(this);
RegisterCollision<CentipedeHead>(*this);
}
/* METHODS */
void CentipedeHead::Update()
{
MainSprite.Update();
if (index > int(pCurrentState->GetMoveOffsets().size() - 1)) // If no more moves, check State
{
pOldTile = pTile; // For segments to grab
pCurrentState = pCurrentState->GetNextState(this); // Grab next State
index = 0;
}
// Update position and move index
Pos += sf::Vector2f(pCurrentState->GetMoveOffsets()[index].x, pCurrentState->GetMoveOffsets()[index].y);
MainSprite.rotate(pCurrentState->GetMoveOffsets()[index].z);
index++;
MainSprite.setPosition(Pos);
}
void CentipedeHead::Draw()
{
WindowManager::MainWindow.draw(MainSprite);
}
void CentipedeHead::Destroy()
{
WaveManager::FreeCenti(this);
DeregisterCollision<CentipedeHead>(*this);
}
// Assigns Head's current Tile
void CentipedeHead::setTile(Tile *pTile)
{
this->pTile = pTile;
}
// Returns Head's current Tile
Tile *CentipedeHead::getTile()
{
return this->pTile;
}
// Returns Head's last used Tile
Tile *CentipedeHead::getOldTile()
{
return this->pOldTile;
}
// Creates a given number of Segments for a Head
void CentipedeHead::CreateSegments(int num)
{
Centipede* traverse = this->pHead;
for (int i = 0; i < num; i++)
{
CentipedeSegmentFactory::createCentipedeSegment(traverse->getTile(), traverse->getPos(), 0, &HeadMoveFSM::StateDoNothing, traverse);
traverse = traverse->getNext();
}
}
// Returns the Head's current Move State
const HeadMoveState *CentipedeHead::GetNextState()
{
return this->pCurrentState;
}
// Returns the Head's current index
int CentipedeHead::GetIndex()
{
return this->index;
}
void CentipedeHead::ReportHeadRecall()
{
CentipedeHeadFactory::ReportRecall();
}
void CentipedeHead::Split()
{
CentipedeSegment* temp1 = this->pHead->getNext(); // Point to adjacent segment
if (pNext != 0) // If it is a segment
{
CentipedeHeadFactory::createCentipedeHead(temp1->getTile(), temp1->getPos(), temp1->GetIndex(), temp1->GetNextState(), 0, temp1->getNext()); // Spawns new Head adjacent
//Remove the replaced Segment
temp1->setNext(0);
temp1->setPrev(0);
temp1->Delete();
}
}
void CentipedeHead::PlaceShroom()
{
// Attempt to spawn mushroom
if (pTile->hasObject() == false)
{
MushroomFactory::createMushroom(pTile->getPos(), pTile);
ConsoleMsg::WriteLine("New Mushroom at: " + Tools::ToString(pTile->getPos()));
}
}
/* COLLISIONS */
void CentipedeHead::Collision(Bullet *other)
{
// Splits head appropriately
Split();
// Places a mushroom at current location
PlaceShroom();
// Add score and destroy
CentipedeHeadFactory::ReportDeath();
MarkForDestroy();
}
void CentipedeHead::Collision(Mushroom *other)
{
} | 24 | 170 | 0.722905 | Shaditto |
3c9230e97fdd1595a8a6f61d4a63f8e2da5626d6 | 8,692 | hpp | C++ | test_nodejs/input.hpp | hirakuni45/test | 04254eab7d2398408aa0015194d4c21011f9bd7a | [
"BSD-3-Clause"
] | 6 | 2016-03-07T02:40:09.000Z | 2021-07-25T11:07:01.000Z | test_nodejs/input.hpp | hirakuni45/test | 04254eab7d2398408aa0015194d4c21011f9bd7a | [
"BSD-3-Clause"
] | 2 | 2021-11-16T17:51:01.000Z | 2021-11-16T17:51:42.000Z | test_nodejs/input.hpp | hirakuni45/test | 04254eab7d2398408aa0015194d4c21011f9bd7a | [
"BSD-3-Clause"
] | 1 | 2021-01-17T23:03:33.000Z | 2021-01-17T23:03:33.000Z | #pragma once
//=====================================================================//
/*! @file
@brief input クラス @n
数値、文字列などの入力クラス @n
%b ---> 2進の数値 @n
%o ---> 8進の数値 @n
%d ---> 10進の数値 @n
%x ---> 16進の数値 @n
%f ---> 浮動小数点数(float、double) @n
%c ---> 1文字のキャラクター @n
%% ---> '%' のキャラクター
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <type_traits>
#include <unistd.h>
namespace utils {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 標準入力ファンクタ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class def_chainp {
const char* str_;
char last_;
bool unget_;
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] str 入力文字列(省力された場合「sci_getch」を使う)
*/
//-----------------------------------------------------------------//
def_chainp(const char* str = nullptr) : str_(str), last_(0), unget_(false) { }
//-----------------------------------------------------------------//
/*!
@brief 1文字戻す
*/
//-----------------------------------------------------------------//
void unget() {
unget_ = true;
}
//-----------------------------------------------------------------//
/*!
@brief ファンクタ(文字取得)
@return 文字
*/
//-----------------------------------------------------------------//
char operator() () {
if(unget_) {
unget_ = false;
} else {
if(str_ == nullptr) {
char ch;
if(read(0, &ch, 1) == 1) {
if(ch == '\n') ch = 0;
last_ = ch;
} else {
last_ = 0;
}
} else {
last_ = *str_;
if(last_ != 0) { ++str_; }
}
}
return last_;
}
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 汎用入力クラス
@param[in] INP 文字入力クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class INP>
class basic_input {
public:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief エラー種別
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class error : uint8_t {
none, ///< エラー無し
cha_sets, ///< 文字セットの不一致
partition, ///< 仕切りキャラクターの不一致
input_type, ///< 無効な入力タイプ
not_integer, ///< 整数の不一致
not_float, ///< 浮動小数点の不一致
terminate, ///< 終端文字の不一致
};
private:
const char* form_;
INP inp_;
enum class mode : uint8_t {
NONE,
BIN,
OCT,
DEC,
HEX,
REAL,
CHA,
};
mode mode_;
error error_;
int num_;
uint32_t bin_() {
uint32_t a = 0;
char ch;
while((ch = inp_()) != 0 && ch >= '0' && ch <= '1') {
a <<= 1;
a += ch - '0';
}
return a;
}
uint32_t oct_() {
uint32_t a = 0;
char ch;
while((ch = inp_()) != 0 && ch >= '0' && ch <= '7') {
a <<= 3;
a += ch - '0';
}
return a;
}
uint32_t dec_() {
uint32_t a = 0;
char ch;
while((ch = inp_()) != 0 && ch >= '0' && ch <= '9') {
a *= 10;
a += ch - '0';
}
return a;
}
uint32_t hex_() {
uint32_t a = 0;
char ch;
while((ch = inp_()) != 0) {
if(ch >= '0' && ch <= '9') {
a <<= 4;
a += ch - '0';
} else if(ch >= 'A' && ch <= 'F') {
a <<= 4;
a += ch - 'A' + 10;
} else if(ch >= 'a' && ch <= 'f') {
a <<= 4;
a += ch - 'a' + 10;
} else {
break;
}
}
return a;
}
template<typename T>
T real_() {
uint32_t a = 0;
uint32_t b = 0;
uint32_t c = 1;
char ch;
bool p = false;
while((ch = inp_()) != 0) {
if(ch >= '0' && ch <= '9') {
a *= 10;
a += ch - '0';
c *= 10;
} else if(!p && ch == '.') {
b = a;
a = 0;
c = 1;
p = true;
} else {
break;
}
}
if(p) {
return static_cast<T>(b) + (static_cast<T>(a) / static_cast<T>(c));
} else {
return static_cast<T>(a);
}
}
void next_()
{
enum class fmm : uint8_t {
none,
type,
};
fmm cm = fmm::none;
char ch;
while((ch = *form_++) != 0) {
switch(cm) {
case fmm::none:
if(ch == '[') {
auto a = inp_();
const char* p = form_;
bool ok = false;
while((ch = *p++) != 0 && ch != ']') {
if(ch == a) ok = true;
}
form_ = p;
if(!ok) {
error_ = error::cha_sets;
return;
}
} else if(ch == '%' && *form_ != '%') {
cm = fmm::type;
} else if(ch != inp_()) {
error_ = error::partition;
return;
}
break;
case fmm::type:
switch(ch) {
case 'b':
mode_ = mode::BIN;
break;
case 'o':
mode_ = mode::OCT;
break;
case 'd':
mode_ = mode::DEC;
break;
case 'x':
mode_ = mode::HEX;
break;
case 'f':
mode_ = mode::REAL;
break;
case 'c':
mode_ = mode::CHA;
break;
default:
error_ = error::input_type;
break;
}
return;
}
}
if(ch == 0 && inp_() == 0) ;
else {
error_ = error::terminate;
}
}
bool neg_() {
bool neg = false;
auto s = inp_();
if(s == '-') { neg = true; }
else if(s == '+') { neg = false; }
else inp_.unget();
return neg;
}
void skip_space_() {
while(1) {
char ch = inp_();
if(ch != ' ') {
inp_.unget();
return;
}
}
}
int32_t nb_int_(bool sign = true)
{
skip_space_();
auto neg = neg_();
uint32_t v = 0;
switch(mode_) {
case mode::BIN:
v = bin_();
break;
case mode::OCT:
v = oct_();
break;
case mode::DEC:
v = dec_();
break;
case mode::HEX:
v = hex_();
break;
default:
error_ = error::not_integer;
break;
}
if(error_ == error::none) {
inp_.unget();
next_();
if(error_ == error::none) ++num_;
}
if(sign && neg) return -static_cast<int32_t>(v);
else return static_cast<int32_t>(v);
}
template <typename T>
T nb_real_()
{
skip_space_();
bool neg = neg_();
T v = 0.0f;
switch(mode_) {
case mode::REAL:
v = real_<T>();
break;
default:
error_ = error::not_float;
break;
}
if(error_ == error::none) {
inp_.unget();
next_();
if(error_ == error::none) ++num_;
}
if(neg) return -v;
else return v;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] form 入力形式
@param[in] inp 変換文字列(nullptrの場合、sci_getch で取得)
*/
//-----------------------------------------------------------------//
basic_input(const char* form, const char* inp = nullptr) : form_(form), inp_(inp),
mode_(mode::NONE), error_(error::none), num_(0)
{
next_();
}
//-----------------------------------------------------------------//
/*!
@brief エラー種別を返す
@return エラー
*/
//-----------------------------------------------------------------//
error get_error() const { return error_; }
//-----------------------------------------------------------------//
/*!
@brief 変換ステータスを返す
@return 変換が全て正常なら「true」
*/
//-----------------------------------------------------------------//
bool status() const { return error_ == error::none; }
//-----------------------------------------------------------------//
/*!
@brief 正常変換数を取得
@return 正常変換数
*/
//-----------------------------------------------------------------//
int num() const { return num_; }
//-----------------------------------------------------------------//
/*!
@brief テンプレート・オペレーター「%」
@param[in] val 整数型
@return 自分の参照
*/
//-----------------------------------------------------------------//
template <typename T>
basic_input& operator % (T& val)
{
if(error_ != error::none) return *this;
if(std::is_floating_point<T>::value) {
val = nb_real_<T>();
} else {
if(mode_ == mode::CHA) {
val = inp_();
next_();
} else {
val = nb_int_(std::is_signed<T>::value);
}
}
return *this;
}
};
typedef basic_input<def_chainp> input;
}
| 20.794258 | 85 | 0.358951 | hirakuni45 |
3ca10d77aea8b434ee92f83ecace2f977fc44f32 | 7,504 | cpp | C++ | tests/database_test.cpp | bloodeagle40234/LineairDB | b0e1f601b0459c71f2c58471849340e6da3f830a | [
"Apache-2.0",
"BSD-2-Clause"
] | 83 | 2020-04-28T05:44:32.000Z | 2022-03-27T10:40:55.000Z | tests/database_test.cpp | bloodeagle40234/LineairDB | b0e1f601b0459c71f2c58471849340e6da3f830a | [
"Apache-2.0",
"BSD-2-Clause"
] | 170 | 2020-04-28T08:32:25.000Z | 2022-03-28T23:07:24.000Z | tests/database_test.cpp | bloodeagle40234/LineairDB | b0e1f601b0459c71f2c58471849340e6da3f830a | [
"Apache-2.0",
"BSD-2-Clause"
] | 10 | 2020-04-28T07:12:48.000Z | 2022-03-27T07:05:10.000Z | /*
* Copyright (C) 2020 Nippon Telegraph and Telephone Corporation.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "lineairdb/database.h"
#include <atomic>
#include <chrono>
#include <experimental/filesystem>
#include <memory>
#include <thread>
#include <vector>
#include "gtest/gtest.h"
#include "lineairdb/config.h"
#include "lineairdb/transaction.h"
#include "lineairdb/tx_status.h"
#include "test_helper.hpp"
class DatabaseTest : public ::testing::Test {
protected:
LineairDB::Config config_;
std::unique_ptr<LineairDB::Database> db_;
virtual void SetUp() {
std::experimental::filesystem::remove_all("lineairdb_logs");
config_.max_thread = 4;
config_.checkpoint_period = 1;
db_ = std::make_unique<LineairDB::Database>(config_);
}
};
TEST_F(DatabaseTest, Instantiate) {}
TEST_F(DatabaseTest, InstantiateWithConfig) {
db_.reset(nullptr);
LineairDB::Config conf;
conf.checkpoint_period = 1;
ASSERT_NO_THROW(db_ = std::make_unique<LineairDB::Database>(conf));
}
TEST_F(DatabaseTest, ExecuteTransaction) {
int value_of_alice = 1;
TestHelper::DoTransactions(
db_.get(),
{[&](LineairDB::Transaction& tx) {
tx.Write("alice", reinterpret_cast<std::byte*>(&value_of_alice),
sizeof(int));
},
[&](LineairDB::Transaction& tx) {
auto alice = tx.Read("alice");
ASSERT_NE(alice.first, nullptr);
ASSERT_EQ(value_of_alice, *reinterpret_cast<const int*>(alice.first));
ASSERT_EQ(0, tx.Read("bob").second);
}});
}
TEST_F(DatabaseTest, ExecuteTransactionWithTemplates) {
int value_of_alice = 1;
TestHelper::DoTransactions(db_.get(),
{[&](LineairDB::Transaction& tx) {
tx.Write<int>("alice", value_of_alice);
},
[&](LineairDB::Transaction& tx) {
auto alice = tx.Read<int>("alice");
ASSERT_EQ(value_of_alice, alice.value());
ASSERT_FALSE(tx.Read<int>("bob").has_value());
}});
}
TEST_F(DatabaseTest, Scan) {
int alice = 1;
int bob = 2;
int carol = 3;
TestHelper::DoTransactions(
db_.get(), {[&](LineairDB::Transaction& tx) {
tx.Write<int>("alice", alice);
tx.Write<int>("bob", bob);
tx.Write<int>("carol", carol);
},
[&](LineairDB::Transaction& tx) {
// Scan
auto count = tx.Scan<decltype(alice)>(
"alice", "carol", [&](auto key, decltype(alice) value) {
if (key == "alice") { EXPECT_EQ(alice, value); }
if (key == "bob") { EXPECT_EQ(bob, value); }
if (key == "carol") { EXPECT_EQ(carol, value); }
return false;
});
ASSERT_TRUE(count.has_value());
ASSERT_EQ(count.value(), 3);
},
[&](LineairDB::Transaction& tx) {
// Cancel
auto count = tx.Scan<decltype(alice)>(
"alice", "carol", [&](auto key, decltype(alice) value) {
if (key == "alice") { EXPECT_EQ(alice, value); }
return true;
});
ASSERT_TRUE(count.has_value());
ASSERT_EQ(count.value(), 1);
}});
}
TEST_F(DatabaseTest, ScanWithPhantomAvoidance) {
int alice = 1;
int bob = 2;
int carol = 3;
int dave = 4;
TestHelper::DoTransactions(db_.get(), {[&](LineairDB::Transaction& tx) {
tx.Write<int>("alice", alice);
tx.Write<int>("bob", bob);
tx.Write<int>("carol", carol);
}});
// When there exists conflict between insertion and scanning,
// either one will abort.
auto hit = 0;
const auto committed = TestHelper::DoTransactionsOnMultiThreads(
db_.get(),
{[&](LineairDB::Transaction& tx) { tx.Write<int>("dave", dave); },
[&](LineairDB::Transaction& tx) {
tx.Scan("alice", "dave", [&](auto, auto) {
hit++;
return false;
});
}});
// the key "dave" has been inserted by concurrent transaction and thus
// it is not visible for #Scan operation.
if (committed == 2) { ASSERT_EQ(3, hit); }
}
TEST_F(DatabaseTest, SaveAsString) {
TestHelper::DoTransactions(db_.get(),
{[&](LineairDB::Transaction& tx) {
tx.Write<std::string_view>("alice", "value");
},
[&](LineairDB::Transaction& tx) {
auto alice = tx.Read<std::string_view>("alice");
ASSERT_EQ("value", alice.value());
}});
}
TEST_F(DatabaseTest, UserAbort) {
TestHelper::DoTransactions(db_.get(),
{[&](LineairDB::Transaction& tx) {
int value_of_alice = 1;
tx.Write<int>("alice", value_of_alice);
tx.Abort();
},
[&](LineairDB::Transaction& tx) {
auto alice = tx.Read<int>("alice");
ASSERT_FALSE(alice.has_value()); // Opacity
tx.Abort();
}});
}
TEST_F(DatabaseTest, ReadYourOwnWrites) {
int value_of_alice = 1;
TestHelper::DoTransactions(db_.get(), {[&](LineairDB::Transaction& tx) {
tx.Write<int>("alice", value_of_alice);
auto alice = tx.Read<int>("alice");
ASSERT_EQ(value_of_alice, alice.value());
}});
}
TEST_F(DatabaseTest, ThreadSafetyInsertions) {
TransactionProcedure insertTenTimes([](LineairDB::Transaction& tx) {
int value = 0xBEEF;
for (size_t idx = 0; idx <= 10; idx++) {
tx.Write<int>("alice" + std::to_string(idx), value);
}
});
ASSERT_NO_THROW({
TestHelper::DoTransactionsOnMultiThreads(
db_.get(),
{insertTenTimes, insertTenTimes, insertTenTimes, insertTenTimes});
});
db_->Fence();
TestHelper::DoTransactions(
db_.get(), {[](LineairDB::Transaction& tx) {
for (size_t idx = 0; idx <= 10; idx++) {
auto alice = tx.Read<int>("alice" + std::to_string(idx));
ASSERT_TRUE(alice.has_value());
auto current_value = alice.value();
ASSERT_EQ(0xBEEF, current_value);
}
}});
}
| 37.148515 | 80 | 0.515592 | bloodeagle40234 |
3ca630f1d3291a21b30b6fc523bac10db7f12f33 | 961 | inl | C++ | include/inline/P2P_Endpoint.inl | AR0EN/communication | 7bcc319df0c83746dad6ea51e4ec5ff5b6d68e8d | [
"MIT"
] | 3 | 2021-12-28T06:15:16.000Z | 2022-01-09T12:26:16.000Z | include/inline/P2P_Endpoint.inl | AR0EN/communication | 7bcc319df0c83746dad6ea51e4ec5ff5b6d68e8d | [
"MIT"
] | 15 | 2021-12-17T13:30:08.000Z | 2022-01-09T13:41:34.000Z | include/inline/P2P_Endpoint.inl | AR0EN/communication | 7bcc319df0c83746dad6ea51e4ec5ff5b6d68e8d | [
"MIT"
] | null | null | null | #include "P2P_Endpoint.hpp"
namespace comm {
inline bool P2P_Endpoint::send(std::unique_ptr<Packet>& pPacket) {
if (pPacket) {
if (!mTxQueue.enqueue(pPacket)) {
LOGE("Tx Queue is full!\n");
}
return true;
} else {
LOGE("[%s][%d] Tx packet must not be empty!\n", __func__, __LINE__);
return false;
}
}
inline bool P2P_Endpoint::send(std::unique_ptr<Packet>&& pPacket) {
if (pPacket) {
if (!mTxQueue.enqueue(pPacket)) {
LOGE("Tx Queue is full!\n");
}
return true;
} else {
LOGE("[%s][%d] Tx packet must not be empty!\n", __func__, __LINE__);
return false;
}
}
inline bool P2P_Endpoint::recvAll(std::deque<std::unique_ptr<Packet>>& pRxPackets, bool wait) {
return mDecoder.dequeue(pRxPackets, wait);
}
inline bool P2P_Endpoint::isPeerConnected() {
return true;
}
} // namespace comm
| 25.289474 | 96 | 0.57232 | AR0EN |
3ca63945a6e59ff6281ab40189045b93a67f60e6 | 773 | cpp | C++ | code/2020/21_virtual.cpp | watchpoints/daily-interview | 2a9848ed1290211952aea995dc312bc7e84b221e | [
"Apache-2.0"
] | 2 | 2021-07-21T04:19:46.000Z | 2021-07-21T04:19:52.000Z | code/2020/21_virtual.cpp | watchpoints/daily-interview | 2a9848ed1290211952aea995dc312bc7e84b221e | [
"Apache-2.0"
] | 27 | 2021-03-14T04:28:48.000Z | 2021-12-08T10:39:22.000Z | code/2020/21_virtual.cpp | watchpoints/daily-interview | 2a9848ed1290211952aea995dc312bc7e84b221e | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <typeinfo>
using namespace std;
class Base
{
public:
Base(int a = 1)
{
ma = a;
}
virtual void show()
{
cout<<"base::show"<<endl;
}
void show(int b)
{
cout<<"base show 2"<<endl;
}
private:
int ma;
};
class Derive : public Base
{
public:
Derive(int b = 2):Base(b)
{
mb = b;
}
void show()
{
cout<<"derive::show "<<endl;
}
private:
int mb;
};
int main()
{
Base b;
Derive d;
Base* p = &d;
Derive* pd = &d;
cout<<"base size:"<<" "<<sizeof(b)<<endl;
cout<<"derive size:"<<" "<<sizeof(d)<<endl;
cout<<"p type:"<<" "<<typeid(p).name()<<endl;
cout<<"*p type:"<<" "<<typeid(*p).name()<<endl;
cout<<"pd->show()"<<endl;
pd->show();
b =d;
cout<<"test1:call function"<<endl;
b.show();
return 0;
}
| 12.467742 | 48 | 0.542044 | watchpoints |
3ca6a8fe7f099d2cb5afef1da51ef6496e39b368 | 523 | cpp | C++ | cpp/sqrt.cpp | chaohan/code-samples | 0ae7da954a36547362924003d56a8bece845802c | [
"MIT"
] | null | null | null | cpp/sqrt.cpp | chaohan/code-samples | 0ae7da954a36547362924003d56a8bece845802c | [
"MIT"
] | null | null | null | cpp/sqrt.cpp | chaohan/code-samples | 0ae7da954a36547362924003d56a8bece845802c | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int mySqrt(int x)
{
if (x<2) {return x;}
int j = x,k;
while (true)
{
k = (j+x/j)/2;
if (j<=k) {return j;}
else {j=k;}
}
return j;
}
int main()
{
cout << s.mySqrt(0) << endl;
cout << s.mySqrt(1) << endl;
cout << s.mySqrt(3) << endl;
cout << s.mySqrt(8) << endl;
cout << s.mySqrt(400) << endl;
return 0;
} | 18.678571 | 36 | 0.374761 | chaohan |
3cb13eb8e634f7c6748db39cbcf9c8087cc73ae7 | 1,550 | cpp | C++ | SkeletalAnimation/SkeletalAnimation/Re/Graphics/Gui/GuiText.cpp | Risist/Project-skeletal-animation | 1f39d572521bfa0fef7ce9aebf32152608e3dc33 | [
"MIT"
] | null | null | null | SkeletalAnimation/SkeletalAnimation/Re/Graphics/Gui/GuiText.cpp | Risist/Project-skeletal-animation | 1f39d572521bfa0fef7ce9aebf32152608e3dc33 | [
"MIT"
] | null | null | null | SkeletalAnimation/SkeletalAnimation/Re/Graphics/Gui/GuiText.cpp | Risist/Project-skeletal-animation | 1f39d572521bfa0fef7ce9aebf32152608e3dc33 | [
"MIT"
] | null | null | null | /// Code from ReEngine library
/// all rights belongs to Risist (Maciej Dominiak) (risistt@gmail.com)
#include <Re\Graphics\Gui\GuiText.h>
#include <Re\Graphics\ResourceManager.h>
namespace Gui
{
Text::Text()
{
txt.setFont(res.fonts[1]);
txt.setFillColor(Color::White);
txt.setCharacterSize(25u);
}
void Text::onUpdate(RenderTarget & target, RenderStates states)
{
txt.setString(str);
txt.setPosition(getActualPosition());
/// multiplaying in X axes by 0.25 seems to work
/// Probably because of twice multiplaying by 0.5 ( from size and character size)
/// Take care over that
txt.setOrigin(
static_cast<float>(str.size()* txt.getCharacterSize()) *0.25f,
static_cast<float>(txt.getCharacterSize())*0.5f);
target.draw(txt, states);
}
void Text::serialiseF(std::ostream & file, Res::DataScriptSaver & saver) const
{
/// TODO
}
void Text::deserialiseF(std::istream & file, Res::DataScriptLoader & loader)
{
Base::deserialiseF(file,loader);
str = loader.loadRaw("str", "");
Color cl;
cl.r = loader.load("clR", 255);
cl.g = loader.load("clG", 255);
cl.b = loader.load("clB", 255);
cl.a = loader.load("clA", 255);
txt.setFillColor(cl);
cl.r = loader.load("outClR", 255);
cl.g = loader.load("outClG", 255);
cl.b = loader.load("outClB", 255);
cl.a = loader.load("outClA", 255);
txt.setOutlineColor(cl);
txt.setOutlineThickness(loader.load("outThickness", 0.f));
txt.setCharacterSize(loader.load("size", 25));
txt.setFont(fontInst[loader.load("font", (ResId)1)]);
}
} | 24.603175 | 83 | 0.673548 | Risist |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.