hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
f0f4d31ae7f6da1fc55dcc061022c290329f8c54
724
cpp
C++
Array of objects.cpp
paurav11/Cpp
e8cc137d1530000898c9a92a98663a8a8b254068
[ "MIT" ]
1
2021-05-18T06:52:59.000Z
2021-05-18T06:52:59.000Z
Array of objects.cpp
paurav11/Cpp
e8cc137d1530000898c9a92a98663a8a8b254068
[ "MIT" ]
null
null
null
Array of objects.cpp
paurav11/Cpp
e8cc137d1530000898c9a92a98663a8a8b254068
[ "MIT" ]
null
null
null
#include <iostream> #include <conio.h> #include <stdlib.h> using namespace std; class student { char name[100]; int id,age; public: void getdata() { cout<<"\nEnter name: "; cin>>name; cout<<"Enter id: "; cin>>id; cout<<"Enter age: "; cin>>age; } void display() { cout<<"\nName: "<<name<<endl; cout<<"ID: "<<id<<endl; cout<<"Age: "<<age<<endl; } }; int main() { int i,n; cout<<"Enter no. of students: "; cin>>n; student s[n]; for(i=0;i<n;i++) { s[i].getdata(); } cout<<"\nStudent Details\n"; for(i=0;i<n;i++) { s[i].display(); } _getch(); return 0; }
15.73913
37
0.45442
e7c8407173d6b4e707e9f2fdde5bfd73ab685257
14,476
cpp
C++
src/audio/CSoundMixer.cpp
rherriman/Avara
eaa68133ac273796b60162673b8f240619cb35ed
[ "MIT" ]
null
null
null
src/audio/CSoundMixer.cpp
rherriman/Avara
eaa68133ac273796b60162673b8f240619cb35ed
[ "MIT" ]
null
null
null
src/audio/CSoundMixer.cpp
rherriman/Avara
eaa68133ac273796b60162673b8f240619cb35ed
[ "MIT" ]
null
null
null
/* Copyright ©1994-1996, Juri Munkki All rights reserved. File: CSoundMixer.c Created: Friday, December 23, 1994, 08:25 Modified: Tuesday, August 20, 1996, 00:20 */ #include "CSoundMixer.h" #include "CBasicSound.h" #include "CSoundHub.h" #include "Memory.h" #include "System.h" #define DONT_USE_MINIMUM_VOLUME void AudioCallback(void *userData, uint8_t *stream, int size) { CSoundMixer *theMaster = (CSoundMixer *)userData; theMaster->DoubleBack(stream, size); } void CSoundMixer::StartTiming() { baseTime = SDL_GetTicks(); } int CSoundMixer::ReadTime() { return SDL_GetTicks() - baseTime; } void CSoundMixer::SetSoundEnvironment(Fixed speedOfSound, Fixed distanceToOne, int timeUnit) { if (speedOfSound) { soundSpeed = speedOfSound; distanceToSamples = (unsigned int)samplingRate / (unsigned int)soundSpeed; } if (timeUnit) { timeConversion = 65536L / timeUnit; } else { timeConversion = 65536; // Assume time unit is milliseconds. } if (distanceToOne) { distanceToLevelOne = distanceToOne; distanceToOne >>= 4; distanceAdjust = FMul(distanceToOne, distanceToOne); } if (stereo) maxAdjustedVolume = MAXADJUSTEDVOLUME; else maxAdjustedVolume = MAXADJUSTEDVOLUME / 2; } /* ** Since what you hear depends very much on what kind of environment ** is used to listen to the audio, two different stereo environments ** are provided. ** ** Strong stereo (strongStereo = true) is provided for users who have ** speakers. Since both ears can hear the sound from speakers, the ** stereo separation can be very clear as follows: ** ** Strong stereo: Sound position: LEFT MIDDLE RIGHT ** (Speakers) Left channel 1.0 0.5 0.0 ** Right channel 0.0 0.5 1.0 ** ** Users with headphones can only hear the left channel with the ** left ear and the right channel with the right ear. It seems the ** human hearing system doesn't like hearing sounds from just one ** ear (it gives me a headache), so even when the signal is coming ** from the left side, the channel will still play it at one third ** of the volume on the left and vice versa. ** ** Weak stereo: Sound position: LEFT MIDDLE RIGHT ** (Headphones) Left channel 1.0 0.66 0.33 ** Right channel 0.33 0.66 1.0 */ void CSoundMixer::SetStereoSeparation(Boolean strongFlag) { strongStereo = strongFlag; } void CSoundMixer::UpdateRightVector(Fixed *right) { // Lock with metaphor newRightMeta = false; newRight[0] = right[0]; newRight[1] = right[1]; newRight[2] = right[2]; // Announce that it is ok to access these. newRightMeta = true; } void CSoundMixer::ISoundMixer(Fixed sampRate, short maxChannelCount, short maxMixCount, Boolean stereoEnable, Boolean sample16Enable, Boolean interpolateEnable) { OSErr iErr; int globTemp; short i, j; Vector rightVect = {FIX(1), 0, 0, 0}; sample16flag = true; // TODO: bump this to 48khz? samplingRate = sampRate ? sampRate : rate22khz; if (samplingRate == rate22khz) { standardRate = FIX(1); } else { standardRate = FDivNZ(rate22050hz, samplingRate >> 1) >> 1; } soundBufferBits = BASESOUNDBUFFERBITS; if (samplingRate > rate22khz) { soundBufferBits++; } soundBufferSize = 1 << soundBufferBits; mixBuffers[0] = (WordSample *)NewPtr(2 * soundBufferSize * sizeof(WordSample)); mixBuffers[1] = mixBuffers[0] + soundBufferSize; frameTime = FMulDivNZ(soundBufferSize, FIX(500), samplingRate >> 1); SetSoundEnvironment(FIX(343), FIX(1), 1); UpdateRightVector(rightVect); motion.loc[0] = motion.loc[1] = motion.loc[2] = 0; motion.speed[0] = motion.speed[1] = motion.speed[2] = 0; motionLink = NULL; altLink = NULL; useAltLink = false; maxChannels = maxChannelCount; maxMix = maxMixCount; if (maxMix > maxChannels) maxMix = maxChannels; stereo = stereoEnable; strongStereo = false; hushFlag = false; infoTable = (MixerInfo *)NewPtr(sizeof(MixerInfo) * maxChannels); sortSpace[0] = (MixerInfo **)NewPtr(sizeof(MixerInfo *) * (maxChannels + 1) * 2); sortSpace[1] = sortSpace[0] + maxChannels + 1; for (i = 0; i < maxChannels; i++) { infoTable[i].intro = NULL; infoTable[i].introBackup = NULL; infoTable[i].active = NULL; infoTable[i].release = NULL; infoTable[i].volume = 0; infoTable[i].isFree = true; for (j = 0; j < 2; j++) sortSpace[j][i + 1] = &infoTable[i]; } if (sample16flag) { scaleLookup = NULL; #ifndef DONT_USE_MINIMUM_VOLUME if (soundCapabilities & gestalt16BitSoundIO) minimumVolume = 0; else minimumVolume = MINIMUM8BITVOLUME; #endif } else { PrepareScaleLookup(); #ifndef DONT_USE_MINIMUM_VOLUME minimumVolume = MINIMUM8BITVOLUME; #endif } volumeLookup = (SampleConvert *)NewPtr(sizeof(SampleConvert) * VOLUMERANGE); PrepareVolumeLookup(); sortSpace[0][0] = &dummyChannel; sortSpace[1][0] = &dummyChannel; dummyChannel.volume = 32767; volumeMax = VOLUMERANGE; StartTiming(); size_t bufferRAM = sizeof(WordSample) * 2 * soundBufferSize; doubleBuffers[0] = (WordSample *)malloc(bufferRAM); doubleBuffers[1] = (WordSample *)malloc(bufferRAM); SilenceBuffers(); frameCounter = -2; SDL_AudioSpec want, have; SDL_memset(&want, 0, sizeof(want)); want.freq = samplingRate / 65536; want.format = AUDIO_S16; want.channels = 2; want.samples = soundBufferSize; want.callback = AudioCallback; want.userdata = this; outputDevice = SDL_OpenAudioDevice(NULL, 0, &want, &have, 0); SDL_Log("Sound device (id=%d): format=%d channels=%d samples=%d size=%d\n", outputDevice, want.format, want.channels, want.samples, want.size); SDL_PauseAudioDevice(outputDevice, 0); } void CSoundMixer::PrepareScaleLookup() { int i; int value; Sample *output; int scaleLookupSize; scaleLookupSize = sizeof(Sample) << (VOLUMEBITS + BITSPERSAMPLE - 1); scaleLookup = NewPtr(scaleLookupSize); output = (Sample *)scaleLookup; scaleLookupSize >>= 1; scaleLookupZero = scaleLookup + scaleLookupSize; for (i = -scaleLookupSize; i < scaleLookupSize; i++) { value = (i + (i >> 1)) >> (BITSPERSAMPLE + VOLUMEBITS - 10); value = (value + 257) >> 1; if (value > 255) value = 255; else if (value < 0) value = 0; *output++ = value; } } void CSoundMixer::PrepareVolumeLookup(uint8_t mixerVolume /* 0-100 */) { WordSample *dest; short vol, samp; dest = &volumeLookup[0][0]; if (sample16flag) { for (vol = 1; vol <= VOLUMERANGE; vol++) { for (samp = -SAMPLERANGE / 2; samp < SAMPLERANGE / 2; samp++) { *dest++ = (samp * vol * mixerVolume / 100) << (16 - BITSPERSAMPLE - VOLUMEBITS); } } } else { for (vol = 1; vol <= VOLUMERANGE; vol++) { for (samp = -SAMPLERANGE / 2; samp < SAMPLERANGE / 2; samp++) { *dest++ = (samp * vol * mixerVolume / 100); } } } } void CSoundMixer::SetVolume(uint8_t volume) { PrepareVolumeLookup(std::min(volume, uint8_t(100))); } void CSoundMixer::SilenceBuffers() { for (int j = 0; j < 2; j++) { size_t numChannels = 2; memset(doubleBuffers[j], 0, numChannels * soundBufferSize); } } void CSoundMixer::Dispose() { OSErr iErr; short i; MixerInfo *mix; SDL_PauseAudioDevice(outputDevice, 1); SDL_CloseAudioDevice(outputDevice); if (motionLink) { altLink = NULL; useAltLink = true; motionHub->ReleaseLink(motionLink); motionLink = NULL; } mix = infoTable; for (i = 0; i < maxChannels; i++) { if (mix->active) mix->active->Release(); else if (mix->release) mix->release->Release(); else if (mix->intro) mix->intro->Release(); mix++; } if (mixBuffers[0]) { DisposePtr((Ptr)mixBuffers[0]); mixBuffers[0] = NULL; } #define OBLITERATE(pointer) \ if (pointer) { \ DisposePtr((Ptr)pointer); \ pointer = NULL; \ } OBLITERATE(doubleBuffers[0]) OBLITERATE(doubleBuffers[1]) OBLITERATE(infoTable) OBLITERATE(volumeLookup) OBLITERATE(scaleLookup) OBLITERATE(sortSpace[0]) } void CSoundMixer::HouseKeep() { short i; MixerInfo *mix; mix = infoTable; for (i = 0; i < maxChannels; i++) { if (mix->release) { mix->release->Release(); mix->release = NULL; mix->isFree = true; } mix++; } } void CSoundMixer::AddSound(CBasicSound *theSound) { short i; MixerInfo *mix; mix = infoTable; for (i = 0; i < maxChannels; i++) { if (mix->isFree) { theSound->itsMixer = this; mix->isFree = false; mix->intro = theSound; mix->introBackup = theSound; return; } mix++; } // Couldn't find a free slot, so release the sound immediately. theSound->Release(); } void CSoundMixer::UpdateMotion() { SoundLink *aLink; frameStartTime = ReadTime(); frameEndTime = frameStartTime + frameTime; if (newRightMeta) { rightVector[0] = newRight[0]; rightVector[1] = newRight[1]; rightVector[2] = newRight[2]; newRightMeta = false; } if (useAltLink) aLink = altLink; else aLink = motionLink; if (aLink && (aLink->meta == metaNewData)) { Fixed *s, *d; Fixed t; s = aLink->nSpeed; d = aLink->speed; *d++ = FMul(*s++, timeConversion); *d++ = FMul(*s++, timeConversion); *d++ = FMul(*s++, timeConversion); s = aLink->nLoc; d = aLink->loc; *d++ = *s++; *d++ = *s++; *d++ = *s++; s = aLink->speed; d = aLink->loc; t = aLink->t; *d++ -= *s++ * t; *d++ -= *s++ * t; *d++ -= *s++ * t; aLink->meta = metaNoData; s = aLink->loc; d = motion.loc; *d++ = *s++; *d++ = *s++; *d++ = *s++; s = aLink->speed; d = motion.speed; *d++ = *s++; *d++ = *s++; *d++ = *s++; } } #define DEBUGSOUNDno #ifdef DEBUGSOUND short gDebugMixCount; #endif void CSoundMixer::DoubleBack(uint8_t *stream, int size) { short i; MixerInfo *mix; MixerInfo **sort, **inSort; int volumeTotal; short whichStereo; // SDL_Log("CSoundMixer::DoubleBack wants %d bytes, soundBufferSize=%d\n", size, soundBufferSize); SDL_memset(stream, 0, size); UpdateMotion(); frameCounter++; mixTo[0] = mixBuffers[0]; mixTo[1] = mixBuffers[1]; // Will never actually be touched by monophonic sounds. memset(mixTo[0], 0, soundBufferSize * sizeof(WordSample)); memset(mixTo[1], 0, soundBufferSize * sizeof(WordSample)); /* ** Activate new channels. */ mix = infoTable; i = maxChannels; do { if (mix->intro && mix->intro == mix->introBackup) { mix->active = mix->intro; mix->intro = NULL; mix->introBackup = NULL; mix->active->FirstFrame(); } mix++; } while (--i); #ifdef DEBUGSOUND gDebugMixCount = 0; #endif for (whichStereo = 0; whichStereo <= stereo; whichStereo++) { short volumeLimit = 0; /* ** Go through channels, asking the volume for this side. */ mix = infoTable; i = maxChannels; do { if (mix->active) { volumeLimit += (mix->volume = mix->active->CalcVolume(whichStereo)); } mix++; } while (--i); volumeLimit >>= 5; if (volumeLimit) { mix = infoTable; i = maxChannels; do { if (mix->active && volumeLimit > mix->volume) { mix->volume = 0; } mix++; } while (--i); } /* ** Insertion sort according to volume. */ sort = sortSpace[whichStereo] + 2; i = maxChannels; while (--i) { inSort = sort++; while (inSort[-1]->volume < inSort[0]->volume) { mix = inSort[0]; inSort[0] = inSort[-1]; inSort[-1] = mix; inSort--; } } /* ** Select as many of the loudest sounds that fit. */ volumeTotal = 0; sort = sortSpace[whichStereo] + 1; i = maxMix; do { mix = *sort; if (mix->volume) { volumeTotal += mix->volume; if (volumeTotal >= volumeMax) { mix->volume += volumeMax - volumeTotal; if (mix->volume) sort++; volumeTotal = volumeMax; break; } } else break; sort++; } while (--i); sort--; while (volumeTotal > 0) { mix = *sort--; volumeTotal -= mix->volume; mix->active->WriteFrame(whichStereo, mix->volume); #ifdef DEBUGSOUND gDebugMixCount++; #endif } } mix = infoTable; i = maxChannels; if (hushFlag) { do { if (mix->active) { mix->release = mix->active; mix->active = NULL; mix->volume = 0; } mix++; } while (--i); hushFlag = false; } else { do { if (mix->active && mix->active->EndFrame()) { mix->release = mix->active; mix->active = NULL; mix->volume = 0; } mix++; } while (--i); } InterleaveStereoChannels(mixTo[0], mixTo[1], (WordSample *)stream, soundBufferSize); }
25.396491
102
0.550843
e7c8958dc2beaffff8a59eb2d4072ef8b2a3bd22
1,114
cpp
C++
silk_engine/src/gfx/buffers/index_buffer.cpp
GeorgeAzma/VulkanEngine
0c2279682f526f428b44eae2a82be6933c74320d
[ "MIT" ]
1
2022-02-11T12:49:49.000Z
2022-02-11T12:49:49.000Z
silk_engine/src/gfx/buffers/index_buffer.cpp
GeorgeAzma/VulkanEngine
0c2279682f526f428b44eae2a82be6933c74320d
[ "MIT" ]
null
null
null
silk_engine/src/gfx/buffers/index_buffer.cpp
GeorgeAzma/VulkanEngine
0c2279682f526f428b44eae2a82be6933c74320d
[ "MIT" ]
null
null
null
#include "index_buffer.h" #include "staging_buffer.h" #include "gfx/graphics.h" #include "gfx/buffers/command_buffer.h" IndexBuffer::IndexBuffer(const void* data, VkDeviceSize count, IndexType index_type, VmaMemoryUsage memory_usage) : Buffer(count * indexTypeSize(index_type), VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, memory_usage), index_type(index_type) { setData(data, count * indexTypeSize(index_type)); } void IndexBuffer::bind(VkDeviceSize offset) { Graphics::getActiveCommandBuffer().bindIndexBuffer(buffer, offset, indexType(index_type)); } VkIndexType IndexBuffer::indexType(IndexType index_type) { switch (index_type) { case IndexType::UINT16: return VK_INDEX_TYPE_UINT16; case IndexType::UINT32: return VK_INDEX_TYPE_UINT32; } SK_ERROR("Unsupported index type specified: {0}.", index_type); return VkIndexType(0); } size_t IndexBuffer::indexTypeSize(IndexType index_type) { switch (index_type) { case IndexType::UINT16: return 2; case IndexType::UINT32: return 4; } SK_ERROR("Unsoppurted index type specified: {0}.", index_type); return 0; }
26.52381
113
0.777379
e7cb1b6abec8324c260fbf8ecc7489fc23aa1f9f
780
cpp
C++
Snipets/08_Strings/CharacterCounting.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
Snipets/08_Strings/CharacterCounting.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
Snipets/08_Strings/CharacterCounting.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
// CharacterCounting.cpp // Programa para contar los caracteres contenidos en un string #include <iostream> #include <stdlib.h> #include <stdio.h> #include <string.h> int main() { char str[100]; int i, j, n, k, o; i=0; j=0; k=0; o=0; puts("Introduce una frase"); gets(str); n=strlen(str); while(str[i]!='\0') { if((str[i]>=65) &&(str[i]<97)) j++; if((str[i]>=97) &&(str[i]<122)) k++; if(str[i]==' ') o++; i++; } std::cout << "El numero total de letras es: " << n << std::endl; std::cout << "El numero de letras mayusculas es: " << j << std::endl; std::cout << "El numero de letras minusculas es: " << k << std::endl; std::cout << "El numero de espacios en blanco es: " << o << std::endl; system("pause"); return 0; }
16.595745
71
0.553846
e7d5a48fc6a783714974803c80fcd00436f6473c
3,002
cpp
C++
source/src/gui/qrsystemtray.cpp
Qters/QrChaos
accc5b9efe5469377a09170ecd92e4674d177f9f
[ "MIT" ]
1
2016-10-21T08:14:26.000Z
2016-10-21T08:14:26.000Z
source/src/gui/qrsystemtray.cpp
Qters/QrChaos
accc5b9efe5469377a09170ecd92e4674d177f9f
[ "MIT" ]
null
null
null
source/src/gui/qrsystemtray.cpp
Qters/QrChaos
accc5b9efe5469377a09170ecd92e4674d177f9f
[ "MIT" ]
null
null
null
#include "gui/qrsystemtray.h" #include <QtCore/qdebug.h> #include <QtCore/qmap.h> #include <QtWidgets/qsystemtrayicon.h> #include <QtWidgets/qaction.h> #include <QtWidgets/qmenu.h> #include <QtWidgets/qapplication.h> #include "db/qrtblsystemtray.h" #include "db/qrtblframeconfig.h" NS_CHAOS_BASE_BEGIN class QrSystemTrayPrivate{ QR_DECLARE_PUBLIC(QrSystemTray) public: static QrSystemTrayPrivate *dInstance(); public: QrSystemTrayPrivate(QWidget* parent); ~QrSystemTrayPrivate(); bool initTray(); QAction *getAction(const QString& key); public: QWidget* parent; QMenu trayMenu; QSystemTrayIcon systemTray; QMap<QString, QAction*> actions; public: static QrSystemTray* qInstance; }; QrSystemTray* QrSystemTrayPrivate::qInstance = nullptr; QrSystemTrayPrivate *QrSystemTrayPrivate::dInstance(){ Q_ASSERT(nullptr != QrSystemTrayPrivate::qInstance); return QrSystemTrayPrivate::qInstance->d_func(); } QrSystemTrayPrivate::QrSystemTrayPrivate(QWidget *parent) : parent(parent) {} QrSystemTrayPrivate::~QrSystemTrayPrivate() {} QAction *QrSystemTrayPrivate::getAction(const QString &key) { Q_ASSERT(actions.contains(key)); return actions[key]; } bool QrSystemTrayPrivate::initTray() { QVector<QrSystemlTrayData> trayDatas; if (! QrTbSystemlTrayHelper::getTrayList(&trayDatas)) { return false; } QMap<QString, QString> systemtrayValues; if (! Qters::QrFrame::QrTblFrameConfigHelper::getKeyValuesByType("systemtray", &systemtrayValues)) { return false; } if ("false" == systemtrayValues["use"]) { qDebug() << "database config deside not use system tray"; return false; } systemTray.setIcon(QIcon(systemtrayValues["icon"])); systemTray.setToolTip(systemtrayValues["tooltip"]); trayMenu.clear(); Q_FOREACH(QrSystemlTrayData data, trayDatas) { auto action = new QAction(data.text, parent); action->setIcon(QIcon(data.icon)); if (! data.visible) { action->setVisible(false); } trayMenu.addAction(action); actions[data.key] = action; if (data.separator) { trayMenu.addSeparator(); } } systemTray.setContextMenu(&trayMenu); systemTray.show(); QObject::connect( qApp, &QApplication::aboutToQuit, [this](){ systemTray.hide(); }); return true; } NS_CHAOS_BASE_END USING_NS_CHAOS_BASE; QrSystemTray::QrSystemTray(QWidget* parent) :d_ptr(new QrSystemTrayPrivate(parent)) { QrSystemTrayPrivate::qInstance = this; d_ptr->initTray(); } bool QrSystemTray::qrconnect(const QString &key, const QObject *receiver, const char *member) { auto action = QrSystemTrayPrivate::dInstance()->getAction(key); if (nullptr == action) { return false; } QObject::connect(action, SIGNAL(triggered(bool)), receiver, member); return true; }
24.606557
104
0.675217
e7d5b0650b5e1da2cf4539df03afdd9040eb82ee
17,283
cpp
C++
SerialPortTool/MainWindow.cpp
mghcool/SerialPortToolForVs
06b6149f271f13a4c683d247e3bda1902c65d63c
[ "MIT" ]
null
null
null
SerialPortTool/MainWindow.cpp
mghcool/SerialPortToolForVs
06b6149f271f13a4c683d247e3bda1902c65d63c
[ "MIT" ]
null
null
null
SerialPortTool/MainWindow.cpp
mghcool/SerialPortToolForVs
06b6149f271f13a4c683d247e3bda1902c65d63c
[ "MIT" ]
null
null
null
#include "MainWindow.h" #include "CrcCheck.h" #include <QSerialPort> #include <QSerialPortInfo> #include <QStandardPaths> #include <QMessageBox> #include <QSettings> #include <QFileInfo> #include <QDebug> #include <QTimer> #include <QDir> #include <QDomDocument> #include <QDateTime> #include <QStandardItemModel> #include "VersionUpdate.h" QSerialPort serial; //串口对象 QList<QSerialPortInfo> portList;//串口列表 QLabel* lblStatus; //状态栏状态标签 QLabel* lblRxByte; //状态栏接收字节标签 QLabel* lblTxByte; //状态栏发送字节标签 CrcCheck crcObj; QSettings* qSettings; SettingInfo settingInfo; QFile apacheFile; QDomDocument apacheDoc; QDomElement apacheDocRoot; int RxdCount; // 接收字节计数 int TxdCount; // 发送字节计数 // 重载窗口关闭事件 void MainWindow::closeEvent(QCloseEvent* e) { } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); // 设置窗口标题版本 this->setWindowTitle(this->windowTitle() + " v" + VersionUpdate::GetVersion()); // 获取标准用户配置文件夹 QDir configDir(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)); // 读取配置 QString settingPath = configDir.absoluteFilePath(SETTING_FILENAME); // 配置文件全路径 QFileInfo info(settingPath); qSettings = new QSettings(settingPath, QSettings::IniFormat); // 载入配置文件 qSettings->setIniCodec("UTF-8"); // 设置配置文件编码 if (info.exists()) { // 如果配置文件存在,就读取配置文件 // 串口设置 settingInfo.BaudRateIndex = qSettings->value("SerialPort/BaudRate").toInt(); settingInfo.DataBitsIndex = qSettings->value("SerialPort/DataBits").toInt(); settingInfo.ParityIndex = qSettings->value("SerialPort/Parity").toInt(); settingInfo.StopBitsIndex = qSettings->value("SerialPort/StopBits").toInt(); settingInfo.FlowControlIndex = qSettings->value("SerialPort/FlowControl").toInt(); // 接收设置 settingInfo.RxHex = qSettings->value("RxdSetting/Hex").toBool(); settingInfo.RxWordWrap = qSettings->value("RxdSetting/WordWrap").toBool(); settingInfo.RxShowTime = qSettings->value("RxdSetting/ShowTime").toBool(); // 发送设置 settingInfo.TxHex = qSettings->value("TxdSetting/Hex").toBool(); settingInfo.ShowTx = qSettings->value("RxdSetting/ShowTx").toBool(); settingInfo.TxCrc = qSettings->value("TxdSetting/Crc").toBool(); settingInfo.TxCrcModel = qSettings->value("TxdSetting/CrcModel").toInt(); } else// 如果配置文件不存在,就初始化配置文件 { // 串口设置 qSettings->beginGroup("SerialPort"); qSettings->setValue("BaudRate", 3); // 波特率 qSettings->setValue("DataBits", 3); // 数据位 qSettings->setValue("Parity", 0); // 校验位 qSettings->setValue("StopBits", 0); // 停止位 qSettings->setValue("FlowControl", 0); // 流控 qSettings->endGroup(); // 接收设置 qSettings->beginGroup("RxdSetting"); qSettings->setValue("Hex", false); // 是否16进制 qSettings->setValue("WordWrap", false); // 自动换行 qSettings->setValue("ShowTime", false); // 显示时间 qSettings->endGroup(); // 发送设置 qSettings->beginGroup("TxdSetting"); qSettings->setValue("Hex", false); // 是否16进制 qSettings->setValue("ShowTx", false); // 显示发送 qSettings->setValue("Crc", false); // 启用CRC校验 qSettings->setValue("CrcModel", 0); // CRC计算模型 qSettings->endGroup(); // 发送历史 qSettings->beginGroup("History"); qSettings->setValue("Line0", ""); qSettings->setValue("Line1", ""); qSettings->setValue("Line2", ""); qSettings->setValue("Line4", ""); qSettings->setValue("Line5", ""); qSettings->setValue("Line6", ""); qSettings->setValue("Line7", ""); qSettings->setValue("Line8", ""); qSettings->setValue("Line9", ""); qSettings->endGroup(); // 设置配置变量 settingInfo = { 3,3 }; } //创建状态标签 lblStatus = new QLabel(); ui.statusbar->addWidget(lblStatus); lblStatus->setMinimumWidth(500); lblStatus->setMaximumWidth(500); lblStatus->setStyleSheet("color:red;"); lblStatus->setText(" 未打开串口"); //创建接收和发送字节数标签 lblRxByte = new QLabel(); ui.statusbar->addWidget(lblRxByte); lblRxByte->setMinimumWidth(100); lblRxByte->setText("Rx: 0 Bytes"); lblTxByte = new QLabel(); ui.statusbar->addWidget(lblTxByte); lblTxByte->setMinimumWidth(100); lblTxByte->setText("Tx: 0 Bytes"); //添加crc选项 for (int i = 0; i < crcObj.modelListSize; i++) { ui.cmbCRCType->addItem(crcObj.modelList[i].name); } //设置默认选项 ui.comBaudRate->setCurrentIndex(settingInfo.BaudRateIndex); // 波特率 ui.comDataBits->setCurrentIndex(settingInfo.DataBitsIndex); // 数据位 ui.comParity->setCurrentIndex(settingInfo.ParityIndex); // 校验位 ui.comStopBits->setCurrentIndex(settingInfo.StopBitsIndex); // 停止位 ui.comFlowControl->setCurrentIndex(settingInfo.FlowControlIndex); // 流控 ui.radioRxHex->setChecked(settingInfo.RxHex); // 是否16进制 ui.cbxWordWrap->setChecked(settingInfo.RxWordWrap); // 自动换行 ui.cbxShowTime->setChecked(settingInfo.RxShowTime); // 显示时间 ui.radioTxHex->setChecked(settingInfo.TxHex); // 是否16进制 ui.cbxShowSend->setChecked(settingInfo.ShowTx); // 显示发送 ui.cbxCRC->setChecked(settingInfo.TxCrc); // 启用CRC校验 ui.cmbCRCType->setCurrentIndex(settingInfo.TxCrcModel); // CRC计算模型 ui.spinBoxRepeat->setValue(1000); // 重复发送间隔 ui.cbxCRC->setEnabled(settingInfo.TxHex); // 是否启用CRC //更新串口列表 UpdatePortList(); // 读取缓存 apacheFile.setFileName(configDir.absoluteFilePath("cache.xml")); if (apacheFile.exists()) { apacheFile.open(QFile::ReadOnly); apacheDoc.setContent(&apacheFile); apacheFile.close(); apacheDocRoot = apacheDoc.documentElement(); QDomNode historyNode = apacheDocRoot.lastChild(); //获得第最后一个子节点History if (!historyNode.isNull()) { QDomNodeList list = historyNode.childNodes(); for (int i = 0; i < list.count(); i++) { QString val = list.at(i).attributes().item(0).nodeValue(); ui.cmbSendHistory->insertItem(i, val); } } } else { apacheFile.open(QFile::WriteOnly | QFile::Truncate); // 创建xml头部格式 QDomProcessingInstruction instruction; instruction = apacheDoc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""); apacheDoc.appendChild(instruction); // 创建root节点 apacheDocRoot = apacheDoc.createElement("root"); apacheDocRoot.appendChild(apacheDoc.createElement("CMD")); apacheDocRoot.appendChild(apacheDoc.createElement("History")); apacheDoc.appendChild(apacheDocRoot); // 保存文件 QTextStream stream(&apacheFile); apacheDoc.save(stream, 4); //4 缩进字符 apacheFile.close(); } //定义串口更新定时器 timerUpdatePort = new QTimer(this); timerUpdatePort->start(PORT_UPDATE_INTERVAL); //连接信号槽 connect(&serial, SIGNAL(readyRead()), this, SLOT(slot_PortReceive())); connect(timerUpdatePort, SIGNAL(timeout()), this, SLOT(slot_UpdatePort())); // 重复发送定时器 timerRepeat = new QTimer(this); connect(timerRepeat, SIGNAL(timeout()), this, SLOT(slot_timerRepeat())); } //窗体析构 MainWindow::~MainWindow() { // 保存串口设置 qSettings->setValue("SerialPort/BaudRate", ui.comBaudRate->currentIndex()); // 波特率 qSettings->setValue("SerialPort/DataBits", ui.comDataBits->currentIndex()); // 数据位 qSettings->setValue("SerialPort/Parity", ui.comParity->currentIndex()); // 校验位 qSettings->setValue("SerialPort/StopBits", ui.comStopBits->currentIndex()); // 停止位 qSettings->setValue("SerialPort/FlowControl", ui.comFlowControl->currentIndex()); // 流控 // 保存接受设置 qSettings->setValue("RxdSetting/Hex", ui.radioRxHex->isChecked()); // 是否16进制 qSettings->setValue("RxdSetting/WordWrap", ui.cbxWordWrap->isChecked()); // 自动换行 qSettings->setValue("RxdSetting/ShowTime", ui.cbxShowTime->isChecked()); // 显示时间 // 保存发送设置 qSettings->setValue("TxdSetting/Hex", ui.radioTxHex->isChecked()); // 是否16进制 qSettings->setValue("RxdSetting/ShowTx", ui.cbxShowSend->isChecked()); // 显示发送 qSettings->setValue("TxdSetting/Crc", ui.cbxCRC->isChecked()); // 启用CRC校验 qSettings->setValue("TxdSetting/CrcModel", ui.cmbCRCType->currentIndex()); // CRC计算模型 // 释放资源 serial.close(); timerUpdatePort->stop(); delete lblStatus; delete lblRxByte; delete lblTxByte; delete timerUpdatePort; delete qSettings; // 保存缓存文件 apacheFile.open(QFile::WriteOnly | QFile::Truncate); QTextStream stream(&apacheFile); apacheDoc.save(stream, 4); //4 缩进字符 apacheFile.close(); } //更新串口列表 void MainWindow::UpdatePortList() { QList<QSerialPortInfo> newList = QSerialPortInfo::availablePorts(); if (portList.size() != newList.size()) { portList = newList; ui.cmbSerialPort->clear(); QStandardItemModel* model = new QStandardItemModel(); QStandardItem* item = new QStandardItem();//设置下拉框选择提示 foreach(const QSerialPortInfo & info, portList) { QString portInfo = info.portName() + " " + info.description(); item = new QStandardItem(portInfo); // 下拉框显示文本 item->setToolTip(portInfo); // 设置提示类容 model->appendRow(item); // 将item添加到model中 } ui.cmbSerialPort->setModel(model); // 下拉框设置model } } //串口更新定时器触发 void MainWindow::slot_UpdatePort() { UpdatePortList(); } //打开串口 void MainWindow::on_start_triggered(bool checked) { ui.start->setChecked(true); ui.pause->setChecked(false); ui.stop->setChecked(false); if (portList.isEmpty()) { ui.start->setChecked(false); ui.pause->setChecked(false); ui.stop->setChecked(true); QMessageBox::warning(this, "错误", "没有相应的串口!", QMessageBox::Ok); return; } if (checked) { //设置串口名 serial.setPortName(portList[ui.cmbSerialPort->currentIndex()].portName()); //设置波特率 serial.setBaudRate(ui.comBaudRate->currentText().toInt()); //设置数据位数 serial.setDataBits((QSerialPort::DataBits)ui.comDataBits->currentText().toInt()); //设置奇偶校验 switch (ui.comParity->currentIndex()) { case 0: serial.setParity(QSerialPort::NoParity); break; case 1: serial.setParity(QSerialPort::EvenParity); break; case 2: serial.setParity(QSerialPort::OddParity); break; case 3: serial.setParity(QSerialPort::SpaceParity); break; case 4: serial.setParity(QSerialPort::MarkParity); break; } //设置停止位 switch (ui.comStopBits->currentIndex()) { case 0: serial.setStopBits(QSerialPort::OneStop); break; case 1: serial.setStopBits(QSerialPort::OneAndHalfStop); break; case 2: serial.setStopBits(QSerialPort::TwoStop); break; } //设置流控制 switch (ui.comFlowControl->currentIndex()) { case 0: serial.setFlowControl(QSerialPort::NoFlowControl); break; case 1: serial.setFlowControl(QSerialPort::HardwareControl); break; case 2: serial.setFlowControl(QSerialPort::SoftwareControl); break; } //打开串口 if (serial.open(QIODevice::ReadWrite)) { QString text = " 串口打开: " + ui.cmbSerialPort->currentText() + " " + ui.comBaudRate->currentText(); lblStatus->setStyleSheet("color:green;"); lblStatus->setText(text); } else { switch (serial.error()) { case QSerialPort::PermissionError: QMessageBox::warning(this, "错误", "串口被占用!", QMessageBox::Ok); break; case QSerialPort::OpenError: QMessageBox::warning(this, "错误", "无法打开串口", QMessageBox::Ok); break; default: QMessageBox::warning(this, "错误", "打开串口错误!", QMessageBox::Ok); } serial.clearError(); ui.start->setChecked(false); ui.pause->setChecked(false); ui.stop->setChecked(true); } } } //暂停串口 void MainWindow::on_pause_triggered(bool checked) { ui.start->setChecked(false); ui.pause->setChecked(true); ui.stop->setChecked(false); if (checked) { qDebug() << "pause"; } } //停止串口 void MainWindow::on_stop_triggered(bool checked) { ui.start->setChecked(false); ui.pause->setChecked(false); ui.stop->setChecked(true); if (checked) { serial.close(); lblStatus->setStyleSheet("color:red;"); lblStatus->setText(tr(" 未打开串口")); } } //添加一条历史记录 void MainWindow::AddHistory(QString text) { if (ui.cmbSendHistory->itemText(0) != text) { ui.cmbSendHistory->insertItem(0, text); ui.cmbSendHistory->setCurrentIndex(0); int historyCount = ui.cmbSendHistory->count(); QDomNode historyNode = apacheDocRoot.lastChild(); //获得第最后一个子节点History QDomElement val = apacheDoc.createElement("text"); val.setAttribute("val", text); QDomNode first = historyNode.firstChild(); historyNode.insertBefore(val, first); } } // 选中历史记录 void MainWindow::on_cmbSendHistory_activated(const QString& arg1) { ui.textEditTx->setText(arg1); } // 发送数据 void MainWindow::SendDatas(QString text) { // 换行符转换 text = text.replace("\n", "\r\n"); //转换数据 QByteArray sendData; if (ui.radioTxAscii->isChecked()) sendData = text.toUtf8(); //按Ascii发送 else sendData = QByteArray::fromHex(text.toLatin1().data()); //按Hex发送 //CRC校验 if (ui.cbxCRC->isChecked() && ui.radioTxHex->isChecked()) { quint32 crcVal = crcObj.computeCrcVal(sendData, ui.cmbCRCType->currentIndex()); sendData.append(crcVal & 0x00FF); sendData.append(crcVal >> 8); } // 显示发送 if (ui.cbxShowSend->isChecked()) { if (ui.cbxShowTime->isChecked()) { QDateTime nowDataTime = QDateTime::currentDateTime(); QString timeStr = nowDataTime.toString("[hh:mm:ss.zzz] "); ui.textShowRx->append(timeStr + text); } else { ui.textShowRx->append(text); } } // 写入发送缓存区 qDebug() << sendData; serial.write(sendData); TxdCount += sendData.count(); lblTxByte->setText("Tx: " + QString::number(TxdCount) + " Bytes"); //添加到历史发送 this->AddHistory(text); } //发送一条信息 void MainWindow::on_btnSend_clicked() { //如果串口没有打开,那就打开串口 if (!ui.start->isChecked()) { on_start_triggered(true); return; } //获取输入窗口sendData的数据 QString inputText = ui.textEditTx->toPlainText(); SendDatas(inputText); } //读取接收到的数据 void MainWindow::slot_PortReceive() { if (ui.pause->isChecked()) return; //暂停时不处理接收 QByteArray buf; buf = serial.readAll(); if (!buf.isEmpty()) { QString str = QString::fromLocal8Bit(buf); //支持中文 if (ui.radioRxHex->isChecked()) str = buf.toHex(' ').toUpper(); //转16进制显示,带空格大写 if (ui.cbxWordWrap->isChecked())//换行显示 { if (ui.cbxShowTime->isChecked()) { QDateTime nowDataTime = QDateTime::currentDateTime(); QString timeStr = nowDataTime.toString("[hh:mm:ss.zzz] "); str = timeStr + str; } ui.textShowRx->append(str); } else //不换行显示 { QTextCursor tc = ui.textShowRx->textCursor(); tc.movePosition(QTextCursor::End); tc.insertText(str + " "); } } RxdCount += buf.count(); lblRxByte->setText("Rx: " + QString::number(RxdCount) + " Bytes"); buf.clear(); } //清理接收区 void MainWindow::on_clean_triggered() { ui.textShowRx->clear(); RxdCount = 0; TxdCount = 0; lblTxByte->setText("Tx: 0 Bytes"); lblRxByte->setText("Rx: 0 Bytes"); } // 重复发送复选框 void MainWindow::on_cbxRepeat_clicked(bool state) { if (state) { timerRepeat->start(ui.spinBoxRepeat->value()); } else { timerRepeat->stop(); } } // 重复发送定时器槽 void MainWindow::slot_timerRepeat() { if (ui.start->isChecked()) { qDebug() << "发送"; //获取输入窗口sendData的数据 QString inputText = ui.textEditTx->toPlainText(); SendDatas(inputText); } } void MainWindow::on_radioTxAscii_clicked(bool state) { ui.cbxCRC->setEnabled(!state); } void MainWindow::on_radioTxHex_clicked(bool state) { ui.cbxCRC->setEnabled(state); }
33.236538
105
0.602789
e7d5fe6d99e8f0be14b02a2fecc0be859f659a67
181
cpp
C++
src/test/resources/cpp/function_ptr.cpp
shahrzadav/codyze
c075e8c874f8bef52037d3538166150a488f1607
[ "Apache-2.0" ]
58
2020-04-18T19:26:32.000Z
2022-03-23T20:37:18.000Z
src/test/resources/cpp/function_ptr.cpp
shahrzadav/codyze
c075e8c874f8bef52037d3538166150a488f1607
[ "Apache-2.0" ]
409
2020-04-06T08:29:20.000Z
2022-03-31T17:46:54.000Z
src/test/resources/cpp/function_ptr.cpp
shahrzadav/codyze
c075e8c874f8bef52037d3538166150a488f1607
[ "Apache-2.0" ]
13
2020-05-04T05:36:02.000Z
2022-01-29T09:24:16.000Z
#include <iostream> class A { public: void fun() { std::cout << "Hello" << std::endl; } }; int main() { A a; void (A::* f_ptr) () = &A::fun; (a.*f_ptr)(); }
12.066667
40
0.453039
e7d68cfba12d0c5cc12915b0739af0e174083928
6,140
cpp
C++
PG/physics/PhysicsWorld.cpp
mcdreamer/PG
a047615d9eae7f2229a203a262f239106cf7f39c
[ "MIT" ]
2
2018-01-14T17:47:22.000Z
2021-11-15T10:34:24.000Z
PG/physics/PhysicsWorld.cpp
mcdreamer/PG
a047615d9eae7f2229a203a262f239106cf7f39c
[ "MIT" ]
23
2017-07-31T19:43:00.000Z
2018-11-11T18:51:28.000Z
PG/physics/PhysicsWorld.cpp
mcdreamer/PG
a047615d9eae7f2229a203a262f239106cf7f39c
[ "MIT" ]
null
null
null
#include "PG/physics/PhysicsWorld.h" #include "PG/physics/PhysicsBody.h" #include "PG/app/GameConstants.h" #include "PG/entities/TilePositionCalculator.h" #include "PG/core/RectUtils.h" #include "PG/core/PointUtils.h" #include "PG/core/SizeUtils.h" #include "PG/core/MathsUtils.h" #include <array> namespace PG { namespace { const size_t kNumCoordsToTest = 9; using TileCoordsToTest = std::array<TileCoord, kNumCoordsToTest>; //-------------------------------------------------------- TileCoordsToTest getCollisionTestCoords(const TileCoord& bodyTileCoord) { TileCoordsToTest coordsToTest; for (auto& coordToTest : coordsToTest) { coordToTest = bodyTileCoord; } auto coordToTestIt = coordsToTest.begin(); // Aligned points ++coordToTestIt; coordToTestIt->y -= 1; ++coordToTestIt; coordToTestIt->y += 1; ++coordToTestIt; coordToTestIt->x -= 1; ++coordToTestIt; coordToTestIt->x += 1; // Diagonal points ++coordToTestIt; coordToTestIt->x -= 1; coordToTestIt->y += 1; ++coordToTestIt; coordToTestIt->x += 1; coordToTestIt->y += 1; ++coordToTestIt; coordToTestIt->x -= 1; coordToTestIt->y -= 1; ++coordToTestIt; coordToTestIt->x += 1; coordToTestIt->y -= 1; return coordsToTest; } // Don't allow passing through tiles // Better detection of whether collision is above/below or left/right? //-------------------------------------------------------- void findIntersectionAndResolveForBody(PhysicsBody& body, const Rect& geometryRect) { const Rect desiredRect(body.desiredPosition, body.bounds.size); const auto intersection = RectUtils::getIntersection(desiredRect, geometryRect); if (!RectUtils::isEmpty(intersection)) { Point removeIntersectionPt; Point adjustedVelocity; if (intersection.size.height < intersection.size.width) { const bool collisionBelow = (desiredRect.origin.y <= geometryRect.origin.y); if (collisionBelow) { body.hasHitGround(); } const int dir = collisionBelow ? -1 : 1; removeIntersectionPt = Point(0, dir * intersection.size.height); adjustedVelocity = Point(body.velocity.x, 0); } else { const int dir = (desiredRect.origin.x < geometryRect.origin.x) ? -1 : 1; removeIntersectionPt = Point(dir * intersection.size.width, 0); adjustedVelocity = Point(0, body.velocity.y); } body.velocity = adjustedVelocity; body.desiredPosition = PointUtils::addPoints(body.desiredPosition, removeIntersectionPt); } } //-------------------------------------------------------- void resolveCollisionAtCoord(const TileCoord& coordToTest, const DataGrid<bool>& levelGeometry, PhysicsBody& body) { if (coordToTest.x < 0 || coordToTest.x >= levelGeometry.getWidth() || coordToTest.y < 0 || coordToTest.y >= levelGeometry.getHeight() || !levelGeometry.at(coordToTest.x, coordToTest.y)) { return; } TilePositionCalculator tilePosCalc; const Rect tileRect(tilePosCalc.calculatePoint(coordToTest), Size(GameConstants::tileSize(), GameConstants::tileSize())); findIntersectionAndResolveForBody(body, tileRect); } //-------------------------------------------------------- void applyForcesToBody(PhysicsBody& body, const PhysicsWorldParams& params, float dt) { const auto gravityStep = SizeUtils::scaleSize(params.gravity, dt); const auto forwardStep = PointUtils::scalePoint(params.forward, dt); // Gravity and X friction followed by movement if (!body.isFreeMoving) { body.velocity = PointUtils::addToPoint(body.velocity, gravityStep); body.velocity = Point(body.velocity.x * params.friction, body.velocity.y); if (body.jumpToConsume && body.onGround) { body.velocity = PointUtils::addPoints(body.velocity, params.jumpForce); body.jumpToConsume = false; body.onGround = false; } } else { body.velocity = Point(body.velocity.x * params.friction, body.velocity.y * params.friction); if (body.movingUp) { body.velocity = PointUtils::subtractPoints(body.velocity, PointUtils::swapValues(forwardStep)); } if (body.movingDown) { body.velocity = PointUtils::addPoints(body.velocity, PointUtils::swapValues(forwardStep)); } } // Horizontal movement always the same if (body.movingRight) { body.velocity = PointUtils::addPoints(body.velocity, forwardStep); } if (body.movingLeft) { body.velocity = PointUtils::subtractPoints(body.velocity, forwardStep); } // Clamp velocity auto clampedVelX = MathsUtils::clamp(body.velocity.x, params.minMovement.x, params.maxMovement.x); auto clampedVelY = MathsUtils::clamp(body.velocity.y, params.minMovement.y, params.maxMovement.y); body.velocity = Point(clampedVelX, clampedVelY); // Apply velocity auto velocityStep = PointUtils::scalePoint(body.velocity, dt); body.desiredPosition = PointUtils::addPoints(body.bounds.origin, velocityStep); } } //-------------------------------------------------------- void PhysicsWorld::applyPhysicsForBody(PhysicsBody& body, const DataGrid<bool>& levelGeometry, float dt) const { applyForcesToBody(body, m_Params, dt); TilePositionCalculator tilePosCalc; const auto bodyTileCoord = tilePosCalc.calculateTileCoord(body.desiredPosition); // Collision detection const auto coordsToTest = getCollisionTestCoords(bodyTileCoord); for (size_t i = 0; i < coordsToTest.size(); ++i) { resolveCollisionAtCoord(coordsToTest[i], levelGeometry, body); } // Apply updated desired position body.setPosition(body.desiredPosition); } //-------------------------------------------------------- void PhysicsWorld::findCollisionsWithBody(const PhysicsBody& body, const std::vector<PhysicsBody>& bodiesToCheck, PhysicsWorldCallback& callback) const { for (size_t nthBody = 0; nthBody < bodiesToCheck.size(); ++nthBody) { if (!RectUtils::isEmpty(RectUtils::getIntersection(body.bounds, bodiesToCheck[nthBody].bounds))) { callback.bodiesDidCollide(body, bodiesToCheck[nthBody], (int)nthBody); } } } }
29.238095
123
0.669055
e7d6cb36c09282359e3ab5b7cc06ba1989389fd0
1,269
cxx
C++
src/sqlite/connection.cxx
slurps-mad-rips/apex
8d88e6167e460a74e2c42a4d11d7f8e70adb5102
[ "Apache-2.0" ]
4
2020-12-14T18:07:28.000Z
2021-04-21T18:10:26.000Z
src/sqlite/connection.cxx
slurps-mad-rips/apex
8d88e6167e460a74e2c42a4d11d7f8e70adb5102
[ "Apache-2.0" ]
11
2020-07-21T03:27:10.000Z
2021-03-22T20:24:44.000Z
src/sqlite/connection.cxx
slurps-mad-rips/apex
8d88e6167e460a74e2c42a4d11d7f8e70adb5102
[ "Apache-2.0" ]
3
2020-12-14T17:40:07.000Z
2022-03-18T15:43:10.000Z
#include <apex/sqlite/connection.hpp> #include <apex/sqlite/memory.hpp> #include <apex/sqlite/table.hpp> #include <apex/sqlite/error.hpp> #include <apex/core/memory.hpp> #include <apex/memory/out.hpp> #include <sqlite3.h> namespace apex::sqlite { void default_delete<sqlite3>::operator () (sqlite3* ptr) noexcept { sqlite3_close_v2(ptr); } //connection::connection (::std::filesystem::path const& path) noexcept(false) : // resource_type { } //{ // sqlite3_open_v2(path.c_str(), out_ptr(static_cast<resource_type&>(*this)), SQLITE_OPEN_READONLY, nullptr); // throw ::std::runtime_error("Not yet implemented"); //} void plugin (connection& conn, std::string_view name, std::shared_ptr<table> item) noexcept(false) { auto destructor = [] (void* ptr) noexcept { auto pointer = static_cast<std::shared_ptr<table>*>(ptr); apex::destroy_at(pointer); deallocate(pointer); }; auto db = conn.get(); auto module = item->module(); auto aux = ::new (allocate(sizeof(item))) std::shared_ptr<table>(item); if (not aux) { throw std::system_error(error::not_enough_memory); } auto result = sqlite3_create_module_v2(db, name.data(), module, aux, destructor); if (result) { throw std::system_error(error(result)); } } } /* namespace apex::sqlite */
34.297297
110
0.704492
e7d95f2a857ad6a08d8098f6ce262a5ba9c33277
1,669
cpp
C++
Code/peek_recv.cpp
hewei-nju/TCP-IP-Network-Programming
0685f0cc60e3af49093d3aa5189c7eafda5af017
[ "MIT" ]
null
null
null
Code/peek_recv.cpp
hewei-nju/TCP-IP-Network-Programming
0685f0cc60e3af49093d3aa5189c7eafda5af017
[ "MIT" ]
null
null
null
Code/peek_recv.cpp
hewei-nju/TCP-IP-Network-Programming
0685f0cc60e3af49093d3aa5189c7eafda5af017
[ "MIT" ]
null
null
null
/** @author heweibright@gmail.com * @date 2021/9/3 11:06 * Copyright (c) All rights reserved. */ #include <iostream> #include <unistd.h> #include <cstdlib> #include <cstring> #include <sys/socket.h> #include <arpa/inet.h> const int BUF_SIZE = 1024; void error_handling(const char *msg) { std::cerr << msg << '\n'; std::terminate(); } int main(int argc, char *argv[]) { if (argc != 2) { std::cout << "Usage: " << argv[0] << " <port>\n"; std::terminate(); } int acpt_sock, recv_sock; struct sockaddr_in acpt_addr; if ((acpt_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) error_handling("socket() error"); memset(&acpt_addr, 0, sizeof(acpt_addr)); acpt_addr.sin_family = PF_INET; acpt_addr.sin_addr.s_addr = htonl(INADDR_ANY); acpt_addr.sin_port = htons(atoi(argv[1])); if (bind(acpt_sock, reinterpret_cast<sockaddr *>(&acpt_addr), sizeof(acpt_addr)) == -1) error_handling("bind() error"); if (listen(acpt_sock, 5) == -1) error_handling("listen() error"); if ((recv_sock = accept(acpt_sock, 0, 0)) == -1) error_handling("accept() error"); ssize_t len; char buf[BUF_SIZE]; while ((len = recv(recv_sock, buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT)) != -1 && len == 0); if (len == -1) error_handling("recv() error"); buf[len] = '\0'; std::cout << "Buffering " << len << " bytes: " << buf << '\n'; if ((len = recv(recv_sock, buf, sizeof(buf), 0)) == -1) error_handling("recv() error"); buf[len] = '\0'; std::cout << "Read again: " << buf << '\n'; close(acpt_sock); close(recv_sock); return 0; }
27.816667
97
0.584781
e7dab0aec55c610adbe8dc2f3a51df4ee13a9827
17,150
cpp
C++
test/tf/t_tf_tree.cpp
Robotics-BUT/Robotic-Template-Library
a93b31f5a8f5b12fbbd5fa134a714ea0f82c1578
[ "MIT" ]
8
2020-04-22T09:46:14.000Z
2022-03-17T00:09:38.000Z
test/tf/t_tf_tree.cpp
Robotics-BUT/Robotic-Template-Library
a93b31f5a8f5b12fbbd5fa134a714ea0f82c1578
[ "MIT" ]
1
2020-08-11T07:24:14.000Z
2020-10-05T12:47:05.000Z
test/tf/t_tf_tree.cpp
Robotics-BUT/Robotic-Template-Library
a93b31f5a8f5b12fbbd5fa134a714ea0f82c1578
[ "MIT" ]
null
null
null
// This file is part of the Robotic Template Library (RTL), a C++ // template library for usage in robotic research and applications // under the MIT licence: // // Copyright 2020 Brno University of Technology // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, 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. // // Contact person: Ales Jelinek <Ales.Jelinek@ceitec.vutbr.cz> #include <gtest/gtest.h> #include <rtl/Transformation.h> #include <rtl/Test.h> #include <vector> #include <typeinfo> #include <iostream> #include <chrono> #include "tf_test/key_generator.h" #include "tf_test/tf_comparison.h" #include "rtl/io/StdLib.h" TEST(t_tf_tree, key_generator) { rtl::test::Types<TestKeyGenerator, TYPES> keyGenTest(static_cast<size_t>(10)); } ////////////////////////// /// Tests ////////////////////////// template<int N, typename dtype, typename T> struct TestInit { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); tree.clear(); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); } }; TEST(t_tf_tree, init) { [[maybe_unused]]auto keyGenTest = rtl::test::RangeTypesTypes<TestInit, 2, 4, float, double>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestConstructors { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree_copy(origin); ASSERT_EQ(tree_copy.empty(), false); ASSERT_EQ(tree_copy.size(), 1); auto tree_copy_root_address = &tree_copy.root(); ASSERT_TRUE(&tree.root() != tree_copy_root_address); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree_move(rtl::TfTree<T, rtl::RigidTfND<N, dtype>>{origin}); ASSERT_EQ(tree_move.empty(), false); ASSERT_EQ(tree_move.size(), 1); } }; TEST(t_tf_tree, constructors) { [[maybe_unused]]auto constructorTests = rtl::test::RangeTypesTypes<TestConstructors, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> void fill_tree_insert(rtl::TfTree<T, rtl::RigidTfND<N, dtype>>& tree, std::vector<T> keys) { auto generator = rtl::test::Random::uniformCallable<double>(-1.0, 1.0); for (size_t i = 1 ; i < keys.size() ; i++) { auto tf = rtl::RigidTfND<N, dtype>::random(generator); tree.insert(keys.at(i), tf, keys.at(i-1)); auto tf2 = tree.at(keys.at(i)).tf(); bool res = CompareTfsEqual<N, dtype>(tf, tf2); ASSERT_EQ(res, true); } } template<int N, typename dtype, typename T> struct TestInsert { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); } }; TEST(t_tf_tree, insert) { [[maybe_unused]]auto insertTest = rtl::test::RangeTypesTypes<TestInsert, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestClear { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); tree.clear(); // root should stay ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); } }; TEST(t_tf_tree, clear) { [[maybe_unused]]auto clearTest = rtl::test::RangeTypesTypes<TestClear, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestContains { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); for (size_t i = 1 ; i < keys.size() ; i++) { ASSERT_EQ(tree.contains(keys.at(i)), false); } fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); for (const auto& key : keys) { ASSERT_EQ(tree.contains(key), true); } } }; TEST(t_tf_tree, contains) { [[maybe_unused]]auto containsTest = rtl::test::RangeTypesTypes<TestContains, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestErase { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); for (typename std::vector<T>::iterator it = keys.end() - 1; it > keys.begin(); it--) { tree.erase(*it); } ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); { size_t i = 0; for (typename std::vector<T>::iterator it = keys.end() - 1; it > keys.begin(); it--) { ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size() - i); tree.erase(*it); for (typename std::vector<T>::iterator it2 = (keys.end() - 1); it2 > keys.begin(); it2--) { if (it2 >= it){ ASSERT_EQ(tree.contains(*it2), false); } else { ASSERT_EQ(tree.contains(*it2), true); } } i++; } } } }; TEST(t_tf_tree, erase) { [[maybe_unused]]auto eraseTest = rtl::test::RangeTypesTypes<TestErase, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestErase2 { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); tree.erase(keys.at(1)); for (size_t i = 0 ; i < keys.size() ; i++) { if (i > 0) { ASSERT_EQ(tree.contains(keys.at(i)), false); } else { ASSERT_EQ(tree.contains(keys.at(i)), true); } } } }; TEST(t_tf_tree, erase_2) { [[maybe_unused]]auto erase2Test = rtl::test::RangeTypesTypes<TestErase2, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct RootTest { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); ASSERT_EQ(tree.root().key(), origin); ASSERT_EQ(tree.root().children().size(), 0); ASSERT_EQ(tree.root().depth(), 0); ASSERT_EQ(tree.root().key() , tree.root().parent()->key()); } }; TEST(t_tf_tree, root) { [[maybe_unused]]auto rootTest = rtl::test::RangeTypesTypes<RootTest, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct AtTest { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); for (const auto& key : keys) { ASSERT_EQ(tree.at(key).key(), key); ASSERT_EQ(tree[key].key(), key); ASSERT_EQ( &tree[key], &tree.at(key)); } } }; TEST(t_tf_tree, at) { [[maybe_unused]]auto atTest = rtl::test::RangeTypesTypes<AtTest, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TreeStructureTest { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); fill_tree_insert(tree, keys); for (size_t i = 0 ; i < keys.size() ; i++) { auto& node1 = tree.at(keys.at(i)); auto& node2 = tree[keys.at(i)]; ASSERT_EQ( &node1, &node2); ASSERT_EQ( node1.depth(), i); if(i > 0) { const auto& parent = tree[keys.at(i-1)]; auto node_parent = node1.parent(); ASSERT_EQ( node_parent, &parent); } } } }; TEST(t_tf_tree, tree_structure) { [[maybe_unused]]auto treeStructureTest = rtl::test::RangeTypesTypes<TreeStructureTest, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestTfFromTo { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); auto generator = rtl::test::Random::uniformCallable<double>(-1.0, 1.0); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); auto tf1 = rtl::RigidTfND<N, dtype>::random(generator); auto tf2 = rtl::RigidTfND<N, dtype>::random(generator); auto tf3 = rtl::RigidTfND<N, dtype>::random(generator); auto tf4 = rtl::RigidTfND<N, dtype>::random(generator); auto tf5 = rtl::RigidTfND<N, dtype>::random(generator); auto tf6 = rtl::RigidTfND<N, dtype>::random(generator); auto tf7 = rtl::RigidTfND<N, dtype>::random(generator); auto tf8 = rtl::RigidTfND<N, dtype>::random(generator); auto tf9 = rtl::RigidTfND<N, dtype>::random(generator); /* * * / tf2 - tf5 - tf9 * / \ tf6 * origin * \ * \ tf1 - tf3 - tf7 * \ \ tf8 * \ tf4 */ tree.insert(key_1, tf1, origin); tree.insert(key_2, tf2, origin); tree.insert(key_3, tf3, key_1); tree.insert(key_4, tf4, key_1); tree.insert(key_5, tf5, key_2); tree.insert(key_6, tf6, key_2); tree.insert(key_7, tf7, key_3); tree.insert(key_8, tf8, key_3); tree.insert(key_9, tf9, key_5); auto identity = rtl::RigidTfND<N, dtype>::identity(); auto tfChain = tree.tf(key_8, key_9); std::cout << tf1 << std::endl; auto cumulated = tfChain(identity); auto cumulated2 = tf9(tf5(tf2(tf1.inverted()(tf3.inverted()(tf8.inverted()))))); ASSERT_EQ(CompareTfsEqual(cumulated, cumulated2), true); } }; TEST(t_tf_tree, tree_tf_from_to) { [[maybe_unused]]auto tfFromToTest = rtl::test::RangeTypesTypes<TestTfFromTo, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct APITest { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree_copy(tree); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree_move(rtl::TfTree<T, rtl::RigidTfND<N, dtype>>{origin}); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); ASSERT_EQ(tree_copy.empty(), false); ASSERT_EQ(tree_copy.size(), 1); ASSERT_EQ(tree_move.empty(), false); ASSERT_EQ(tree_move.size(), 1); tree_copy.clear(); tree_move.clear(); ASSERT_EQ(tree_copy.empty(), false); ASSERT_EQ(tree_copy.size(), 1); ASSERT_EQ(tree_move.empty(), false); ASSERT_EQ(tree_move.size(), 1); tree_copy = tree; tree_move = rtl::TfTree<T, rtl::RigidTfND<N, dtype>>(origin); ASSERT_EQ(tree.contains(key_1), false); tree.insert(key_1, rtl::RigidTfND<N, dtype>::identity(), origin); ASSERT_EQ(tree.contains(key_1), true); tree.erase(key_1); ASSERT_EQ(tree.contains(key_1), false); ASSERT_EQ(tree.root().key(), origin); auto new_tf = rtl::RigidTfND<N, dtype>::identity(); tree[origin].tf() = new_tf; tree.at(origin).tf() = new_tf; auto rootNode_1 = tree[origin]; auto rootNode_2 = tree[origin]; auto rootNode_3 = tree.at(origin); auto rootNode_4 = tree.at(origin); tree.clear(); ASSERT_EQ(tree.root().key(), origin); } }; TEST(t_tf_tree, api_test) { [[maybe_unused]]auto apiTest = rtl::test::RangeTypesTypes<APITest, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename K> struct GeneralTFTest { static void testFunction() { auto keyGen = KeysGenerator<K>{keyN}; auto keys = keyGen.generateKyes(); auto generator = rtl::test::Random::uniformCallable<double>(-1.0, 1.0); using General3DTf = rtl::GeneralTf<rtl::RigidTfND<3,double>, rtl::TranslationND<3, double>, rtl::RotationND<3, double>>; rtl::TfTree<std::string, General3DTf> generalTree{origin}; auto rigid = rtl::RigidTfND<3, double>::random(generator); auto rot = rtl::RotationND<3, double>::random(generator); auto trans = rtl::TranslationND<3, double>::random(generator); /* origin / \ trans rot / \ 1 2 / rigidTf / 3 */ generalTree.insert(key_1, trans, origin); generalTree.insert(key_2, rot, origin); generalTree.insert(key_3, rigid, key_1); auto chain_3_2 = generalTree.tf(key_3, key_2); auto tf_3_2 = rot(trans.inverted()(rigid.inverted())); ASSERT_EQ(CompareTfsEqual((rtl::RigidTfND<3, double>) chain_3_2.squash(), tf_3_2 ), true); } }; TEST(t_tf_tree, generalTfTest) { [[maybe_unused]]auto generalTfTests = rtl::test::RangeTypesTypes<GeneralTFTest, RANGE_AND_DTYPES>::with<std::string>{}; } TEST(t_tf_tree, str_cmp_vs_stc_hash) { auto keyGen = KeysGenerator<std::string>{2}; auto keys = keyGen.generateKyes(); auto a = origin; auto b = key_1; auto t1 = std::chrono::high_resolution_clock::now(); for(size_t i = 0 ; i < 10000000 ; i++) { if( a == b ) {} } auto t2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(); std::cout << "Str cmp duration: " << duration << " ms" << std::endl; auto hasher = std::hash<std::string>{}; t1 = std::chrono::high_resolution_clock::now(); for(size_t i = 0 ; i < 10000000 ; i++) { auto ha = hasher(a); auto hb = hasher(b); if( ha == hb ) {} } t2 = std::chrono::high_resolution_clock::now(); duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(); std::cout << "Str hash and int cmp duration: " << duration << " ms" << std::endl;; } int main(int argc, char **argv){ testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
31.181818
128
0.593703
e7dc104fac5aba661f0f9a7f0b3db94052f413c2
10,700
hxx
C++
main/sc/source/filter/inc/xelink.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sc/source/filter/inc/xelink.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sc/source/filter/inc/xelink.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef SC_XELINK_HXX #define SC_XELINK_HXX #include "markdata.hxx" #include "xllink.hxx" #include "xerecord.hxx" #include "xehelper.hxx" #include "xeformula.hxx" #include "externalrefmgr.hxx" class ScRange; struct ScSingleRefData; struct ScComplexRefData; /* ============================================================================ Classes for export of different kinds of internal/external references. - 3D cell and cell range links - External cell and cell range links - External defined names - Macro calls - Add-in functions - DDE links - OLE object links ============================================================================ */ // Excel sheet indexes ======================================================== /** Stores the correct Excel sheet index for each Calc sheet. @descr The class knows all sheets which will not exported (i.e. external link sheets, scenario sheets). */ class XclExpTabInfo : protected XclExpRoot { public: /** Initializes the complete buffer from the current exported document. */ explicit XclExpTabInfo( const XclExpRoot& rRoot ); /** Returns true, if the specified Calc sheet will be exported. */ bool IsExportTab( SCTAB nScTab ) const; /** Returns true, if the specified Calc sheet is used to store external cell contents. */ bool IsExternalTab( SCTAB nScTab ) const; /** Returns true, if the specified Calc sheet is visible and will be exported. */ bool IsVisibleTab( SCTAB nScTab ) const; /** Returns true, if the specified Calc sheet is selected and will be exported. */ bool IsSelectedTab( SCTAB nScTab ) const; /** Returns true, if the specified Calc sheet is the displayed (active) sheet. */ bool IsDisplayedTab( SCTAB nScTab ) const; /** Returns true, if the specified Calc sheet is displayed in right-to-left mode. */ bool IsMirroredTab( SCTAB nScTab ) const; /** Returns the Calc name of the specified sheet. */ const String& GetScTabName( SCTAB nScTab ) const; /** Returns the Excel sheet index for a given Calc sheet. */ sal_uInt16 GetXclTab( SCTAB nScTab ) const; /** Returns the Calc sheet index of the nSortedTab-th entry in the sorted sheet names list. */ SCTAB GetRealScTab( SCTAB nSortedScTab ) const; //UNUSED2009-05 /** Returns the index of the passed Calc sheet in the sorted sheet names list. */ //UNUSED2009-05 SCTAB GetSortedScTab( SCTAB nScTab ) const; /** Returns the number of Calc sheets. */ inline SCTAB GetScTabCount() const { return mnScCnt; } /** Returns the number of Excel sheets to be exported. */ inline sal_uInt16 GetXclTabCount() const { return mnXclCnt; } /** Returns the number of external linked sheets. */ inline sal_uInt16 GetXclExtTabCount() const { return mnXclExtCnt; } /** Returns the number of exported selected sheets. */ inline sal_uInt16 GetXclSelectedCount() const { return mnXclSelCnt; } /** Returns the Excel index of the active, displayed sheet. */ inline sal_uInt16 GetDisplayedXclTab() const { return mnDisplXclTab; } /** Returns the Excel index of the first visible sheet. */ inline sal_uInt16 GetFirstVisXclTab() const { return mnFirstVisXclTab; } private: /** Returns true, if any of the passed flags is set for the specified Calc sheet. */ bool GetFlag( SCTAB nScTab, sal_uInt8 nFlags ) const; /** Sets or clears (depending on bSet) all passed flags for the specified Calc sheet. */ void SetFlag( SCTAB nScTab, sal_uInt8 nFlags, bool bSet = true ); /** Searches for sheets not to be exported. */ void CalcXclIndexes(); /** Sorts the names of all tables and stores the indexes of the sorted indexes. */ void CalcSortedIndexes(); private: /** Data structure with infoemation about one Calc sheet. */ struct XclExpTabInfoEntry { String maScName; sal_uInt16 mnXclTab; sal_uInt8 mnFlags; inline explicit XclExpTabInfoEntry() : mnXclTab( 0 ), mnFlags( 0 ) {} }; typedef ::std::vector< XclExpTabInfoEntry > XclExpTabInfoVec; typedef ::std::vector< SCTAB > ScTabVec; XclExpTabInfoVec maTabInfoVec; /// Array of Calc sheet index information. SCTAB mnScCnt; /// Count of Calc sheets. sal_uInt16 mnXclCnt; /// Count of Excel sheets to be exported. sal_uInt16 mnXclExtCnt; /// Count of external link sheets. sal_uInt16 mnXclSelCnt; /// Count of selected and exported sheets. sal_uInt16 mnDisplXclTab; /// Displayed (active) sheet. sal_uInt16 mnFirstVisXclTab; /// First visible sheet. ScTabVec maFromSortedVec; /// Sorted Calc sheet index -> real Calc sheet index. ScTabVec maToSortedVec; /// Real Calc sheet index -> sorted Calc sheet index. }; // Export link manager ======================================================== class XclExpLinkManagerImpl; /** Stores all data for internal/external references (the link table). */ class XclExpLinkManager : public XclExpRecordBase, protected XclExpRoot { public: explicit XclExpLinkManager( const XclExpRoot& rRoot ); virtual ~XclExpLinkManager(); /** Searches for an EXTERNSHEET index for the given Calc sheet. @descr See above for the meaning of EXTERNSHEET indexes. @param rnExtSheet (out-param) Returns the EXTERNSHEET index. @param rnXclTab (out-param) Returns the Excel sheet index. @param nScTab The Calc sheet index to process. param pRefLogEntry If not 0, data about the external link is stored here. */ void FindExtSheet( sal_uInt16& rnExtSheet, sal_uInt16& rnXclTab, SCTAB nScTab, XclExpRefLogEntry* pRefLogEntry = 0 ); /** Searches for an EXTERNSHEET index for the given Calc sheet range. @descr See above for the meaning of EXTERNSHEET indexes. @param rnExtSheet (out-param) Returns the EXTERNSHEET index. @param rnFirstXclTab (out-param) Returns the Excel sheet index of the first sheet. @param rnXclTab (out-param) Returns the Excel sheet index of the last sheet. @param nFirstScTab The first Calc sheet index to process. @param nLastScTab The last Calc sheet index to process. param pRefLogEntry If not 0, data about the external link is stored here. */ void FindExtSheet( sal_uInt16& rnExtSheet, sal_uInt16& rnFirstXclTab, sal_uInt16& rnLastXclTab, SCTAB nFirstScTab, SCTAB nLastScTab, XclExpRefLogEntry* pRefLogEntry = 0 ); /** Searches for a special EXTERNSHEET index for the own document. */ sal_uInt16 FindExtSheet( sal_Unicode cCode ); void FindExtSheet( sal_uInt16 nFileId, const String& rTabName, sal_uInt16 nXclTabSpan, sal_uInt16& rnExtSheet, sal_uInt16& rnFirstSBTab, sal_uInt16& rnLastSBTab, XclExpRefLogEntry* pRefLogEntry = NULL ); /** Stores the cell with the given address in a CRN record list. */ void StoreCell( const ScSingleRefData& rRef ); /** Stores all cells in the given range in a CRN record list. */ void StoreCellRange( const ScComplexRefData& rRef ); void StoreCell( sal_uInt16 nFileId, const String& rTabName, const ScSingleRefData& rRef ); void StoreCellRange( sal_uInt16 nFileId, const String& rTabName, const ScComplexRefData& rRef ); /** Finds or inserts an EXTERNNAME record for an add-in function name. @param rnExtSheet (out-param) Returns the index of the EXTSHEET structure for the add-in function name. @param rnExtName (out-param) Returns the 1-based EXTERNNAME record index. @return true = add-in function inserted; false = error (i.e. not supported in current BIFF). */ bool InsertAddIn( sal_uInt16& rnExtSheet, sal_uInt16& rnExtName, const String& rName ); /** InsertEuroTool */ bool InsertEuroTool( sal_uInt16& rnExtSheet, sal_uInt16& rnExtName, const String& rName ); /** Finds or inserts an EXTERNNAME record for DDE links. @param rnExtSheet (out-param) Returns the index of the EXTSHEET structure for the DDE link. @param rnExtName (out-param) Returns the 1-based EXTERNNAME record index. @return true = DDE link inserted; false = error (i.e. not supported in current BIFF). */ bool InsertDde( sal_uInt16& rnExtSheet, sal_uInt16& rnExtName, const String& rApplic, const String& rTopic, const String& rItem ); bool InsertExtName( sal_uInt16& rnExtSheet, sal_uInt16& rnExtName, const String& rUrl, const String& rName, const ScExternalRefCache::TokenArrayRef pArray ); /** Writes the entire Link table. */ virtual void Save( XclExpStream& rStrm ); private: typedef ScfRef< XclExpLinkManagerImpl > XclExpLinkMgrImplPtr; XclExpLinkMgrImplPtr mxImpl; }; // ============================================================================ #endif
49.082569
115
0.619159
e7dcb2b460b4edcbb916fd0fbe0f247cf0c112eb
784
cc
C++
bluetooth/newblued/main.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
5
2019-01-19T15:38:48.000Z
2021-10-06T03:59:46.000Z
bluetooth/newblued/main.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
null
null
null
bluetooth/newblued/main.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
1
2019-02-15T23:05:30.000Z
2019-02-15T23:05:30.000Z
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <brillo/flag_helper.h> #include <brillo/syslog_logging.h> #include "bluetooth/common/dbus_daemon.h" #include "bluetooth/newblued/newblue.h" #include "bluetooth/newblued/newblue_daemon.h" int main(int argc, char** argv) { brillo::FlagHelper::Init(argc, argv, "newblued, the Chromium OS Newblue daemon."); brillo::InitLog(brillo::kLogToSyslog | brillo::kLogToStderrIfTty); bluetooth::DBusDaemon daemon(std::make_unique<bluetooth::NewblueDaemon>( std::make_unique<bluetooth::Newblue>( std::make_unique<bluetooth::LibNewblue>()))); return daemon.Run(); }
34.086957
74
0.716837
e7dd038a07f541672ecdbee54894256ccb613089
2,899
cpp
C++
387/387.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
387/387.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
387/387.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
/* A Harshad or Niven number is a number that is divisible by the sum of its digits. 201 is a Harshad number because it is divisible by 3 (the sum of its digits.) When we truncate the last digit from 201, we get 20, which is a Harshad number. When we truncate the last digit from 20, we get 2, which is also a Harshad number. Let's call a Harshad number that, while recursively truncating the last digit, always results in a Harshad number a right truncatable Harshad number. Also: 201/3=67 which is prime. Let's call a Harshad number that, when divided by the sum of its digits, results in a prime a strong Harshad number. Now take the number 2011 which is prime. When we truncate the last digit from it we get 201, a strong Harshad number that is also right truncatable. Let's call such primes strong, right truncatable Harshad primes. You are given that the sum of the strong, right truncatable Harshad primes less than 10000 is 90619. Find the sum of the strong, right truncatable Harshad primes less than 1014. Solution comment: Quite fast, <100 ms. Hard to optimize further. Starting with all single digit numbers, which are Harshads, we can add digits that produces new Harshads. If adding a digit does not give a new Harshad, then it is either because we just hit a boring number, or it could be that we hit a prime. If this prime, without its last digit added happens to be a strong Harshad (and also truncatable by design) then the prime is a strong right truncatable Harshad prime. This problem really put the eulertools to the test, showing overflow issues in pow_mod, which is used in the Miller-Rabbin primality test. I don't think this is solvable without that test btw., as the numbers are way to big to test by trial division. Now there should be no overflow issues left, as handling of it is explicitly done when needed. I really don't agree with the 10% difficulty of this one, clearly much harder than many other problems in the 30-40% range. */ #include <iostream> #include "timing.hpp" #include "primes.hpp" using euler::primes::is_prime; using Int = uint64_t; Int sum = 0; void build_strong_Harshad_prime(Int base, Int base_digit_sum, int depth) { if (depth < 1) return; bool base_is_strong = is_prime(base / base_digit_sum); for (Int digit = 0; digit <= 9; ++digit) { Int x = base * 10 + digit; Int digit_sum = base_digit_sum + digit; if (x % digit_sum != 0) { if ( base_is_strong and is_prime(x)) { sum += x; } continue; } build_strong_Harshad_prime(x, digit_sum, depth - 1); } } int main() { euler::Timer timer {}; constexpr Int digits = 14; for (Int base = 1; base <= 9; ++base) { build_strong_Harshad_prime(base, base, digits - 1); } std::cout << "Answer: " << sum << std::endl; timer.stop(); }
34.511905
79
0.709555
e7df344610a036fa37f3a557b41d52afea50ac7d
2,027
cpp
C++
TAO/tao/Incoming_Message_Queue.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/Incoming_Message_Queue.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/Incoming_Message_Queue.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: Incoming_Message_Queue.cpp 91628 2010-09-07 11:11:12Z johnnyw $ #include "tao/Incoming_Message_Queue.h" #include "tao/Queued_Data.h" #include "tao/debug.h" #include "ace/Log_Msg.h" #include "ace/Malloc_Base.h" #if !defined (__ACE_INLINE__) # include "tao/Incoming_Message_Queue.inl" #endif /* __ACE_INLINE__ */ TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_Incoming_Message_Queue::~TAO_Incoming_Message_Queue (void) { CORBA::ULong const sz = this->size_; // Delete all the nodes left behind for (CORBA::ULong i = 0; i < sz; ++i) { TAO_Queued_Data *qd = this->dequeue_head (); TAO_Queued_Data::release (qd); } } TAO_Queued_Data * TAO_Incoming_Message_Queue::dequeue_head (void) { if (this->size_ == 0) return 0; // Get the node on the head of the queue... TAO_Queued_Data * const head = this->last_added_->next (); // Reset the head node.. this->last_added_->next (head->next ()); // Decrease the size and reset last_added_ if empty if (--this->size_ == 0) this->last_added_ = 0; return head; } TAO_Queued_Data * TAO_Incoming_Message_Queue::dequeue_tail (void) { // This is a bit painful stuff... if (this->size_ == 0) return 0; // Get the node on the head of the queue... TAO_Queued_Data *head = this->last_added_->next (); while (head->next () != this->last_added_) { head = head->next (); } // Put the head in tmp. head->next (this->last_added_->next ()); TAO_Queued_Data *ret_qd = this->last_added_; this->last_added_ = head; // Decrease the size if (--this->size_ == 0) this->last_added_ = 0; return ret_qd; } int TAO_Incoming_Message_Queue::enqueue_tail (TAO_Queued_Data *nd) { if (this->size_ == 0) { this->last_added_ = nd; this->last_added_->next (this->last_added_); } else { nd->next (this->last_added_->next ()); this->last_added_->next (nd); this->last_added_ = nd; } ++this->size_; return 0; } TAO_END_VERSIONED_NAMESPACE_DECL
20.474747
71
0.653182
e7e04f2e48b35efebb79ea7a8852920c557ecd42
1,921
cpp
C++
Game/src/game/Kamikaze.cpp
franticsoftware/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
3
2019-10-04T19:44:44.000Z
2021-07-27T15:59:39.000Z
Game/src/game/Kamikaze.cpp
franticsoftware/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
1
2019-07-20T05:36:31.000Z
2019-07-20T22:22:49.000Z
Game/src/game/Kamikaze.cpp
aminere/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
null
null
null
/* Amine Rehioui Created: November 05th 2011 */ #include "ShootTest.h" #include "Kamikaze.h" namespace shoot { DEFINE_OBJECT(Kamikaze); DEFINE_OBJECT(KamikazeSettings); //! constructor KamikazeSettings::KamikazeSettings() : m_fDuration(1.5f) { } //! serializes the entity to/from a PropertyStream void KamikazeSettings::Serialize(PropertyStream& stream) { super::Serialize(stream); stream.Serialize(PT_Float, "Duration", &m_fDuration); } //! constructor Kamikaze::Kamikaze() : m_vDirection(Vector3::Create(0.0f, -1.0f, 0.0f)) , m_fTimer(1.5f) { } //! called during the initialization of the entity void Kamikaze::Init() { super::Init(); if(Player* pPlayer = Player::Instance()) { Vector3 vPosition = pPlayer->GetPosition() + GetSpawningPoint(); SetAbsolutePosition(vPosition); } if(KamikazeSettings* pSettings = static_cast<KamikazeSettings*>(m_Settings.Get())) { m_fTimer = pSettings->m_fDuration; } } //! called during the update of the entity void Kamikaze::Update() { super::Update(); if(m_HitPoints < 0) { return; } KamikazeSettings* pSettings = static_cast<KamikazeSettings*>(m_Settings.Get()); if(m_fTimer > 0.0f) { Vector3 vPosition = GetTransformationMatrix().GetTranslation(); Vector3 vPlayerMeshPos = Player::Instance()->GetMeshEntity()->GetTransformationMatrix().GetTranslation(); f32 fInterpolator = pSettings->m_fHomingFactor*g_fDeltaTime; fInterpolator = Math::Clamp(fInterpolator, 0.0f, 1.0f); Vector3 vDirectionToPlayer = (vPlayerMeshPos-vPosition).Normalize(); m_vDirection = ((vDirectionToPlayer-m_vDirection)*fInterpolator + m_vDirection).Normalize(); f32 fAngle = Math::ATan2(-m_vDirection.X, -m_vDirection.Y)*Math::RadToDegFactor; SetRotation(Vector3::Create(0.0f, 0.0f, fAngle)); m_fTimer -= g_fDeltaTime; } Translate(m_vDirection*pSettings->m_fSpeed*g_fDeltaTime); } }
22.337209
108
0.71317
e7e43276a194c619ccf2813db3479e093ae732c5
7,324
cpp
C++
msfs2020/GaugeConnect/GaugeConnect.cpp
brion/simpanel
5ac172006889cbbf92e2b7f86bab3f709072ff12
[ "MIT" ]
1
2021-07-21T03:19:55.000Z
2021-07-21T03:19:55.000Z
msfs2020/GaugeConnect/GaugeConnect.cpp
brion/simpanel
5ac172006889cbbf92e2b7f86bab3f709072ff12
[ "MIT" ]
null
null
null
msfs2020/GaugeConnect/GaugeConnect.cpp
brion/simpanel
5ac172006889cbbf92e2b7f86bab3f709072ff12
[ "MIT" ]
1
2021-07-21T03:20:01.000Z
2021-07-21T03:20:01.000Z
// GaugeConnect.cpp #include <MSFS/MSFS.h> #include <MSFS/MSFS_WindowsTypes.h> #include <MSFS/Legacy/gauges.h> #include <SimConnect.h> #include <cstring> #include "GaugeConnect.h" struct Expression { bool valid; double value; char* expression; UINT32 expr_len; Expression(void) : valid(false), expression(0), expr_len(0) { }; ~Expression() { remove(); }; void remove(void) { if (valid && expression) delete[] expression; valid = false; expression = 0; }; }; Expression* exprs = 0; size_t num_exprs = 0; enum GaugeInputCommands { GISetExpr, GIEvaluate, }; enum GaugeOutputResults { GIError, GIOk, GIMore, GIComplete, }; struct GaugeInputStruct { UINT32 sequence; UINT16 command; UINT16 param; char data[248]; }; struct GaugeOutputStruct { UINT32 sequence; UINT16 result; UINT16 count; struct { INT16 index; INT16 valid; FLOAT64 value; } values[20]; }; enum Event : DWORD { GaugeInput, GaugeOutput, }; enum SCData : DWORD { GaugeInputData, GaugeOutputData, }; enum SCRequest : DWORD { GaugeInputReq, GaugeInputCD, GaugeOutputReq, GaugeOutputCD, }; enum SCGroup : DWORD { GaugeConnectGroup, }; HANDLE sim = 0; ID gvar; template<typename T> void sim_recv(T* ev, DWORD data, void* ctx) { fprintf(stderr, "[GaugeConnect] unhandled RECV type %ld\n", ev->dwID); fflush(stderr); } #define RECV(tn) case SIMCONNECT_RECV_ID_##tn: sim_recv(static_cast<SIMCONNECT_RECV_##tn*>(recv), data, ctx); return #define RECV_FUNC(tn) template<> void sim_recv(SIMCONNECT_RECV_##tn* ev, DWORD data, void* ctx) RECV_FUNC(EXCEPTION) { fprintf(stderr, "[GaugeConnect] SimConnect exception %ld\n", ev->dwException); fflush(stderr); } RECV_FUNC(OPEN) { printf("[GaugeConnect] Open (%s)\n", ev->szApplicationName);; } RECV_FUNC(CLIENT_DATA) { switch (ev->dwRequestID) { case GaugeInputReq: { const GaugeInputStruct& inp = *reinterpret_cast<GaugeInputStruct*>(&ev->dwData); GaugeOutputStruct out; out.sequence = inp.sequence; out.result = GIError; switch (inp.command) { case GISetExpr: { if (inp.param >= num_exprs) { size_t nn = (inp.param+256) & ~255; Expression* ne = new Expression[nn]; if(ne) { if (exprs) { std::memcpy(ne, exprs, num_exprs*sizeof(Expression)); std::memset(exprs, 0, num_exprs*sizeof(Expression)); delete[] exprs; } exprs = ne; num_exprs = nn; } } if (exprs && inp.param < num_exprs) { Expression& e = exprs[inp.param]; e.remove(); if ((e.expression = new char[strlen(inp.data)+1])) { strcpy(e.expression, inp.data); e.valid = true; out.result = GIOk; // printf("[GaugeConnect] expression %d registered (%s)\n", int(inp.param), inp.data); // fflush(stdout); } else e.valid = false; } } break; case GIEvaluate: { out.result = GIMore; out.count = 0; for (int i = 0; i < inp.param; i++) { UINT16 index = reinterpret_cast<const UINT16*>(inp.data + inp.param * sizeof(FLOAT64))[i]; FLOAT64 value = reinterpret_cast<const FLOAT64*>(inp.data)[i]; if (index < num_exprs && exprs[index].valid) { auto& v = out.values[out.count++]; char* str = 0; int vi; v.index = index; set_named_variable_value(gvar, value); v.valid = execute_calculator_code(exprs[index].expression, &v.value, (SINT32*)0, (PCSTRINGZ * )0); // printf("[GaugeConnect] eval '%s': returns %g ('%s')\n", exprs[index].expression, v.value, str ? str : "<no string>"); // fflush(stdout); } if (out.count == 20) { SimConnect_SetClientData(sim, GaugeOutputCD, GaugeOutputData, 0, 0, sizeof(GaugeOutputStruct), &out); out.count = 0; } } out.result = GIComplete; } break; } SimConnect_SetClientData(sim, GaugeOutputCD, GaugeOutputData, 0, 0, sizeof(GaugeOutputStruct), &out); break; } } } RECV_FUNC(SYSTEM_STATE) { printf("[GaugeConnect] System state: %g '%s'\n", ev->fFloat, ev->szString); fflush(stdout); } RECV_FUNC(QUIT) { } RECV_FUNC(EVENT_FILENAME) { switch (ev->uEventID) { default: fprintf(stderr, "[GaugeConnect] unhandled event %ld (filename)\n", ev->uEventID); fflush(stderr); break; } } RECV_FUNC(EVENT) { switch (ev->uEventID) { default: fprintf(stderr, "[GaugeConnect] unhandled event %ld\n", ev->uEventID); fflush(stderr); break; } } void CALLBACK sim_recv(SIMCONNECT_RECV* recv, DWORD data, void* ctx) { switch (recv->dwID) { RECV(EVENT_FRAME); RECV(EVENT_FILENAME); RECV(EVENT); RECV(EXCEPTION); RECV(CLIENT_DATA); RECV(SYSTEM_STATE); RECV(SIMOBJECT_DATA); RECV(OPEN); RECV(QUIT); default: fprintf(stderr, "[GaugeConnect] unknown recv? (%ld)\n", recv->dwID); fflush(stderr); break; } } extern "C" MSFS_CALLBACK void module_init(void) { gvar = register_named_variable("GCVAL"); if (SimConnect_Open(&sim, "GaugeConnect Module", 0, 0, 0, 0) != S_OK) { fprintf(stderr, "[GaugeConnect] Unable to open SimConnect.\n"); return; } if (SimConnect_MapClientDataNameToID(sim, "org.uberbox.gauge.input", GaugeInputCD) != S_OK) fprintf(stderr, "[GaugeConnect] MapClientDataNameToID(org.uberbox.gauge.input) failed\n"); if(SimConnect_CreateClientData(sim, GaugeInputCD, sizeof(GaugeInputStruct), 0) != S_OK) fprintf(stderr, "[GaugeConnect] CreateClientData(org.uberbox.gauge.input) failed\n"); if (SimConnect_MapClientDataNameToID(sim, "org.uberbox.gauge.output", GaugeOutputCD) != S_OK) fprintf(stderr, "[GaugeConnect] MapClientDataNameToID(org.uberbox.gauge.output) failed\n"); if(SimConnect_CreateClientData(sim, GaugeOutputCD, sizeof(GaugeOutputStruct), SIMCONNECT_CREATE_CLIENT_DATA_FLAG_READ_ONLY) != S_OK) fprintf(stderr, "[GaugeConnect] CreateClientData(org.uberbox.gauge.output) failed\n"); SimConnect_MapClientEventToSimEvent(sim, GaugeInput, "org.uberbox.gauge.input"); SimConnect_MapClientEventToSimEvent(sim, GaugeOutput, "org.uberbox.gauge.output"); SimConnect_AddToClientDataDefinition(sim, GaugeInputData, 0, SIMCONNECT_CLIENTDATATYPE_INT32); SimConnect_AddToClientDataDefinition(sim, GaugeInputData, 4, SIMCONNECT_CLIENTDATATYPE_INT16); SimConnect_AddToClientDataDefinition(sim, GaugeInputData, 6, SIMCONNECT_CLIENTDATATYPE_INT16); SimConnect_AddToClientDataDefinition(sim, GaugeInputData, 8, 248); SimConnect_AddToClientDataDefinition(sim, GaugeOutputData, 0, SIMCONNECT_CLIENTDATATYPE_INT32); SimConnect_AddToClientDataDefinition(sim, GaugeOutputData, 4, SIMCONNECT_CLIENTDATATYPE_INT16); SimConnect_AddToClientDataDefinition(sim, GaugeOutputData, 6, SIMCONNECT_CLIENTDATATYPE_INT16); SimConnect_AddToClientDataDefinition(sim, GaugeOutputData, 8, sizeof(GaugeOutputStruct)-8); SimConnect_CallDispatch(sim, sim_recv, NULL); SimConnect_RequestClientData(sim, GaugeInputCD, GaugeInputReq, GaugeInputData, SIMCONNECT_CLIENT_DATA_PERIOD_ON_SET, SIMCONNECT_CLIENT_DATA_REQUEST_FLAG_DEFAULT); fflush(stderr); printf("[GaugeConnect] Module started!\n"); } extern "C" MSFS_CALLBACK void module_deinit(void) { printf("[GaugeConnect] Module going away. :-(\n"); if (!sim) return; SimConnect_Close(sim); }
28.061303
164
0.685554
e7e8f43ab3bc37214f81a307791266a6fffe32ef
341
cpp
C++
UB/Scripting/EntTeleportAction.cpp
Mr-1337/CAGE
e99082676e83cc069ebf0859fcb34e5b96712725
[ "MIT" ]
null
null
null
UB/Scripting/EntTeleportAction.cpp
Mr-1337/CAGE
e99082676e83cc069ebf0859fcb34e5b96712725
[ "MIT" ]
null
null
null
UB/Scripting/EntTeleportAction.cpp
Mr-1337/CAGE
e99082676e83cc069ebf0859fcb34e5b96712725
[ "MIT" ]
1
2019-06-16T19:00:31.000Z
2019-06-16T19:00:31.000Z
#include "EntTeleportAction.hpp" namespace ub { EntTeleportAction::EntTeleportAction(World* world, glm::vec2 destination) : ScriptAction(world), m_destination(destination) { } void EntTeleportAction::Initialize() { } void EntTeleportAction::Update(float dt) { m_world->MoveEnt(1, m_destination); m_complete = true; } }
15.5
77
0.727273
e7eae52e56931502dd1699a15e56f123e6279b66
559
cpp
C++
src/tests/kits/app/bmessagequeue/MessageQueueTest.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/tests/kits/app/bmessagequeue/MessageQueueTest.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/tests/kits/app/bmessagequeue/MessageQueueTest.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
#include "../common.h" #include "AddMessageTest1.h" #include "AddMessageTest2.h" #include "ConcurrencyTest1.h" #include "ConcurrencyTest2.h" #include "FindMessageTest1.h" Test *MessageQueueTestSuite() { TestSuite *testSuite = new TestSuite(); testSuite->addTest(AddMessageTest1::suite()); testSuite->addTest(AddMessageTest2::suite()); testSuite->addTest(ConcurrencyTest1::suite()); // testSuite->addTest(ConcurrencyTest2::suite()); // Causes an "Abort" for some reason... testSuite->addTest(FindMessageTest1::suite()); return(testSuite); }
20.703704
89
0.735242
e7ec48c5dc2a6d4ffe8b131612214e9de530f484
420
cpp
C++
Online Judges/URI/1987/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
64
2019-03-17T08:56:28.000Z
2022-01-14T02:31:21.000Z
Online Judges/URI/1987/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
1
2020-12-24T07:16:30.000Z
2021-03-23T20:51:05.000Z
Online Judges/URI/1987/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
19
2019-05-25T10:48:16.000Z
2022-01-07T10:07:46.000Z
#include <iostream> using namespace std; int main() { int qtdNumbers, sum; string number; bool stopped; while(cin >> qtdNumbers >> number) { sum = 0; while(qtdNumbers--) { sum +=(number[qtdNumbers] - '0'); } if(sum % 3 == 0) { cout << sum << " sim\n"; } else { cout << sum << " nao\n"; } } return 0; }
17.5
45
0.430952
e7eddc82f37df2a9dd86f8058ebcf131a0bf6f69
2,142
hpp
C++
kernel/lib/elf.hpp
ethan4984/rock
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
207
2020-05-27T21:57:28.000Z
2022-02-26T15:17:27.000Z
kernel/lib/elf.hpp
ethan4984/crepOS
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
3
2020-07-26T18:14:05.000Z
2020-12-09T05:32:07.000Z
kernel/lib/elf.hpp
ethan4984/rock
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
17
2020-07-05T19:08:48.000Z
2021-10-13T12:30:13.000Z
#ifndef ELF_HPP_ #define ELF_HPP_ #include <mm/vmm.hpp> #include <string.hpp> #include <fs/fd.hpp> namespace elf { constexpr size_t elf_signature = 0x464C457F; constexpr size_t elf64 = 0x2; constexpr size_t ei_class = 0x4; constexpr size_t ei_data = 0x5; constexpr size_t ei_version = 0x6; constexpr size_t ei_osabi = 0x7; constexpr size_t abi_system_v = 0x0; constexpr size_t abi_linux = 0x3; constexpr size_t little_endian = 0x1; constexpr size_t mach_x86_64 = 0x3e; struct aux { uint64_t at_entry; uint64_t at_phdr; uint64_t at_phent; uint64_t at_phnum; }; constexpr size_t at_entry = 10; constexpr size_t at_phdr = 20; constexpr size_t at_phent = 21; constexpr size_t at_phnum = 22; struct elf64_phdr { uint32_t p_type; uint32_t p_flags; uint64_t p_offset; uint64_t p_vaddr; uint64_t p_paddr; uint64_t p_filesz; uint64_t p_memsz; uint64_t p_align; }; constexpr size_t pt_null = 0x0; constexpr size_t pt_load = 0x1; constexpr size_t pt_dynamic = 0x2; constexpr size_t pt_interp = 0x3; constexpr size_t pt_note = 0x4; constexpr size_t pt_shlib = 0x5; constexpr size_t pt_phdr = 0x6; constexpr size_t pt_lts = 0x7; constexpr size_t pt_loos = 0x60000000; constexpr size_t pt_hois = 0x6fffffff; constexpr size_t pt_loproc = 0x70000000; constexpr size_t pt_hiproc = 0x7fffffff; struct elf64_shdr { uint32_t sh_name; uint32_t sh_type; uint64_t sh_flags; uint64_t sh_addr; uint64_t sh_offset; uint64_t sh_size; uint32_t sh_link; uint32_t sh_info; uint64_t sh_addr_align; uint64_t sh_entsize; }; struct file { file(vmm::pmlx_table *page_map, aux *aux_cur, fs::fd &file, uint64_t base, lib::string **ld_path); struct [[gnu::packed]] { uint8_t ident[16]; uint16_t type; uint16_t machine; uint32_t version; uint64_t entry; uint64_t phoff; uint64_t shoff; uint32_t flags; uint16_t hdr_size; uint16_t phdr_size; uint16_t ph_num; uint16_t shdr_size; uint16_t sh_num; uint16_t shstrndx; } hdr; size_t status; }; }; #endif
21.636364
102
0.704949
e7f00603063bc356ee35f2dd4e5a891475b981ee
387
cpp
C++
01_Week_Programming_Basics/FishTank/FishTank.cpp
kostadinmarkov99/SoftUni_Exercises_PB_Jan_2022
70e619d7c19b6676f509f2509fe102ecbc7669bc
[ "MIT" ]
null
null
null
01_Week_Programming_Basics/FishTank/FishTank.cpp
kostadinmarkov99/SoftUni_Exercises_PB_Jan_2022
70e619d7c19b6676f509f2509fe102ecbc7669bc
[ "MIT" ]
null
null
null
01_Week_Programming_Basics/FishTank/FishTank.cpp
kostadinmarkov99/SoftUni_Exercises_PB_Jan_2022
70e619d7c19b6676f509f2509fe102ecbc7669bc
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int length, width, height; double percetage; cin >> length >> width >> height >> percetage; double volumeInSM = length * width * height; double liters = volumeInSM / 1000; double unusedLiters = liters * percetage / 100.0; double usedLiters = liters - unusedLiters; cout << usedLiters << endl; }
19.35
53
0.648579
e7f4315c365569ee6ce9a3393bc227c62b6a2fc9
9,001
cpp
C++
Client/src/UIGuildBankForm.cpp
ruuuubi/corsairs-client
ddbcd293d6ef3f58ff02290c02382cbb7e0939a2
[ "Apache-2.0" ]
1
2021-06-14T09:34:08.000Z
2021-06-14T09:34:08.000Z
Client/src/UIGuildBankForm.cpp
ruuuubi/corsairs-client
ddbcd293d6ef3f58ff02290c02382cbb7e0939a2
[ "Apache-2.0" ]
null
null
null
Client/src/UIGuildBankForm.cpp
ruuuubi/corsairs-client
ddbcd293d6ef3f58ff02290c02382cbb7e0939a2
[ "Apache-2.0" ]
null
null
null
#include "StdAfx.h" #include "UIGuildBankForm.h" #include "uiform.h" #include "uilabel.h" #include "uiformmgr.h" #include "uigoodsgrid.h" #include "NetProtocol.h" #include "uiboxform.h" #include "uiEquipForm.h" #include "UIGoodsGrid.h" #include "uiItemCommand.h" #include "uiform.h" #include "uiBoatForm.h" #include "packetcmd.h" #include "Character.h" #include "GameApp.h" #include "StringLib.h" namespace GUI { //======================================================================= // CGuildBankMgr 's Members //======================================================================= bool CGuildBankMgr::Init() //用户银行信息初始化 { CFormMgr &mgr = CFormMgr::s_Mgr; frmBank = mgr.Find("frmManage");// 查找NPC银行存储表单 if ( !frmBank) { LG("gui", g_oLangRec.GetString(438)); return false; } grdBank = dynamic_cast<CGoodsGrid*>(frmBank->Find("guildBank")); labGuildMoney = dynamic_cast<CLabel*>(frmBank->Find("labGuildMoney")); btnGoldTake = dynamic_cast<CTextButton*>(frmBank->Find("btngoldtake")); btnGoldPut = dynamic_cast<CTextButton*>(frmBank->Find("btngoldput")); grdBank->evtBeforeAccept = CUIInterface::_evtDragToGoodsEvent; grdBank->evtSwapItem = _evtBankToBank; btnGoldPut->evtMouseClick=_OnClickGoldPut; btnGoldTake->evtMouseClick=_OnClickGoldTake; return true; } void CGuildBankMgr::UpdateGuildGold(const char* value){ labGuildMoney->SetCaption(StringSplitNum(value)); } void CGuildBankMgr::_OnClickGoldPut(CGuiData *pSender, int x, int y, DWORD key){ g_stUIBox.ShowNumberBox(_EnterGoldPut, g_stUIBoat.GetHuman()->getGameAttr()->get(ATTR_GD), "Enter Gold", false); } void CGuildBankMgr::_EnterGoldPut(CCompent *pSender, int nMsgType, int x, int y, DWORD dwKey){ if( nMsgType!=CForm::mrYes ) { return; } stNumBox* kItemPriceBox = (stNumBox*)pSender->GetForm()->GetPointer(); if (!kItemPriceBox) return; int value = kItemPriceBox->GetNumber(); if( value<=0 ) { g_pGameApp->MsgBox( g_oLangRec.GetString(451) ); return; } CS_GuildBankGiveGold(value); } void CGuildBankMgr::_OnClickGoldTake(CGuiData *pSender, int x, int y, DWORD key){ g_stUIBox.ShowNumberBox(_EnterGoldTake, 2000000000-(g_stUIBoat.GetHuman()->getGameAttr()->get(ATTR_GD)), "Enter Gold", false); } void CGuildBankMgr::_EnterGoldTake(CCompent *pSender, int nMsgType, int x, int y, DWORD dwKey){ if( nMsgType!=CForm::mrYes ) { return; } stNumBox* kItemPriceBox = (stNumBox*)pSender->GetForm()->GetPointer(); if (!kItemPriceBox) return; int value = kItemPriceBox->GetNumber(); if( value<=0 ) { g_pGameApp->MsgBox( g_oLangRec.GetString(451) ); return; } CS_GuildBankTakeGold(value); } void CGuildBankMgr::_evtOnClose( CForm* pForm, bool& IsClose ) // 关闭用户银行 { CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_CLOSE_BANK, NULL); CFormMgr::s_Mgr.SetEnableHotKey(HOTKEY_BANK, true); // 西门文档修改 } //------------------------------------------------------------------------- void CGuildBankMgr::ShowBank() // 显示物品 { // 保存服务器传来的物品 if (!g_stUIBoat.GetHuman()) // 找人物 return; char szBuf[32]; sprintf(szBuf, "%s%s", g_stUIBoat.GetHuman()->getName(), g_oLangRec.GetString(440));//显示人物名及专用 //labCharName->SetCaption(szBuf);//设置标题名字 frmBank->Show(); // 打开玩家的物品栏 if (!g_stUIEquip.GetItemForm()->GetIsShow()) { int nLeft, nTop; nLeft = frmBank->GetX2(); nTop = frmBank->GetY(); g_stUIEquip.GetItemForm()->SetPos(nLeft, nTop); //物品放置位置 g_stUIEquip.GetItemForm()->Refresh(); //更新物品栏 g_stUIEquip.GetItemForm()->Show(); //保存在物品栏 } CFormMgr::s_Mgr.SetEnableHotKey(HOTKEY_BANK, false); // 西门文档修改 } //------------------------------------------------------------------------- bool CGuildBankMgr::PushToBank(CGoodsGrid& rkDrag, CGoodsGrid& rkSelf, int nGridID, CCommandObj& rkItem) { #define EQUIP_TYPE 0 #define BANK_TYPE 1 // 设置发送拖动物品的服务器信息 m_kNetBank.chSrcType = EQUIP_TYPE; m_kNetBank.sSrcID = rkDrag.GetDragIndex(); //m_kNetBank.sSrcNum = ; 数量在回调函数中设置 m_kNetBank.chTarType = BANK_TYPE; m_kNetBank.sTarID = nGridID; // 判断物品是否是可重叠的物品 CItemCommand* pkItemCmd = dynamic_cast<CItemCommand*>(&rkItem); if (!pkItemCmd) return false; CItemRecord* pkItemRecord = pkItemCmd->GetItemInfo(); if (!pkItemRecord) return false; //if(pkItemRecord->sType == 59 && m_kNetBank.sSrcID == 1) //{ // g_pGameApp->MsgBox("您的精灵正在使用中\n请更换到其它位置才可放入仓库"); // return false; // 第二格的精灵不允许拖入银行 //} // if(pkItemRecord->lID == 2520 || pkItemRecord->lID == 2521) if( pkItemRecord->lID == 2520 || pkItemRecord->lID == 2521 || pkItemRecord->lID == 6341 || pkItemRecord->lID == 6343 || pkItemRecord->lID == 6347 || pkItemRecord->lID == 6359 || pkItemRecord->lID == 6370 || pkItemRecord->lID == 6371 || pkItemRecord->lID == 6373 || pkItemRecord->lID >= 6376 && pkItemRecord->lID <= 6378 || pkItemRecord->lID >= 6383 && pkItemRecord->lID <= 6385 )// modify by ning.yan 20080820 策划绵羊、李恒等提需求,增加一些道具不准存银行 { //g_pGameApp->MsgBox(g_oLangRec.GetString(958)); // "该道具不允许存入银行!请重新选择" g_pGameApp->MsgBox(g_oLangRec.GetString(958)); // "该道具不允许存入银行!请重新选择" return false; } if ( pkItemCmd->GetItemInfo()->GetIsPile() && pkItemCmd->GetTotalNum() > 1 ) { /*存放多个物品*/ m_pkNumberBox = g_stUIBox.ShowNumberBox(_MoveItemsEvent, pkItemCmd->GetTotalNum(), g_oLangRec.GetString(441), false); if (m_pkNumberBox->GetNumber() < pkItemCmd->GetTotalNum()) return false; else return true; } else { /*存放单个物品*/ g_stUIGuildBank.m_kNetBank.sSrcNum = 1; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank)); CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); return true; //char buf[256] = { 0 }; //sprintf(buf, "您确认放入银行\n[%s]?", pkItemCmd->GetName()); //g_stUIBox.ShowSelectBox(_MoveAItemEvent, buf, true); //return true; } } //------------------------------------------------------------------------- bool CGuildBankMgr::PopFromBank(CGoodsGrid& rkDrag, CGoodsGrid& rkSelf, int nGridID, CCommandObj& rkItem) { // 设置发送拖动物品的服务器信息 m_kNetBank.chSrcType = BANK_TYPE ; m_kNetBank.sSrcID = rkDrag.GetDragIndex(); //m_kNetBank.sSrcNum = ; 数量在回掉函数中设置 m_kNetBank.chTarType = EQUIP_TYPE; m_kNetBank.sTarID = nGridID; // 判断物品是否是可重叠的物品 CItemCommand* pkItemCmd = dynamic_cast<CItemCommand*>(&rkItem); if (!pkItemCmd) return false; if ( pkItemCmd->GetItemInfo()->GetIsPile() && pkItemCmd->GetTotalNum() > 1 ) { /*取出多个物品*/ m_pkNumberBox = g_stUIBox.ShowNumberBox( _MoveItemsEvent, pkItemCmd->GetTotalNum(), g_oLangRec.GetString(442), false); if (m_pkNumberBox->GetNumber() < pkItemCmd->GetTotalNum()) return false; else return true; } else { /*存放单个物品*/ g_stUIGuildBank.m_kNetBank.sSrcNum = 1; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank)); CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); return true; //char buf[256] = { 0 }; //sprintf(buf, "您确认取出\n[%s]?", pkItemCmd->GetName()); //g_stUIBox.ShowSelectBox(_MoveAItemEvent, buf, true); //return true; } } //------------------------------------------------------------------------- void CGuildBankMgr::_MoveItemsEvent(CCompent *pSender, int nMsgType, int x, int y, DWORD dwKey) // 多个物品移动 { if(nMsgType != CForm::mrYes) // 玩家是否同意拖动 return; int num = g_stUIGuildBank.m_pkNumberBox->GetNumber();// 拖动物品数 if ( num > 0 ) { g_stUIGuildBank.m_kNetBank.sSrcNum = num; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank)); CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); } } //------------------------------------------------------------------------- void CGuildBankMgr::_MoveAItemEvent(CCompent *pSender, int nMsgType, int x, int y, DWORD dwKey) // 单个道具移动 { if(nMsgType != CForm::mrYes) return; g_stUIGuildBank.m_kNetBank.sSrcNum = 1; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank));//更新银行信息 CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); } //------------------------------------------------------------------------- void CGuildBankMgr::CloseForm() // 关闭道具栏表单 { if (frmBank->GetIsShow()) { frmBank->Close(); g_stUIEquip.GetItemForm()->Close(); } } //------------------------------------------------------------------------- void CGuildBankMgr::_evtBankToBank(CGuiData *pSender,int nFirst, int nSecond, bool& isSwap) // 用于用户银行表单中道具互换 { isSwap = false; if( !g_stUIBoat.GetHuman() ) return; g_stUIGuildBank.m_kNetBank.chSrcType = BANK_TYPE ; g_stUIGuildBank.m_kNetBank.sSrcID = nSecond; g_stUIGuildBank.m_kNetBank.sSrcNum = 0; g_stUIGuildBank.m_kNetBank.chTarType = BANK_TYPE; g_stUIGuildBank.m_kNetBank.sTarID = nFirst; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank)); CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); } } // end of namespace GUI
31.582456
128
0.651039
e7f603ac6f13bee4c23a336e65ebf2c1e5f4ece4
4,597
hpp
C++
ASch/include/ASch_System.hpp
JuhoL/ASch
757c7edacb1aabce5577acc3df0560548975df49
[ "MIT" ]
2
2018-08-20T08:56:11.000Z
2019-07-09T07:27:45.000Z
ASch/include/ASch_System.hpp
JuhoL/ASch
757c7edacb1aabce5577acc3df0560548975df49
[ "MIT" ]
null
null
null
ASch/include/ASch_System.hpp
JuhoL/ASch
757c7edacb1aabce5577acc3df0560548975df49
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------------------------------------------------------- // Copyright (c) 2018 Juho Lepistö // // 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. //----------------------------------------------------------------------------------------------------------------------------- //! @file ASch_System.hpp //! @author Juho Lepistö <juho.lepisto(a)gmail.com> //! @date 20 Aug 2018 //! //! @class System //! @brief Generic system control class for ASch. //! //! This class implements system control functions and handles generic system level events like ticks and system errors. #ifndef ASCH_SYSTEM_HPP_ #define ASCH_SYSTEM_HPP_ //----------------------------------------------------------------------------------------------------------------------------- // 1. Include Dependencies //----------------------------------------------------------------------------------------------------------------------------- #include <Utils_Types.hpp> #include <Hal_System.hpp> //----------------------------------------------------------------------------------------------------------------------------- // 2. Typedefs, Structs, Enums and Constants //----------------------------------------------------------------------------------------------------------------------------- namespace ASch { /// @brief This is a system error enum. enum class SysError { invalidParameters = 0, //!< A function was called with invalid parameters. bufferOverflow, //!< A buffer has overflown. insufficientResources, //!< System resources (e.g. task quota) has ran out. accessNotPermitted, //!< An attempt to access blocked resource has occurred. assertFailure, //!< A debug assert has failed. unknownError //!< An unknown error. Should never occur. }; } //----------------------------------------------------------------------------------------------------------------------------- // 3. Inline Functions //----------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------- // 4. Global Function Prototypes //----------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------- // 5. Class Declaration //----------------------------------------------------------------------------------------------------------------------------- namespace ASch { //! @class System //! @brief Generic system control class for ASch. //! This class implements system control functions and handles generic system level events like ticks and system errors. class System { public: explicit System(void) {}; /// @brief This fuction raises a system error. /// @param error - Error type. static void Error(SysError error); /// @brief This function enables reset on error. static void EnableResetOnSystemError(void); /// @brief This fuction initialises the system, e.f. clocks and other base peripherals. static void Init(void); /// @brief This function runs pre-start configuration functions. static void PreStartConfig(void); private: static bool resetOnError; }; } // namespace ASch #endif // ASCH_SYSTEM_HPP_
45.068627
127
0.474005
e7f60c2f38799f660ad85b4e9de2bbd6da832a41
1,843
cpp
C++
src/Ledger.cpp
LAHumphreys/LedgerJRI
0c015ed328a71d624791bc6fb6c03e65709c7b13
[ "MIT" ]
null
null
null
src/Ledger.cpp
LAHumphreys/LedgerJRI
0c015ed328a71d624791bc6fb6c03e65709c7b13
[ "MIT" ]
null
null
null
src/Ledger.cpp
LAHumphreys/LedgerJRI
0c015ed328a71d624791bc6fb6c03e65709c7b13
[ "MIT" ]
null
null
null
#include <Ledger.h> #include <LedgerSessionData.h> #include <LedgerSession.h> #include <LedgerCommands.h> Ledger::Ledger() { // libLedger one-time setup? } std::unique_ptr<LedgerSession> Ledger::LoadJournal(const std::string& fname) { std::unique_ptr<LedgerSession> sess; WithInstance([&] (Ledger& instance) { sess = std::make_unique<LedgerSession>(instance); instance.SwitchToSession(*sess); const char ** env = const_cast<const char**>(environ); sess->Data().sess.set_flush_on_next_data_file(true); ledger::process_environment(env, "LEDGER_", sess->Data().report); sess->Data().sess.set_flush_on_next_data_file(true); bool initialised = false; try { sess->Data().sess.read_journal(fname); initialised = true; } catch (ledger::error_count& ec) { sess->BadJournal(instance, ec.what()); } catch (const std::runtime_error& err) { sess->BadJournal(instance, err.what()); } if (initialised) { sess->SessionInitialised(instance); } }); return sess; } void Ledger::WithInstance(const std::function<void(Ledger &instance)> &cb) { static Ledger instance; std::unique_lock<std::mutex> lock(instance.globalLock); cb(instance); } void Ledger::SwitchToSession(LedgerSession&sess) { ledger::set_session_context(&sess.Data().sess); ledger::scope_t::default_scope = &sess.Data().report; ledger::scope_t::empty_scope = &sess.Data().emptyScope; } void Ledger::WithSession(LedgerSession &sess, const std::function<void(LedgerCommands &)>& task) { WithInstance([&] (Ledger& instance) { instance.SwitchToSession(sess); LedgerCommands cmdHandler(instance, sess); task(cmdHandler); }); }
29.253968
78
0.637005
e7f614803c22f2011f236925dc43df4b1144dd83
2,294
cc
C++
chrome/credential_provider/extension/extension_main.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/credential_provider/extension/extension_main.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/credential_provider/extension/extension_main.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright (c) 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "windows.h" #include "base/at_exit.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/process/memory.h" #include "base/task/thread_pool/thread_pool_instance.h" #include "base/win/process_startup_helper.h" #include "chrome/credential_provider/eventlog/gcp_eventlog_messages.h" #include "chrome/credential_provider/extension/os_service_manager.h" #include "chrome/credential_provider/extension/service.h" #include "chrome/credential_provider/gaiacp/logging.h" int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, wchar_t* lpCmdLine, int /*nCmdShow*/) { base::AtExitManager exit_manager; base::CommandLine::Init(0, nullptr); base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); // Initialize logging. logging::LoggingSettings settings; settings.logging_dest = logging::LOG_NONE; // See if the log file path was specified on the command line. base::FilePath log_file_path = cmdline->GetSwitchValuePath("log-file"); if (!log_file_path.empty()) { settings.logging_dest = logging::LOG_TO_FILE; settings.log_file_path = log_file_path.value().c_str(); } logging::InitLogging(settings); logging::SetLogItems(true, // Enable process id. true, // Enable thread id. true, // Enable timestamp. false); // Enable tickcount. // Make sure the process exits cleanly on unexpected errors. base::EnableTerminationOnHeapCorruption(); base::EnableTerminationOnOutOfMemory(); base::win::RegisterInvalidParamHandler(); base::win::SetupCRT(*base::CommandLine::ForCurrentProcess()); // Set the event logging source and category for GCPW Extension. logging::SetEventSource("GCPW", GCPW_EXTENSION_CATEGORY, MSG_LOG_MESSAGE); // This initializes and starts ThreadPoolInstance with default params. base::ThreadPoolInstance::CreateAndStartWithDefaultParams("gcpw_extension"); credential_provider::extension::Service::Get()->Run(); return 0; }
37.606557
78
0.71796
e7f789f835be45fa51b41edcbf3a38b3802995b0
3,746
cpp
C++
code/silverlib/game_hooks.cpp
adm244/f4silver
564ecc80991266ae8b3238f553b76d75506f9fbf
[ "Unlicense" ]
6
2018-11-07T19:31:30.000Z
2021-07-29T02:58:33.000Z
code/silverlib/game_hooks.cpp
adm244/f4silver
564ecc80991266ae8b3238f553b76d75506f9fbf
[ "Unlicense" ]
2
2018-06-01T23:27:46.000Z
2018-09-11T23:35:58.000Z
code/silverlib/game_hooks.cpp
adm244/f4silver
564ecc80991266ae8b3238f553b76d75506f9fbf
[ "Unlicense" ]
3
2019-12-29T14:45:55.000Z
2020-05-12T16:34:23.000Z
/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. */ //IMPORTANT(adm244): SCRATCH VERSION JUST TO GET IT UP WORKING #ifndef _SILVERLIB_GAME_HOOKS_CPP_ #define _SILVERLIB_GAME_HOOKS_CPP_ extern "C" void GameLoop() { if( gGameState.IsGameLoaded ) { if (gGameState.IsPlayerDead != IsActorDead((TESActor *)TES_GetPlayer())) { gGameState.IsPlayerDead = !gGameState.IsPlayerDead; if (gGameState.IsPlayerDead) { //TODO(adm244): place into a separate function call? INPUT input = {0}; input.type = INPUT_KEYBOARD; input.ki.wVk = Keys.DeathEvent; input.ki.dwExtraInfo = GetMessageExtraInfo(); SendInput(1, &input, sizeof(INPUT)); } } if (!IsActivationPaused()) { if( gGameState.IsInterior != IsPlayerInInterior() ) { gGameState.IsInterior = !gGameState.IsInterior; if( gGameState.IsInterior ) { ProcessQueue(&gQueues.InteriorPendingQueue, false); } else { ProcessQueue(&gQueues.ExteriorPendingQueue, false); } } ProcessQueue(&gQueues.PrimaryQueue, true); } } } extern "C" void LoadGameBegin(char *filename) { gGameState.IsGameLoaded = false; } extern "C" void LoadGameEnd() { gGameState.IsGameLoaded = true; } extern "C" void HackingPrepare() { //TESConsolePrint("Terminal Hacking Entered"); ExtraDataList *extrasList = (*gActiveTerminalREFR)->extraDataList; assert(extrasList != 0); ExtraLockData *lockData = ExtraDataList_GetExtraLockData(extrasList); assert(lockData != 0); //BSReadWriteLock_Lock(&extrasList->lock); //NOTE(adm244): unused flag, should be safe if (lockData->flags & 0x80) { //NOTE(adm244): using padding here, should be safe uint8 savedTries = lockData->pad01[0]; if (savedTries == 0) { lockData->flags &= 0x7F; } else { *gTerminalTryCount = (int32)savedTries; } } //BSReadWriteLock_Unlock(&extrasList->lock); } extern "C" void HackingQuit() { //TESConsolePrint("Terminal Hacking Quitted"); ExtraDataList *extrasList = (*gActiveTerminalREFR)->extraDataList; assert(extrasList != 0); ExtraLockData *lockData = ExtraDataList_GetExtraLockData(extrasList); assert(lockData != 0); //FIX(adm244): locks game sometimes? //BSReadWriteLock_Lock(&extrasList->lock); lockData->flags |= 0x80; lockData->pad01[0] = (uint8)(*gTerminalTryCount); //BSReadWriteLock_Unlock(&extrasList->lock); } //NOTE(adm244): returns true if VATS is allowed to activate, false otherwise extern "C" bool VATSActivate() { return IsPlayerInCombat(); } #endif
29.730159
78
0.70929
e7fe5c6f89e5e9048437b4d5c476f271f8341ad0
1,180
cpp
C++
source/idf/MadCatz.cpp
greck2908/IDF
0882cc35d88b96b0aea55e112060779654f040a6
[ "NASA-1.3" ]
84
2016-06-15T21:26:02.000Z
2022-03-12T15:09:57.000Z
source/idf/MadCatz.cpp
greck2908/IDF
0882cc35d88b96b0aea55e112060779654f040a6
[ "NASA-1.3" ]
44
2016-10-19T17:35:01.000Z
2022-03-11T17:20:51.000Z
source/idf/MadCatz.cpp
greck2908/IDF
0882cc35d88b96b0aea55e112060779654f040a6
[ "NASA-1.3" ]
46
2016-06-25T00:18:52.000Z
2019-12-19T11:13:15.000Z
#include "idf/MadCatz.hh" namespace idf { MadCatz::MadCatz() : forwardBackwardPivot(0, 1023, 511), leftRightPivot(0, 1023, 511), twist(0, 255, 127), leftThrottle(0, 255, 127), rightThrottle(0, 255, 127), trigger(0, 1), button2(0, 1), button3(0, 1), button4(0, 1), button5(0, 1), button6(0, 1), button7(0, 1), button8(0, 1), button9(0, 1), button10(0, 1), button11(0, 1), buttonX(0, 1), hatNorth(0, 1), hatNorthEast(0, 1), hatEast(0, 1), hatSouthEast(0, 1), hatSouth(0, 1), hatSouthWest(0, 1), hatWest(0, 1), hatNorthWest(0, 1), scrollUp(0, 1), scrollDown(0, 1) {} const std::vector<InputLayout::Configurable>& MadCatz::getConfigurables() { static std::vector<Configurable> inputs; if (inputs.empty()) { append(InputLayout::getConfigurables(), inputs); inputs.push_back(Configurable(forwardBackwardPivot, "Forward/Backward Pivot", "forwardBackwardPivot")); inputs.push_back(Configurable(leftRightPivot, "Left/Right Pivot", "leftRightPivot")); inputs.push_back(Configurable(twist, "Twist", "twist")); } return inputs; } }
25.652174
111
0.616102
e7feb77a0e6a3e4807d2f203b96c6ff3cb432fb3
1,002
hpp
C++
coroutine/OverridingList.hpp
bxtx999/pmembench
9577a15bc7934a681f23b3096f2cd25e09f66874
[ "MIT", "Unlicense" ]
10
2021-02-09T21:07:12.000Z
2022-02-10T17:37:06.000Z
coroutine/OverridingList.hpp
bxtx999/pmembench
9577a15bc7934a681f23b3096f2cd25e09f66874
[ "MIT", "Unlicense" ]
null
null
null
coroutine/OverridingList.hpp
bxtx999/pmembench
9577a15bc7934a681f23b3096f2cd25e09f66874
[ "MIT", "Unlicense" ]
4
2021-04-12T08:13:09.000Z
2022-01-05T02:54:45.000Z
#pragma once // ------------------------------------------------------------------------------------- #include <type_traits> #include <cassert> // ------------------------------------------------------------------------------------- template<typename Value> class OverridingList { public: OverridingList() : head(nullptr) {} void Push(Value ptr) { Entry *entry = reinterpret_cast<Entry *>(ptr); entry->next = head; head = ptr; } Value Pop() { assert(!Empty()); Value result = head; head = reinterpret_cast<Entry *>(head)->next; return result; } Value Top() { assert(!Empty()); return head; } bool Empty() const { return head == nullptr; } private: static_assert(std::is_pointer<Value>::value, "InPlaceList can not work on values."); struct Entry { Value next; }; Value head; }; // -------------------------------------------------------------------------------------
20.875
88
0.422156
e7fecc8db9d079f7a0163210bdc20ae85ebd86fd
1,593
hpp
C++
unit_tests/common/test_string_collection.hpp
eido5/cubrid
f32dbe7cb90f096035c255d7b5f348438bbb5830
[ "Apache-2.0", "BSD-3-Clause" ]
253
2016-03-12T01:03:42.000Z
2022-03-14T08:24:39.000Z
unit_tests/common/test_string_collection.hpp
eido5/cubrid
f32dbe7cb90f096035c255d7b5f348438bbb5830
[ "Apache-2.0", "BSD-3-Clause" ]
1,124
2016-03-31T03:48:58.000Z
2022-03-31T23:44:04.000Z
unit_tests/common/test_string_collection.hpp
eido5/cubrid
f32dbe7cb90f096035c255d7b5f348438bbb5830
[ "Apache-2.0", "BSD-3-Clause" ]
268
2016-03-02T06:48:44.000Z
2022-03-04T05:17:24.000Z
/* * Copyright 2008 Search Solution Corporation * Copyright 2016 CUBRID Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _TEST_STRING_COLLECTION_HPP_ #define _TEST_STRING_COLLECTION_HPP_ #include <string> #include <vector> /* * string_collection - a class collection of strings */ namespace test_common { class string_collection { public: template <typename ... Args> string_collection (Args &... args) { register_names (args...); } size_t get_count () const; size_t get_max_length () const; const char *get_name (size_t name_index) const; private: string_collection (); template <typename FirstArg, typename ... OtherArgs> void register_names (FirstArg &first, OtherArgs &... other) { m_names.push_back (first); register_names (other...); } template <typename OneArg> void register_names (OneArg &arg) { m_names.push_back (arg); } std::vector<std::string> m_names; }; } // namespace test_common #endif // _TEST_STRING_COLLECTION_HPP_
23.776119
76
0.696798
f001aa502b6b916c44ef754284d4953e994763a6
2,085
hh
C++
Include/Zion/GameMode.hh
ZionMP/Zion
7266cc5df81644e54c2744fca7f31b24873b31e7
[ "BSD-2-Clause" ]
1
2021-10-14T05:25:47.000Z
2021-10-14T05:25:47.000Z
Include/Zion/GameMode.hh
ZionMP/Zion
7266cc5df81644e54c2744fca7f31b24873b31e7
[ "BSD-2-Clause" ]
null
null
null
Include/Zion/GameMode.hh
ZionMP/Zion
7266cc5df81644e54c2744fca7f31b24873b31e7
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include "Base.hh" #include "Player.hh" #include "Vehicle.hh" #include "Util.hh" #include "TextDraw.hh" #include "Pickup.hh" namespace Zion { class GameMode { public: virtual void OnPlayerInteriorChange(Player *player, int newInterior, int oldInterior) {} virtual void OnDialogResponse(Player *player, int dialogId, int buttonId, int listItem, const char *inputText) {} virtual void OnPlayerClickMap(Player *player, Vector3 position) {} virtual void OnPlayerCommandText(Player *player, const char *command) {} virtual void OnClientMessage(Player *player, const char *message) {} virtual void OnPlayerDeath(Player *player, Player *killer, int reason) {} virtual void OnPlayerSpawn(Player *player) {} virtual bool OnPlayerRequestSpawn(Player *player) { return true; } virtual bool OnPlayerRequestClass(Player *player, int classId) { return true; } virtual void OnPlayerConnect(Player *player) {} virtual void OnPlayerDisconnect(Player *player, int reason) {} virtual void OnPlayerUpdate(Player *player) {} virtual void OnPlayerEnterCheckpoint(Player *player) {} virtual void OnPlayerLeaveCheckpoint(Player *player) {} virtual void OnPlayerEnterRaceCheckpoint(Player *player) {} virtual void OnPlayerLeaveRaceCheckpoint(Player *player) {} virtual void OnPlayerStateChange(Player *player, int newState, int oldState) {} virtual void OnPlayerEnterVehicle(Player *player, Vehicle *vehicle, bool ispassenger) {} virtual void OnPlayerExitVehicle(Player *player, Vehicle *vehicle) {} virtual void OnVehicleDamageStatusUpdate(Vehicle *vehicle, Player *player) {} virtual void OnGameModeInit() {} virtual void OnGameModeExit() {} virtual void OnPlayerClickTextDraw(Player *player, TextDraw *textDraw) {} virtual void OnPlayerPickUpPickup(Player *player, Pickup *pickup) {} }; };
56.351351
125
0.67482
f00450a13a46bc0721e45e796715b2a81e3a5215
558
cpp
C++
ZenUnitTestUtils/TestingNonDefaults.cpp
NeilJustice/ZenUnitAndZenMock
bbcb4221d063fa04e4ef3a98143e0f123e3af8d5
[ "MIT" ]
2
2019-11-11T17:32:53.000Z
2020-04-22T20:42:56.000Z
ZenUnitTestUtils/TestingNonDefaults.cpp
NeilJustice/ZenUnitAndZenMock
bbcb4221d063fa04e4ef3a98143e0f123e3af8d5
[ "MIT" ]
1
2018-04-21T07:53:26.000Z
2018-05-20T14:50:07.000Z
ZenUnitTestUtils/TestingNonDefaults.cpp
NeilJustice/ZenUnitAndZenMock
bbcb4221d063fa04e4ef3a98143e0f123e3af8d5
[ "MIT" ]
null
null
null
#include "pch.h" #include "ZenUnitTestUtils/TestingNonDefaults.h" namespace ZenUnit { TestResult TestingNonDefaultTestResult() noexcept { const FullTestName fullTestName("Non", "Default", 0); TestResult constructorFailTestResult = TestResult::ConstructorFail(fullTestName, TestPhaseResult()); return constructorFailTestResult; } TestClassResult TestingNonDefaultTestClassResult() { TestClassResult testClassResult; testClassResult._testResults.resize(1); return testClassResult; } }
27.9
107
0.724014
f004f4a56457c170fc13c7bf1990d6c17b22871e
2,563
cpp
C++
core/runtime/register_trt_op.cpp
SrivastavaKshitij/TRTorch
cbe186603e21a7e6cb51a4e8182d6e397b33c7ab
[ "BSD-3-Clause" ]
9
2020-10-28T14:54:19.000Z
2021-12-23T07:23:04.000Z
core/runtime/register_trt_op.cpp
magnetsrev/TRTorch
72bf74b2a2e425e6c83542f99c92b9e551148149
[ "BSD-3-Clause" ]
1
2021-07-22T16:58:40.000Z
2021-07-22T16:58:40.000Z
core/runtime/register_trt_op.cpp
magnetsrev/TRTorch
72bf74b2a2e425e6c83542f99c92b9e551148149
[ "BSD-3-Clause" ]
2
2020-10-12T05:47:33.000Z
2020-11-05T09:26:07.000Z
#include "c10/cuda/CUDAStream.h" #include "torch/csrc/jit/runtime/custom_operator.h" #include "torch/torch.h" #include "core/runtime/runtime.h" #include "core/util/prelude.h" namespace trtorch { namespace core { namespace runtime { std::vector<at::Tensor> execute_engine(std::vector<at::Tensor> inputs, c10::intrusive_ptr<TRTEngine> compiled_engine) { LOG_DEBUG("Attempting to run engine (ID: " << compiled_engine->name << ")"); std::vector<void*> gpu_handles; std::vector<at::Tensor> contig_inputs{}; contig_inputs.reserve(inputs.size()); for (size_t i = 0; i < inputs.size(); i++) { uint64_t pyt_idx = compiled_engine->in_binding_map[i]; TRTORCH_CHECK( inputs[pyt_idx].is_cuda(), "Expected input tensors to have device cuda, found device " << inputs[pyt_idx].device()); auto expected_type = util::toATenDType(compiled_engine->exec_ctx->getEngine().getBindingDataType(i)); TRTORCH_CHECK( inputs[pyt_idx].dtype() == expected_type, "Expected input tensors to have type " << expected_type << ", found type " << inputs[pyt_idx].dtype()); auto dims = core::util::toDimsPad(inputs[pyt_idx].sizes(), 1); auto shape = core::util::toVec(dims); contig_inputs.push_back(inputs[pyt_idx].view(shape).contiguous()); LOG_DEBUG("Input shape: " << dims); compiled_engine->exec_ctx->setBindingDimensions(i, dims); gpu_handles.push_back(contig_inputs.back().data_ptr()); } TRTORCH_CHECK( compiled_engine->exec_ctx->allInputDimensionsSpecified(), "Not enough inputs provided (runtime.RunCudaEngine)"); std::vector<at::Tensor> outputs(compiled_engine->num_io.second); for (size_t o = inputs.size(); o < (compiled_engine->num_io.first + compiled_engine->num_io.second); o++) { uint64_t pyt_idx = compiled_engine->out_binding_map[o]; auto out_shape = compiled_engine->exec_ctx->getBindingDimensions(o); LOG_DEBUG("Output shape: " << out_shape); auto dims = core::util::toVec(out_shape); auto type = util::toATenDType(compiled_engine->exec_ctx->getEngine().getBindingDataType(o)); outputs[pyt_idx] = std::move(at::empty(dims, {at::kCUDA}).to(type).contiguous()); gpu_handles.push_back(outputs[pyt_idx].data_ptr()); } c10::cuda::CUDAStream stream = c10::cuda::getCurrentCUDAStream(inputs[0].device().index()); compiled_engine->exec_ctx->enqueueV2(gpu_handles.data(), stream, nullptr); return outputs; } TORCH_LIBRARY(tensorrt, m) { m.def("execute_engine", execute_engine); } } // namespace runtime } // namespace core } // namespace trtorch
40.046875
119
0.708935
f005369c1ccf2e02974208beb2f1ab22db4f5cfb
2,025
hpp
C++
zen/lexgen/nodes.hpp
ZenLibraries/ZenLibraries
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
[ "Apache-2.0" ]
null
null
null
zen/lexgen/nodes.hpp
ZenLibraries/ZenLibraries
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
[ "Apache-2.0" ]
2
2020-02-06T17:01:39.000Z
2020-02-12T17:50:14.000Z
zen/lexgen/nodes.hpp
ZenLibraries/ZenLibraries
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
[ "Apache-2.0" ]
null
null
null
#ifndef ZEN_LEXGEN_NODES_HPP #define ZEN_LEXGEN_NODES_HPP #include <list> #include <memory> #include "zen/string.hpp" #include "zen/dllist.hpp" namespace zen { namespace lexgen { template<typename T> using SPtr = std::shared_ptr<T>; enum class NodeType { rule, ref_expr, char_expr, string_expr, choice_expr, seq_expr, }; class Node { NodeType type; public: inline Node(NodeType type): type(type) {} Node* parent_node = nullptr; inline NodeType get_type() const { return type; } template<typename DerivedT> inline DerivedT& as() { return *static_cast<DerivedT*>(this); } }; class Expr; class Rule : public Node { String name; SPtr<Expr> expr; public: inline Rule(String name): Node(NodeType::rule), name(name) {} string_view get_name() const { return name; } }; class Expr : public Node { public: inline Expr(NodeType type): Node(type) {} }; class CharExpr : public Expr { Glyph ch; public: inline CharExpr(Glyph ch): Expr(NodeType::char_expr), ch(ch) {} inline Glyph get_ch() const { return ch; } }; class ChoiceExpr : public Expr { using Elements = DLList<SPtr<Expr>>; Elements elements; public: template<typename RangeT> inline ChoiceExpr(RangeT range): Expr(NodeType::choice_expr), elements(range.begin(), range.end()) {} Elements::Range get_elements() { return elements.range(); } }; class SeqExpr : public Expr { using Elements = DLList<SPtr<Expr>>; Elements elements; public: inline SeqExpr(): Expr(NodeType::seq_expr) {} template<typename RangeT> inline SeqExpr(RangeT range): Expr(NodeType::seq_expr), elements(range) {} }; } } #endif // of #ifndef ZEN_LEXGEN_NODES_HPP
15.944882
76
0.576296
f00812be6bc41c86a6dcd549186c57d6f57ce8d3
2,301
hpp
C++
CookieEngine/include/Gameplay/CGPWorker.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/include/Gameplay/CGPWorker.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/include/Gameplay/CGPWorker.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
#ifndef _CGP_WORKER_HPP__ #define _CGP_WORKER_HPP__ #include "ComponentTransform.hpp" #include "Map.hpp" #include "Gameplay/CGPResource.hpp" #include "Gameplay/Income.hpp" #include <vector> namespace Cookie { namespace ECS { class Coordinator; } namespace Resources { class Prefab; class Map; } namespace Gameplay { #define TIME_TO_HARVEST 2 #define PRIMARY_PER_HARVEST 5 #define SECONDARY_PER_HARVEST 4 class CGPWorker { public: //will be replace by the CPGMove with flying later on float moveSpeed {5}; //Harvest Income* income {nullptr}; Core::Math::Vec3* posBase {nullptr}; Core::Math::Vec3* posResource {nullptr}; CGPResource* resource {nullptr}; float harvestCountdown {0}; bool isCarryingResource {false}; //Building std::vector<Resources::Prefab*> possibleBuildings; std::vector<std::string> possibleBuildingsAtLoad; Resources::Prefab* BuildingInConstruction {nullptr}; Core::Math::Vec3 posBuilding {0, 0, 0}; // = mousePos when start construction bool needTostartBuilding {false}; float constructionCountdown {0}; std::vector<Resources::Tile*> occupiedTiles; //get at start of building, then set in building CGPWorker() {} ~CGPWorker() {} inline void ToDefault() noexcept { income = nullptr; posBase = nullptr; posResource = nullptr; resource = nullptr; harvestCountdown = 0; isCarryingResource = false; possibleBuildings.clear(); possibleBuildingsAtLoad.clear(); BuildingInConstruction = nullptr; posBuilding = {0, 0, 0}; needTostartBuilding = false; constructionCountdown = 0; for (int i = 0; i < occupiedTiles.size(); ++i) occupiedTiles[i]->isObstacle = false; occupiedTiles.clear(); } void Update(Resources::Map& map, ECS::Coordinator& coordinator, int selfId); void SetResource(Core::Math::Vec3& resourcePos, CGPResource& resourceCGP); bool StartBuilding(Resources::Map& map, Core::Math::Vec3& _posBuilding, int indexInPossibleBuildings); }; } } #endif // !_CGP_WORKER_HPP__
26.755814
105
0.633638
f00a35b5915426f9c5ddcecaebf999755c2cc7e7
192
cpp
C++
bytecode/interpreter/src/BytecodeInterpreter/Units/InterpreterCommandMov.cpp
Scorbutics/skalang
c8d1869a2f0c7857ee05ef45bd3aa4e537d39558
[ "MIT" ]
3
2019-04-08T17:34:19.000Z
2020-01-03T04:47:06.000Z
bytecode/interpreter/src/BytecodeInterpreter/Units/InterpreterCommandMov.cpp
Scorbutics/skalang
c8d1869a2f0c7857ee05ef45bd3aa4e537d39558
[ "MIT" ]
4
2020-04-19T22:09:06.000Z
2020-11-06T15:47:08.000Z
bytecode/interpreter/src/BytecodeInterpreter/Units/InterpreterCommandMov.cpp
Scorbutics/skalang
c8d1869a2f0c7857ee05ef45bd3aa4e537d39558
[ "MIT" ]
null
null
null
#include "InterpreterCommandMov.h" SKALANG_BYTECODE_INTERPRETER_COMMAND_DECLARE(MOV)(ExecutionContext& context, const Operand& left, const Operand& right) { return context.getCell(left); }
32
121
0.8125
f00dbdb3d7bef7604daa1335487649f287667bd0
5,221
cpp
C++
libvast/src/system/read_query.cpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
249
2019-08-26T01:44:45.000Z
2022-03-26T14:12:32.000Z
libvast/src/system/read_query.cpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
586
2019-08-06T13:10:36.000Z
2022-03-31T08:31:00.000Z
libvast/src/system/read_query.cpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
37
2019-08-16T02:01:14.000Z
2022-02-21T16:13:59.000Z
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2019 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #include "vast/system/read_query.hpp" #include "vast/fwd.hpp" #include "vast/concept/parseable/to.hpp" #include "vast/concept/parseable/vast/expression.hpp" #include "vast/defaults.hpp" #include "vast/error.hpp" #include "vast/logger.hpp" #include "vast/scope_linked.hpp" #include "vast/system/signal_monitor.hpp" #include "vast/system/spawn_or_connect_to_node.hpp" #include <caf/actor.hpp> #include <caf/event_based_actor.hpp> #include <caf/scoped_actor.hpp> #include <caf/settings.hpp> #include <caf/stateful_actor.hpp> #include <sys/stat.h> #include <chrono> #include <cstdio> #include <fstream> #include <iostream> #include <unistd.h> using namespace caf; using namespace std::chrono_literals; namespace vast::system { namespace { caf::expected<std::string> read_query(const std::vector<std::string>& args, size_t offset) { if (args.size() > offset + 1) return caf::make_error(ec::invalid_argument, "spreading a query over " "multiple arguments is not " "allowed; please pass it as a " "single string instead."); return args[offset]; } caf::expected<std::string> read_query(std::istream& in) { auto result = std::string{}; result.assign(std::istreambuf_iterator<char>{in}, std::istreambuf_iterator<char>{}); return result; } caf::expected<std::string> read_query(const std::string& path) { std::ifstream f{path}; if (!f) return caf::make_error(ec::no_such_file, fmt::format("unable to read from '{}'", path)); return read_query(f); } std::string make_all_query() { VAST_VERBOSE("not providing a query causes everything to be exported; please " "be aware that this operation may be very expensive."); return R"__(#type != "this expression matches everything")__"; } } // namespace caf::expected<std::string> read_query(const invocation& inv, std::string_view file_option, enum must_provide_query must_provide_query, size_t argument_offset) { VAST_TRACE_SCOPE("{} {}", inv, file_option); // The below logic matches the following behavior: // vast export <format> <query> // takes the query from the command line // vast export -r - <format> // reads the query from stdin. // echo "query" | vast export <format> // reads the query from stdin // vast <query.txt export <format> // reads the query from `query.txt` // vast export <format> // export everything // Specifying any two conflicting ways of reading the query // results in an error. const auto fname = caf::get_if<std::string>(&inv.options, file_option); const bool has_query_cli = inv.arguments.size() > argument_offset; bool has_query_stdin = [] { struct stat stats = {}; if (::fstat(::fileno(stdin), &stats) != 0) return false; return S_ISFIFO(stats.st_mode) || S_ISREG(stats.st_mode); }(); if (fname) { if (has_query_cli) return caf::make_error( ec::invalid_argument, fmt::format("got query '{}' on the command line and query file" " '{}' specified via '--read' option", read_query(inv.arguments, argument_offset), *fname)); if (*fname == "-") return read_query(std::cin); if (has_query_stdin) return caf::make_error(ec::invalid_argument, fmt::format("stdin is connected to a pipe or " "regular file and query file '{}'", " specified via '--read' option", *fname)); return read_query(*fname); } // As a special case we ignore stdin unless we get an actual query // from it, since empirically this is often connected to the remnants // of a long-forgotten file descriptor by some distant parent process // when running in any kind of automated environment like a CI runner. std::string cin_query; if (has_query_stdin) { auto query = read_query(std::cin); if (!query || query->empty()) has_query_stdin = false; else cin_query = *query; } if (has_query_stdin && has_query_cli) return caf::make_error( ec::invalid_argument, fmt::format("got query '{}' on the command line and '{}' via stdin", read_query(inv.arguments, argument_offset), cin_query)); if (has_query_cli) return read_query(inv.arguments, argument_offset); if (has_query_stdin) return cin_query; if (must_provide_query == must_provide_query::yes) return caf::make_error(ec::invalid_argument, "no query provided, but " "command requires a query " "argument"); // No query provided, make a query that finds everything. return make_all_query(); } } // namespace vast::system
35.517007
80
0.622103
f00f829e36cab5051a674b7c0f5f57955c333623
4,000
hpp
C++
include/ashespp/RenderPass/RenderPass.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
227
2018-09-17T16:03:35.000Z
2022-03-19T02:02:45.000Z
include/ashespp/RenderPass/RenderPass.hpp
DragonJoker/RendererLib
0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a
[ "MIT" ]
39
2018-02-06T22:22:24.000Z
2018-08-29T07:11:06.000Z
include/ashespp/RenderPass/RenderPass.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
8
2019-05-04T10:33:32.000Z
2021-04-05T13:19:27.000Z
/* This file belongs to Ashes. See LICENSE file in root folder. */ #ifndef ___AshesPP_RenderPass_HPP___ #define ___AshesPP_RenderPass_HPP___ #pragma once #include "RenderPassCreateInfo.hpp" namespace ashes { /** *\brief * Describes a render pass (which can contain one or more render subpasses). */ class RenderPass : public VkObject { public: /** *\brief * Constructor. *\param[in] device * The logical device. *\param[in] createInfo * The creation informations. */ RenderPass( Device const & device , RenderPassCreateInfo createInfo ); /** *\brief * Constructor. *\param[in] device * The logical device. *\param[in] createInfo * The creation informations. */ RenderPass( Device const & device , std::string const & debugName , RenderPassCreateInfo createInfo ); /** *\brief * Destructor. */ ~RenderPass(); /** *\brief * Creates a frame buffer compatible with this render pass. *\remarks * If the compatibility between wanted views and the render pass' formats * is not possible, a std::runtime_error will be thrown. *\param[in] dimensions * The frame buffer's dimensions. *\param[in] views * The views for the frame buffer to create. *\param[in] layers * The layers count for the frame buffer to create. *\return * The created frame buffer. */ FrameBufferPtr createFrameBuffer( VkFramebufferCreateInfo info )const; /** *\brief * Creates a frame buffer compatible with this render pass. *\remarks * If the compatibility between wanted views and the render pass' formats * is not possible, a std::runtime_error will be thrown. *\param[in] dimensions * The frame buffer's dimensions. *\param[in] views * The views for the frame buffer to create. *\param[in] layers * The layers count for the frame buffer to create. *\return * The created frame buffer. */ FrameBufferPtr createFrameBuffer( std::string const & debugName , VkFramebufferCreateInfo info )const; /** *\brief * Creates a frame buffer compatible with this render pass. *\remarks * If the compatibility between wanted views and the render pass' formats * is not possible, a std::runtime_error will be thrown. *\param[in] dimensions * The frame buffer's dimensions. *\param[in] views * The views for the frame buffer to create. *\param[in] layers * The layers count for the frame buffer to create. *\return * The created frame buffer. */ FrameBufferPtr createFrameBuffer( VkExtent2D const & dimensions , ImageViewCRefArray views , uint32_t layers = 1u )const; /** *\brief * Creates a frame buffer compatible with this render pass. *\remarks * If the compatibility between wanted views and the render pass' formats * is not possible, a std::runtime_error will be thrown. *\param[in] dimensions * The frame buffer's dimensions. *\param[in] views * The views for the frame buffer to create. *\param[in] layers * The layers count for the frame buffer to create. *\return * The created frame buffer. */ FrameBufferPtr createFrameBuffer( std::string const & debugName , VkExtent2D const & dimensions , ImageViewCRefArray views , uint32_t layers = 1u )const; /** *name * Getters. */ /**@{*/ inline size_t getAttachmentCount()const { return m_createInfo.attachments.size(); } inline VkAttachmentDescriptionArray const & getAttachments()const { return m_createInfo.attachments; } inline Device const & getDevice()const { return m_device; } inline size_t getSubpassCount()const { return m_createInfo.subpasses.size(); } inline SubpassDescriptionArray const & getSubpasses()const { return m_createInfo.subpasses; } /**@}*/ /** *\brief * VkRenderPass implicit cast operator. */ inline operator VkRenderPass const & ()const { return m_internal; } private: Device const & m_device; RenderPassCreateInfo m_createInfo; VkRenderPass m_internal{}; }; } #endif
24.390244
76
0.70075
f0140c4ac96027b009016a32e66fd6ff5f3e6fc1
14,176
cpp
C++
Immortal/Platform/D3D12/RenderContext.cpp
QSXW/Immortal
32adcc8609b318752dd97f1c14dc7368b47d47d1
[ "Apache-2.0" ]
6
2021-09-15T08:56:28.000Z
2022-03-29T15:55:02.000Z
Immortal/Platform/D3D12/RenderContext.cpp
DaShi-Git/Immortal
e3345b4ff2a2b9d215c682db2b4530e24cc3b203
[ "Apache-2.0" ]
null
null
null
Immortal/Platform/D3D12/RenderContext.cpp
DaShi-Git/Immortal
e3345b4ff2a2b9d215c682db2b4530e24cc3b203
[ "Apache-2.0" ]
4
2021-12-05T17:28:57.000Z
2022-03-29T15:55:05.000Z
#include "impch.h" #include "RenderContext.h" #include "Framework/Utils.h" #include "Descriptor.h" namespace Immortal { namespace D3D12 { Device *RenderContext::UnlimitedDevice = nullptr; DescriptorAllocator RenderContext::shaderVisibleDescriptorAllocator{ DescriptorPool::Type::ShaderResourceView, DescriptorPool::Flag::ShaderVisible }; DescriptorAllocator RenderContext::descriptorAllocators[U32(DescriptorPool::Type::Quantity)] = { DescriptorPool::Type::ShaderResourceView, DescriptorPool::Type::Sampler, DescriptorPool::Type::RenderTargetView, DescriptorPool::Type::DepthStencilView }; RenderContext::RenderContext(Description &descrition) : desc{ descrition } { Setup(); } RenderContext::RenderContext(const void *handle) { Setup(); } RenderContext::~RenderContext() { IfNotNullThen<FreeLibrary>(hModule); } void RenderContext::Setup() { desc.FrameCount = Swapchain::SWAP_CHAIN_BUFFER_COUNT; uint32_t dxgiFactoryFlags = 0; #if SLDEBUG ComPtr<ID3D12Debug> debugController; if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController)))) { debugController->EnableDebugLayer(); dxgiFactoryFlags |= DXGI_CREATE_FACTORY_DEBUG; LOG::INFO("Enable Debug Layer: {0}", rcast<void*>(debugController.Get())); } #endif Check(CreateDXGIFactory2(dxgiFactoryFlags, IID_PPV_ARGS(&dxgiFactory)), "Failed to create DXGI Factory"); device = std::make_unique<Device>(dxgiFactory); UnlimitedDevice = device.get(); for (size_t i = 0; i < SL_ARRAY_LENGTH(descriptorAllocators); i++) { descriptorAllocators[i].Init(device.get()); } shaderVisibleDescriptorAllocator.Init(device.get()); auto adaptorDesc = device->AdaptorDesc(); Super::UpdateMeta( Utils::ws2s(adaptorDesc.Description).c_str(), nullptr, nullptr ); auto hWnd = rcast<HWND>(desc.WindowHandle->Primitive()); { Queue::Description queueDesc{}; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; queue = device->CreateQueue(queueDesc); } { Swapchain::Description swapchainDesc{}; CleanUpObject(&swapchainDesc); swapchainDesc.BufferCount = desc.FrameCount; swapchainDesc.Width = desc.Width; swapchainDesc.Height = desc.Height; swapchainDesc.Format = NORMALIZE(desc.format); swapchainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapchainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; swapchainDesc.SampleDesc.Count = 1; swapchainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; // swapchainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; swapchain = std::make_unique<Swapchain>(dxgiFactory, queue->Handle(), hWnd, swapchainDesc); // swapchain->SetMaximumFrameLatency(desc.FrameCount); // swapchainWritableObject = swapchain->FrameLatencyWaitableObject(); } Check(dxgiFactory->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER)); { CheckDisplayHDRSupport(); color.enableST2084 = color.hdrSupport; EnsureSwapChainColorSpace(color.bitDepth, color.enableST2084); /* SetHDRMetaData( HDRMetaDataPool[color.hdrMetaDataPoolIdx][0], HDRMetaDataPool[color.hdrMetaDataPoolIdx][1], HDRMetaDataPool[color.hdrMetaDataPoolIdx][2], HDRMetaDataPool[color.hdrMetaDataPoolIdx][3] ); */ } { DescriptorPool::Description renderTargetViewDesc = { DescriptorPool::Type::RenderTargetView, desc.FrameCount, DescriptorPool::Flag::None, 1 }; renderTargetViewDescriptorHeap = std::make_unique<DescriptorPool>( device->Handle(), &renderTargetViewDesc ); renderTargetViewDescriptorSize = device->DescriptorHandleIncrementSize( renderTargetViewDesc.Type ); } CreateRenderTarget(); for (int i{0}; i < desc.FrameCount; i++) { commandAllocator[i] = queue->RequestCommandAllocator(); } commandList = std::make_unique<CommandList>( device.get(), CommandList::Type::Direct, commandAllocator[0] ); commandList->Close(); queue->Handle()->ExecuteCommandLists(1, (ID3D12CommandList **)commandList->AddressOf()); // Create synchronization objects and wait until assets have been uploaded to the GPU. { frameIndex = swapchain->AcquireCurrentBackBufferIndex(); device->CreateFence(&fence, fenceValues[frameIndex], D3D12_FENCE_FLAG_NONE); fenceValues[frameIndex]++; // Create an event handle to use for frame synchronization. fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); if (!fenceEvent) { Check(HRESULT_FROM_WIN32(GetLastError())); return; } const uint64_t fenceToWaitFor = fenceValues[frameIndex]; queue->Signal(fence, fenceToWaitFor); fenceValues[frameIndex]++; Check(fence->SetEventOnCompletion(fenceToWaitFor, fenceEvent)); WaitForSingleObject(fenceEvent, INFINITE); } #ifdef SLDEBUG device->Set("RenderContext::Device"); #endif } void RenderContext::CreateRenderTarget() { CPUDescriptor renderTargetViewDescriptor { renderTargetViewDescriptorHeap->StartOfCPU() }; for (UINT i = 0; i < desc.FrameCount; i++) { swapchain->AccessBackBuffer(i, &renderTargets[i]); device->CreateView(renderTargets[i], rcast<D3D12_RENDER_TARGET_VIEW_DESC *>(nullptr), renderTargetViewDescriptor); renderTargetViewDescriptor.Offset(1, renderTargetViewDescriptorSize); renderTargets[i]->SetName((std::wstring(L"Render Target{") + std::to_wstring(i) + std::wstring(L"}")).c_str()); } } inline int ComputeIntersectionArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { // (ax1, ay1) = left-top coordinates of A; (ax2, ay2) = right-bottom coordinates of A // (bx1, by1) = left-top coordinates of B; (bx2, by2) = right-bottom coordinates of B return std::max(0, std::min(ax2, bx2) - std::max(ax1, bx1)) * std::max(0, std::min(ay2, by2) - std::max(ay1, by1)); } void RenderContext::EnsureSwapChainColorSpace(Swapchain::BitDepth bitDepth, bool enableST2084) { DXGI_COLOR_SPACE_TYPE colorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; switch (bitDepth) { case Swapchain::BitDepth::_8: color.rootConstants[DisplayCurve] = sRGB; break; case Swapchain::BitDepth::_10: colorSpace = enableST2084 ? DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020 : DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; color.rootConstants[DisplayCurve] = enableST2084 ? ST2084 : sRGB; break; case Swapchain::BitDepth::_16: colorSpace = DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709; color.rootConstants[DisplayCurve] = None; break; default: break; } if (color.currentColorSpace != colorSpace) { UINT colorSpaceSupport = 0; if (swapchain->CheckColorSpaceSupport(colorSpace, &colorSpaceSupport) && ((colorSpaceSupport & DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT) == DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT)) { swapchain->Set(colorSpace); color.currentColorSpace = colorSpace; } } } void RenderContext::CheckDisplayHDRSupport() { if (dxgiFactory->IsCurrent() == false) { Check(CreateDXGIFactory2(0, IID_PPV_ARGS(&dxgiFactory))); } ComPtr<IDXGIAdapter1> dxgiAdapter; Check(dxgiFactory->EnumAdapters1(0, &dxgiAdapter)); UINT i = 0; ComPtr<IDXGIOutput> currentOutput; ComPtr<IDXGIOutput> bestOutput; float bestIntersectArea = -1; while (dxgiAdapter->EnumOutputs(i, &currentOutput) != DXGI_ERROR_NOT_FOUND) { int ax1 = windowBounds.left; int ay1 = windowBounds.top; int ax2 = windowBounds.right; int ay2 = windowBounds.bottom; DXGI_OUTPUT_DESC desc{}; Check(currentOutput->GetDesc(&desc)); RECT rect = desc.DesktopCoordinates; int bx1 = rect.left; int by1 = rect.top; int bx2 = rect.right; int by2 = rect.bottom; int intersectArea = ComputeIntersectionArea(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2); if (intersectArea > bestIntersectArea) { bestOutput = currentOutput; bestIntersectArea = ncast<float>(intersectArea); } i++; } ComPtr<IDXGIOutput6> output6; Check(bestOutput.As(&output6)); DXGI_OUTPUT_DESC1 desc1; Check(output6->GetDesc1(&desc1)); color.hdrSupport = (desc1.ColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020); } void RenderContext::SetHDRMetaData(float maxOutputNits, float minOutputNits, float maxCLL, float maxFALL) { if (!swapchain) { return; } if (!color.hdrSupport) { swapchain->Set(DXGI_HDR_METADATA_TYPE_NONE, 0, nullptr); return; } static const DisplayChromaticities displayChromaticityList[] = { { 0.64000f, 0.33000f, 0.30000f, 0.60000f, 0.15000f, 0.06000f, 0.31270f, 0.32900f }, // Display Gamut Rec709 { 0.70800f, 0.29200f, 0.17000f, 0.79700f, 0.13100f, 0.04600f, 0.31270f, 0.32900f }, // Display Gamut Rec2020 }; int selectedChroma{ 0 }; if (color.bitDepth == Swapchain::BitDepth::_16 && color.currentColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709) { selectedChroma = 0; } else if (color.bitDepth == Swapchain::BitDepth::_10 && color.currentColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020) { selectedChroma = 1; } else { swapchain->Set(DXGI_HDR_METADATA_TYPE_NONE, 0, nullptr); } const DisplayChromaticities &chroma = displayChromaticityList[selectedChroma]; DXGI_HDR_METADATA_HDR10 metaData{}; metaData.RedPrimary[0] = ncast<UINT16>(chroma.RedX * 50000.0f); metaData.RedPrimary[0] = ncast<UINT16>(chroma.RedX * 50000.0f); metaData.RedPrimary[1] = ncast<UINT16>(chroma.RedY * 50000.0f); metaData.GreenPrimary[0] = ncast<UINT16>(chroma.GreenX * 50000.0f); metaData.GreenPrimary[1] = ncast<UINT16>(chroma.GreenY * 50000.0f); metaData.BluePrimary[0] = ncast<UINT16>(chroma.BlueX * 50000.0f); metaData.BluePrimary[1] = ncast<UINT16>(chroma.BlueY * 50000.0f); metaData.WhitePoint[0] = ncast<UINT16>(chroma.WhiteX * 50000.0f); metaData.WhitePoint[1] = ncast<UINT16>(chroma.WhiteY * 50000.0f); metaData.MaxMasteringLuminance = ncast<UINT>(maxOutputNits * 10000.0f); metaData.MinMasteringLuminance = ncast<UINT>(minOutputNits * 10000.0f); metaData.MaxContentLightLevel = ncast<UINT16>(maxCLL); metaData.MaxFrameAverageLightLevel = ncast<UINT16>(maxFALL); swapchain->Set(DXGI_HDR_METADATA_TYPE_HDR10, sizeof(metaData), &metaData); } void RenderContext::CleanUpRenderTarget() { for (UINT i = 0; i < desc.FrameCount; i++) { if (renderTargets[i]) { renderTargets[i]->Release(); renderTargets[i] = nullptr; } } } void RenderContext::WaitForGPU() { // Schedule a Signal command in the queue. queue->Signal(fence, fenceValues[frameIndex]); // Wait until the fence has been processed. fence->SetEventOnCompletion(fenceValues[frameIndex], fenceEvent); WaitForSingleObjectEx(fenceEvent, INFINITE, FALSE); // Increment the fence value for the current frame. fenceValues[frameIndex]++; } UINT RenderContext::WaitForPreviousFrame() { // Schedule a Signal command in the queue. const UINT64 currentFenceValue = fenceValues[frameIndex]; queue->Signal(fence, currentFenceValue); // Update the frame index. frameIndex = swapchain->AcquireCurrentBackBufferIndex(); // If the next frame is not ready to be rendered yet, wait until it is ready. auto completedValue = fence->GetCompletedValue(); if (completedValue < fenceValues[frameIndex]) { Check(fence->SetEventOnCompletion(fenceValues[frameIndex], fenceEvent)); WaitForSingleObjectEx(fenceEvent, INFINITE, FALSE); } // Set the fence value for the next frame. fenceValues[frameIndex] = currentFenceValue + 1; return frameIndex; } void RenderContext::UpdateSwapchain(UINT width, UINT height) { if (!swapchain) { return; } WaitForGPU(); CleanUpRenderTarget(); DXGI_SWAP_CHAIN_DESC1 swapchainDesc{}; swapchain->Desc(&swapchainDesc); swapchain->ResizeBuffers( width, height, DXGI_FORMAT_UNKNOWN, swapchainDesc.Flags, desc.FrameCount ); EnsureSwapChainColorSpace(color.bitDepth, color.enableST2084); CreateRenderTarget(); } void RenderContext::WaitForNextFrameResources() { frameIndex = swapchain->AcquireCurrentBackBufferIndex(); HANDLE waitableObjects[] = { swapchainWritableObject, NULL }; DWORD numWaitableObjects = 1; UINT64 fenceValue = fenceValues[frameIndex]; if (fenceValue != 0) // means no fence was signaled { fenceValues[frameIndex] = 0; fence->SetEventOnCompletion(fenceValue, fenceEvent); waitableObjects[1] = fenceEvent; numWaitableObjects = 2; } WaitForMultipleObjects(numWaitableObjects, waitableObjects, TRUE, INFINITE); } void RenderContext::CopyDescriptorHeapToShaderVisible() { auto srcDescriptorAllocator = descriptorAllocators[U32(DescriptorPool::Type::ShaderResourceView)]; device->CopyDescriptors( srcDescriptorAllocator.CountOfDescriptor(), shaderVisibleDescriptorAllocator.FreeStartOfHeap(), srcDescriptorAllocator.StartOfHeap(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ); } } }
31.572383
137
0.670076
f015cd8f7d4f76500819b27551d6ae929fb9f087
11,675
cpp
C++
models/processor/zesto/ZCOMPS-bpred/bpred-tage.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
8
2016-01-22T18:28:48.000Z
2021-05-07T02:27:21.000Z
models/processor/zesto/ZCOMPS-bpred/bpred-tage.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
3
2016-04-15T02:58:58.000Z
2017-01-19T17:07:34.000Z
models/processor/zesto/ZCOMPS-bpred/bpred-tage.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
10
2015-12-11T04:16:55.000Z
2019-05-25T20:58:13.000Z
/* bpred-tage.cpp: TAgged GEometric-history length predictor [Seznec and Michaud, JILP 2006] */ /* * __COPYRIGHT__ GT */ #define COMPONENT_NAME "tage" #ifdef BPRED_PARSE_ARGS if(!strcasecmp(COMPONENT_NAME,type)) { int num_tables; int bim_size; int table_size; int tag_width; int first_length; int last_length; if(sscanf(opt_string,"%*[^:]:%[^:]:%d:%d:%d:%d:%d:%d",name,&num_tables,&bim_size,&table_size,&tag_width,&first_length,&last_length) != 7) fatal("bad bpred options string %s (should be \"tage:name:num-tables:bim-size:table-size:tag-width:first-hist-length:last-hist-length\")",opt_string); return new bpred_tage_t(name,num_tables,bim_size,table_size,tag_width,first_length,last_length); } #else #include <math.h> class bpred_tage_t:public bpred_dir_t { #define TAGE_MAX_HIST 512 #define TAGE_MAX_TABLES 16 typedef qword_t bpred_tage_hist_t[8]; /* Max length: 8 * 64 = 512 */ struct bpred_tage_ent_t { int tag; char ctr; char u; }; class bpred_tage_sc_t:public bpred_sc_t { public: my2bc_t * current_ctr; bpred_tage_hist_t lookup_bhr; int index[TAGE_MAX_TABLES]; int provider; int provpred; int alt; int altpred; int used_alt; int provnew; }; private: inline void bpred_tage_hist_update(bpred_tage_hist_t H, int outcome) { H[7] <<= 1; H[7] |= (H[6]>>63)&1; H[6] <<= 1; H[6] |= (H[5]>>63)&1; H[5] <<= 1; H[5] |= (H[4]>>63)&1; H[4] <<= 1; H[4] |= (H[3]>>63)&1; H[3] <<= 1; H[3] |= (H[2]>>63)&1; H[2] <<= 1; H[2] |= (H[1]>>63)&1; H[1] <<= 1; H[1] |= (H[0]>>63)&1; H[0] <<= 1; H[0] |= outcome&1; } inline void bpred_tage_hist_copy(bpred_tage_hist_t D /*dest*/, bpred_tage_hist_t S /*src*/) { D[0] = S[0]; D[1] = S[1]; D[2] = S[2]; D[3] = S[3]; D[4] = S[4]; D[5] = S[5]; D[6] = S[6]; D[7] = S[7]; } int bpred_tage_hist_hash(bpred_tage_hist_t H, int hist_length, int hash_length) { int result = 0; int i; int mask = (1<<hash_length)-1; int row=0; int pos=0; for(i=0;i<hist_length/hash_length;i++) { result ^= (H[row]>>pos) & mask; if(pos+hash_length > 64) /* wrap past end of current qword_t */ { row++; pos = (pos+hash_length)&63; result ^= (H[row]<<(hash_length-pos))&mask; } else /* includes when pos+HL is exactly 64 */ { pos = pos+hash_length; if(pos > 63) { pos &=63; row++; } } } return result; } protected: int num_tables; int table_size; int log_size; int table_mask; int tag_width; int tag_mask; int bim_size; int bim_mask; int alpha; int * Hlen; /* array of history lengths */ struct bpred_tage_ent_t **T; int pwin; zcounter_t * Tuses; bpred_tage_hist_t bhr; public: /* CREATE */ bpred_tage_t(char * const arg_name, const int arg_num_tables, const int arg_bim_size, const int arg_table_size, const int arg_tag_width, const int arg_first_length, const int arg_last_length ) { init(); int i; /* verify arguments are valid */ CHECK_PPOW2(arg_bim_size); CHECK_PPOW2(arg_table_size); CHECK_POS(arg_num_tables); CHECK_POS(arg_tag_width); CHECK_POS(arg_first_length); CHECK_POS(arg_last_length); CHECK_POS_GT(arg_last_length,arg_first_length); CHECK_POS_LT(arg_num_tables,TAGE_MAX_TABLES); CHECK_POS_LEQ(arg_last_length,TAGE_MAX_HIST); for(i=0;i<8;i++) bhr[i] = 0; name = strdup(arg_name); if(!name) fatal("couldn't malloc tage name (strdup)"); type = strdup(COMPONENT_NAME); if(!type) fatal("couldn't malloc tage type (strdup)"); num_tables = arg_num_tables; table_size = arg_table_size; table_mask = arg_table_size-1; log_size = log_base2(arg_table_size); bim_size = arg_bim_size; bim_mask = arg_bim_size-1; double logA = (log(arg_last_length) - log(arg_first_length)) / ((double)arg_num_tables - 2.0); alpha = (int) exp(logA); Hlen = (int*) calloc(arg_num_tables,sizeof(*Hlen)); if(!Hlen) fatal("couldn't calloc Hlen array"); /* Hlen[0] = 0; set by calloc, for 2bc */ for(i=1;i<num_tables-1;i++) Hlen[i] = (int)floor(arg_first_length * pow(alpha,i-1) + 0.5); Hlen[i] = arg_last_length; T = (struct bpred_tage_ent_t**) calloc(num_tables,sizeof(*T)); if(!T) fatal("couldn't calloc tage T array"); tag_width = arg_tag_width; tag_mask = (1<<arg_tag_width)-1; for(i=0;i<num_tables;i++) { if(i>0) { T[i] = (struct bpred_tage_ent_t*) calloc(table_size,sizeof(**T)); if(!T[i]) fatal("couldn't calloc tage T[%d]",i); for(int j=0;j<table_size;j++) { T[i][j].tag = 0; T[i][j].ctr = 4; /* weakly taken */ } } else /* T0 */ { T[i] = (struct bpred_tage_ent_t*) calloc(bim_size,sizeof(**T)); if(!T[i]) fatal("couldn't calloc tage T[%d]",i); for(int j=0;j<bim_size;j++) T[i][j].ctr = MY2BC_WEAKLY_TAKEN; /* weakly taken */ } } Tuses = (zcounter_t*) calloc(num_tables,sizeof(*Tuses)); if(!Tuses) fatal("failed to calloc Tuses"); pwin = 15; bits = bim_size*2 /*2bc*/ + (num_tables-1)*(2/*u*/+3/*ctr*/+tag_width)*table_size + arg_last_length + 4/*use altpred?*/; } /* DESTROY */ ~bpred_tage_t() { free(Tuses); Tuses = NULL; for(int i=0;i<num_tables;i++) { free(T[i]); T[i] = NULL; } free(T); T = NULL; free(Hlen); Hlen = NULL; } /* LOOKUP */ BPRED_LOOKUP_HEADER { class bpred_tage_sc_t * sc = (class bpred_tage_sc_t*) scvp; for(int i=0;i<num_tables;i++) { if(i==0) sc->index[i] = PC; else sc->index[i] = PC^bpred_tage_hist_hash(bhr,Hlen[i],log_size); } sc->provider = 0; sc->provpred = 0; sc->altpred = 0; sc->provnew = false; int hit = false; int pwin_hit = false; for(int i=num_tables-1;i>0;i--) { struct bpred_tage_ent_t * ent = &T[i][sc->index[i]&table_mask]; if(((unsigned)ent->tag) == (PC&tag_mask)) { sc->provnew = !ent->u && ((ent->ctr==4) || (ent->ctr==3)); if((pwin < 8) || !sc->provnew) pwin_hit = true; sc->provpred = (ent->ctr >= 4); hit = true; sc->provider = i; break; } } sc->alt = -1; if(hit) { for(int i=sc->provider-1;i>0;i--) { struct bpred_tage_ent_t * ent = &T[i][sc->index[i]&table_mask]; if((unsigned)ent->tag == (PC&tag_mask)) { sc->altpred = (ent->ctr >= 4); sc->alt = i; break; } } } if(sc->alt == -1) { sc->altpred = MY2BC_DIR(T[0][sc->index[0]&bim_mask].ctr); sc->alt = 0; } sc->updated = false; BPRED_STAT(lookups++;) bpred_tage_hist_copy(sc->lookup_bhr,bhr); if(!pwin_hit) { sc->used_alt = true; return sc->altpred; } else { sc->used_alt = false; return sc->provpred; } } /* UPDATE */ BPRED_UPDATE_HEADER { class bpred_tage_sc_t * sc = (class bpred_tage_sc_t*) scvp; if(!sc->updated) { BPRED_STAT(updates++;) BPRED_STAT(num_hits += our_pred == outcome;) if(sc->used_alt) Tuses[sc->alt]++; else { assert(sc->provider); Tuses[sc->provider]++; } if(sc->provnew) { if(sc->altpred != sc->provpred) { if(sc->altpred == outcome) { if(pwin < 15) pwin++; } else { if(pwin > 0) pwin--; } } } /* Allocate new entry if needed */ if(our_pred != outcome) /* mispred */ { if(sc->provider < (num_tables-1)) /* not already using longest history */ { int allocated = 0; int allocated2 = 0; for(int i=sc->provider+1;i<num_tables;i++) { if(T[i][sc->index[i]&table_mask].u == 0) { if(!allocated) allocated = i; else { allocated2 = i; break; } } } if(allocated) { if(allocated2) /* more than one choice */ { if((random() & 0xffff) > 21845) /* choose allocated over allocated2 with 2:1 probability */ allocated = allocated2; } struct bpred_tage_ent_t * ent = &T[allocated][sc->index[allocated]&table_mask]; ent->u = 0; ent->ctr = 3+outcome; ent->tag = PC & tag_mask; } else { for(int i=sc->provider+1;i<num_tables;i++) if(T[i][sc->index[i]&table_mask].u > 0) T[i][sc->index[i]&table_mask].u --; } } } /* perioidic reset of ubits */ if((updates & ((1<<18)-1)) == 0) { int mask = ~1; if(updates & (1<<18)) /* alternate reset msb and lsb */ mask = ~2; for(int i=1;i<num_tables;i++) { for(int j=0;j<table_size;j++) T[i][j].u &= mask; } } /* update provider component */ if((sc->provider == 0) || ((sc->alt == 0) && (sc->used_alt))) MY2BC_UPDATE(T[0][sc->index[0]&bim_mask].ctr,outcome); else { if(outcome) { if(T[sc->provider][sc->index[sc->provider]&table_mask].ctr < 7) T[sc->provider][sc->index[sc->provider]&table_mask].ctr ++; } else { if(T[sc->provider][sc->index[sc->provider]&table_mask].ctr > 0) T[sc->provider][sc->index[sc->provider]&table_mask].ctr --; } } /* update u counter: inc if correct and different than altpred */ if(sc->provpred != sc->altpred) { if(sc->provpred == outcome) { if(T[sc->provider][sc->index[sc->provider]&table_mask].u < 3) T[sc->provider][sc->index[sc->provider]&table_mask].u ++; } else { if(T[sc->provider][sc->index[sc->provider]&table_mask].u > 0) T[sc->provider][sc->index[sc->provider]&table_mask].u --; } } sc->updated = true; } } /* SPEC UPDATE */ BPRED_SPEC_UPDATE_HEADER { BPRED_STAT(spec_updates++;) bpred_tage_hist_update(bhr,our_pred); } BPRED_RECOVER_HEADER { class bpred_tage_sc_t * sc = (class bpred_tage_sc_t*) scvp; bpred_tage_hist_copy(bhr,sc->lookup_bhr); bpred_tage_hist_update(bhr,outcome); } BPRED_FLUSH_HEADER { class bpred_tage_sc_t * sc = (class bpred_tage_sc_t*) scvp; bpred_tage_hist_copy(bhr,sc->lookup_bhr); } /* REG_STATS */ BPRED_REG_STATS_HEADER { bpred_dir_t::reg_stats(sdb,core); int id = core?core->current_thread->id:0; for(int i=0;i<num_tables;i++) { char buf[256]; char buf2[256]; sprintf(buf,"c%d.%s.uses%d",id,name,i); sprintf(buf2,"predictions made with %s's T[%d]",name,i); stat_reg_counter(sdb, true, buf, buf2, &Tuses[i], 0, NULL); } } /* GETCACHE */ BPRED_GET_CACHE_HEADER { class bpred_tage_sc_t * sc = new bpred_tage_sc_t(); if(!sc) fatal("couldn't malloc tage State Cache"); return sc; } }; #endif /* BPRED_PARSE_ARGS */ #undef COMPONENT_NAME
23.92418
154
0.53439
f0185c17361e3baf8c59b31edc45e0b8ac2a6df0
6,895
cpp
C++
Apps/APTestApp/MainMac.cpp
tom-weatherhead/exeter-asset-processor
e19c777427afe66684f308cb7b07448b3481c25e
[ "MIT" ]
null
null
null
Apps/APTestApp/MainMac.cpp
tom-weatherhead/exeter-asset-processor
e19c777427afe66684f308cb7b07448b3481c25e
[ "MIT" ]
null
null
null
Apps/APTestApp/MainMac.cpp
tom-weatherhead/exeter-asset-processor
e19c777427afe66684f308cb7b07448b3481c25e
[ "MIT" ]
null
null
null
/* main.c */ #include <Carbon/Carbon.h> #include "main.h" #include "ExAPBitmapARGB32.h" void Initialize(void); /* function prototypes */ void EventLoop(void); void MakeWindow(void); void MakeMenu(void); void DoEvent(EventRecord *event); void DoMenuCommand(long menuResult); void DoAboutBox(void); void DrawWindow(WindowRef window); void DrawTestImage( WindowRef window ); static OSErr QuitAppleEventHandler(const AppleEvent *appleEvt, AppleEvent* reply, UInt32 refcon); Boolean gQuitFlag; /* global */ int main(int argc, char *argv[]) { Initialize(); MakeWindow(); MakeMenu(); EventLoop(); return 0; } void Initialize() /* Initialize the cursor and set up AppleEvent quit handler */ { OSErr err; InitCursor(); err = AEInstallEventHandler( kCoreEventClass, kAEQuitApplication, NewAEEventHandlerUPP((AEEventHandlerProcPtr)QuitAppleEventHandler), 0, false ); if (err != noErr) ExitToShell(); } static OSErr QuitAppleEventHandler( const AppleEvent *appleEvt, AppleEvent* reply, UInt32 refcon ) { gQuitFlag = true; return noErr; } void EventLoop() { Boolean gotEvent; EventRecord event; gQuitFlag = false; do { gotEvent = WaitNextEvent(everyEvent, &event, kSleepTime, nil); if (gotEvent) DoEvent(&event); } while (!gQuitFlag); ExitToShell(); } void MakeWindow() /* Put up a window */ { Rect wRect; WindowRef myWindow; SetRect(&wRect,50,50,600,200); /* left, top, right, bottom */ myWindow = NewCWindow(nil, &wRect, "\pHello", true, zoomNoGrow, (WindowRef) -1, true, 0); if (myWindow != nil) SetPortWindowPort(myWindow); /* set port to new window */ else ExitToShell(); } void MakeMenu() /* Put up a menu */ { Handle menuBar; MenuRef menu; long response; OSErr err; menuBar = GetNewMBar(rMenuBar); /* read menus into menu bar */ if ( menuBar != nil ) { SetMenuBar(menuBar); /* install menus */ err = Gestalt(gestaltMenuMgrAttr, &response); if ((err == noErr) && (response & gestaltMenuMgrAquaLayoutMask)) { menu = GetMenuHandle( mFile ); DeleteMenuItem( menu, iQuit ); DeleteMenuItem( menu, iQuitSeparator ); } DrawMenuBar(); } else ExitToShell(); } void DoEvent(EventRecord *event) { short part; Boolean hit; char key; Rect tempRect; WindowRef whichWindow; switch (event->what) { case mouseDown: part = FindWindow(event->where, &whichWindow); switch (part) { case inMenuBar: /* process a moused menu command */ DoMenuCommand(MenuSelect(event->where)); break; case inSysWindow: break; case inContent: if (whichWindow != FrontWindow()) SelectWindow(whichWindow); break; case inDrag: /* pass screenBits.bounds */ GetRegionBounds(GetGrayRgn(), &tempRect); DragWindow(whichWindow, event->where, &tempRect); break; case inGrow: break; case inGoAway: if (TrackGoAway(whichWindow, event->where)) DisposeWindow(whichWindow); break; case inZoomIn: case inZoomOut: hit = TrackBox(whichWindow, event->where, part); if (hit) { SetPort(GetWindowPort(whichWindow)); // window must be current port EraseRect(GetWindowPortBounds(whichWindow, &tempRect)); // inval/erase because of ZoomWindow bug ZoomWindow(whichWindow, part, true); InvalWindowRect(whichWindow, GetWindowPortBounds(whichWindow, &tempRect)); } break; } break; case keyDown: case autoKey: key = event->message & charCodeMask; if (event->modifiers & cmdKey) if (event->what == keyDown) DoMenuCommand(MenuKey(key)); case activateEvt: /* if you needed to do something special */ break; case updateEvt: DrawWindow((WindowRef) event->message); break; case kHighLevelEvent: AEProcessAppleEvent( event ); break; case diskEvt: break; } } void DoMenuCommand(long menuResult) { short menuID; /* the resource ID of the selected menu */ short menuItem; /* the item number of the selected menu */ menuID = HiWord(menuResult); /* use macros to get item & menu number */ menuItem = LoWord(menuResult); switch (menuID) { case mApple: switch (menuItem) { case iAbout: DoAboutBox(); break; case iQuit: ExitToShell(); break; default: break; } break; case mFile: break; case mEdit: break; } HiliteMenu(0); /* unhighlight what MenuSelect (or MenuKey) hilited */ } void DrawWindow( WindowRef window ) { Rect tempRect; GrafPtr curPort; GetPort(&curPort); SetPort(GetWindowPort(window)); BeginUpdate(window); EraseRect(GetWindowPortBounds(window, &tempRect)); #if 1 DrawTestImage( window ); #endif DrawControls(window); DrawGrowIcon(window); EndUpdate(window); SetPort(curPort); } void DoAboutBox(void) { (void) Alert(kAboutBox, nil); // simple alert dialog box } void DrawTestImage( WindowRef window ) { // Window is 550 pixels wide, 150 pixels high. ExAPBitmapARGB32 image( 550, 150 ); unsigned char srcPixelArray[4] = { 0xFF, 0x00, 0x00, 0xFF }; const unsigned char * srcPixel = srcPixelArray; const ExAPRect imageBoundingRect = image.getBoundingRect(); #if 1 image.SolidRectangle( imageBoundingRect, srcPixel ); #endif image.PixelByteSwap(); image.DrawIntoMacWindow( window ); } // **** End of File ****
26.621622
150
0.522843
f01900af12de7167295f7738f8636d6c75b1ce11
8,180
cc
C++
src/server/DataBase.cc
ryan-rao/LTFS-Data-Management
041960282d20aeefb8da20eabf04367a164a5903
[ "Apache-2.0" ]
19
2018-06-28T03:53:41.000Z
2022-03-15T16:17:33.000Z
src/server/DataBase.cc
ryan-rao/LTFS-Data-Management
041960282d20aeefb8da20eabf04367a164a5903
[ "Apache-2.0" ]
13
2018-04-25T15:40:14.000Z
2021-01-18T11:03:27.000Z
src/server/DataBase.cc
ryan-rao/LTFS-Data-Management
041960282d20aeefb8da20eabf04367a164a5903
[ "Apache-2.0" ]
8
2018-08-08T05:40:31.000Z
2022-03-22T16:21:06.000Z
/******************************************************************************* * Copyright 2018 IBM Corp. 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 * * https://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 "ServerIncludes.h" DataBase DB; std::mutex DataBase::trans_mutex; DataBase::~DataBase() { if (dbNeedsClosed) sqlite3_close(db); sqlite3_shutdown(); } void DataBase::cleanup() { unlink(Const::DB_FILE.c_str()); unlink((Const::DB_FILE + "-journal").c_str()); } void DataBase::fits(sqlite3_context *ctx, int argc, sqlite3_value **argv) { assert(argc == 5); unsigned long size = sqlite3_value_int64(argv[1]); unsigned long *free = (unsigned long *) sqlite3_value_int64(argv[2]); unsigned long *num_found = (unsigned long *) sqlite3_value_int64(argv[3]); unsigned long *total = (unsigned long *) sqlite3_value_int64(argv[4]); if (*free >= size) { *free -= size; (*total)++; (*num_found)++; sqlite3_result_int(ctx, 1); } else { (*total)++; sqlite3_result_int(ctx, 0); } } void DataBase::open(bool dbUseMemory) { int rc; std::string sql; std::string uri; if (dbUseMemory) uri = "file::memory:"; else uri = std::string("file:") + Const::DB_FILE; rc = sqlite3_config(SQLITE_CONFIG_URI, 1); if (rc != SQLITE_OK) { TRACE(Trace::error, rc); errno = rc; THROW(Error::GENERAL_ERROR, uri, rc); } rc = sqlite3_initialize(); if (rc != SQLITE_OK) { TRACE(Trace::error, rc); errno = rc; THROW(Error::GENERAL_ERROR, rc); } rc = sqlite3_open_v2(uri.c_str(), &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_SHAREDCACHE | SQLITE_OPEN_EXCLUSIVE, NULL); if (rc != SQLITE_OK) { TRACE(Trace::error, rc, uri); errno = rc; THROW(Error::GENERAL_ERROR, uri, rc); } rc = sqlite3_extended_result_codes(db, 1); if (rc != SQLITE_OK) { TRACE(Trace::error, rc); errno = rc; THROW(Error::GENERAL_ERROR, rc); } dbNeedsClosed = true; sqlite3_create_function(db, "FITS", 5, SQLITE_UTF8, NULL, &DataBase::fits, NULL, NULL); } void DataBase::createTables() { SQLStatement stmt; stmt(DataBase::CREATE_JOB_QUEUE); stmt.doall(); stmt(DataBase::CREATE_REQUEST_QUEUE); stmt.doall(); } std::string DataBase::opStr(DataBase::operation op) { switch (op) { case MOUNT: return ltfsdm_messages[LTFSDMX0078I]; case UNMOUNT: return ltfsdm_messages[LTFSDMX0079I]; case TRARECALL: return ltfsdm_messages[LTFSDMX0015I]; case SELRECALL: return ltfsdm_messages[LTFSDMX0014I]; case MIGRATION: return ltfsdm_messages[LTFSDMX0013I]; case FORMAT: return ltfsdm_messages[LTFSDMX0081I]; case CHECK: return ltfsdm_messages[LTFSDMX0082I]; case MOVE: return ltfsdm_messages[LTFSDMX0087I]; default: return ""; } } std::string DataBase::reqStateStr(DataBase::req_state reqs) { switch (reqs) { case REQ_NEW: return ltfsdm_messages[LTFSDMX0016I]; case REQ_INPROGRESS: return ltfsdm_messages[LTFSDMX0017I]; case REQ_COMPLETED: return ltfsdm_messages[LTFSDMX0018I]; default: return ""; } } int DataBase::lastUpdates() { return sqlite3_changes(db); } SQLStatement& SQLStatement::operator()(std::string _fmtstr) { fmtstr = _fmtstr; try { fmt = boost::format(fmtstr); } catch (const std::exception& e) { MSG(LTFSDMS0102E); THROW(Error::GENERAL_ERROR, e.what(), fmtstr); } return *this; } void SQLStatement::prepare() { int rc; rc = sqlite3_prepare_v2(DB.getDB(), fmt.str().c_str(), -1, &stmt, NULL); if (rc != SQLITE_OK) { TRACE(Trace::error, fmt.str(), rc); errno = rc; THROW(Error::GENERAL_ERROR, rc); } } std::string SQLStatement::encode(std::string s) { std::string enc; for (char c : s) { switch (c) { case 0047: enc += "\\0047"; break; case 0134: enc += "\\0134"; break; default: enc += c; } } return enc; } std::string SQLStatement::decode(std::string s) { unsigned long pos = s.size(); while ((pos = s.rfind("\\", pos)) != std::string::npos) { if (s.compare(pos, 5, "\\0047") == 0) { s.replace(pos, 5, std::string(1, 0047)); } else if (s.compare(pos, 5, "\\0134") == 0) { s.replace(pos, 5, std::string(1, 0134)); } else { THROW(Error::GENERAL_ERROR, s); } pos--; } return s; } void SQLStatement::getColumn(int *result, int column) { *result = sqlite3_column_int(stmt, column); } void SQLStatement::getColumn(unsigned int *result, int column) { *result = static_cast<unsigned int>(sqlite3_column_int(stmt, column)); } void SQLStatement::getColumn(DataBase::operation *result, int column) { *result = static_cast<DataBase::operation>(sqlite3_column_int(stmt, column)); } void SQLStatement::getColumn(DataBase::req_state *result, int column) { *result = static_cast<DataBase::req_state>(sqlite3_column_int(stmt, column)); } void SQLStatement::getColumn(FsObj::file_state *result, int column) { *result = static_cast<FsObj::file_state>(sqlite3_column_int(stmt, column)); } void SQLStatement::getColumn(long *result, int column) { *result = sqlite3_column_int64(stmt, column); } void SQLStatement::getColumn(unsigned long *result, int column) { *result = static_cast<unsigned long>(sqlite3_column_int64(stmt, column)); } void SQLStatement::getColumn(unsigned long long *result, int column) { *result = static_cast<unsigned long long>(sqlite3_column_int64(stmt, column)); } void SQLStatement::getColumn(std::string *result, int column) { const char *column_ctr = reinterpret_cast<const char*>(sqlite3_column_text( stmt, column)); if (column_ctr != NULL) *result = decode(std::string(column_ctr)); else *result = ""; } std::string SQLStatement::str() { std::string str; try { str = fmt.str(); } catch (const std::exception& e) { MSG(LTFSDMS0102E); THROW(Error::GENERAL_ERROR, e.what(), fmtstr); } return str; } void SQLStatement::bind(int num, int value) { int rc; if ((rc = sqlite3_bind_int(stmt, num, value)) != SQLITE_OK) { TRACE(Trace::error, rc); errno = rc; THROW(Error::GENERAL_ERROR, rc); } } void SQLStatement::bind(int num, std::string value) { int rc; if ((rc = sqlite3_bind_text(stmt, num, value.c_str(), value.size(), 0)) != SQLITE_OK) { TRACE(Trace::error, rc); errno = rc; THROW(Error::GENERAL_ERROR, rc); } } void SQLStatement::finalize() { if (stmt_rc != SQLITE_ROW && stmt_rc != SQLITE_DONE) { TRACE(Trace::error, fmt.str(), stmt_rc); errno = stmt_rc; THROW(Error::GENERAL_ERROR, stmt_rc); } int rc = sqlite3_finalize(stmt); if (rc != SQLITE_OK) { TRACE(Trace::error, fmt.str(), rc); errno = rc; THROW(Error::GENERAL_ERROR, rc); } } void SQLStatement::doall() { prepare(); step(); finalize(); }
22.349727
81
0.590098
f01a5de4d6d19de7b46c6a567e60cd2d44ae84e6
1,786
cpp
C++
bachelor/computer-graphics/Les1/CG1_2DVector.cpp
Brent-rb/University
caae9c7d8e44bf7589865517f786529b1f171059
[ "MIT" ]
null
null
null
bachelor/computer-graphics/Les1/CG1_2DVector.cpp
Brent-rb/University
caae9c7d8e44bf7589865517f786529b1f171059
[ "MIT" ]
null
null
null
bachelor/computer-graphics/Les1/CG1_2DVector.cpp
Brent-rb/University
caae9c7d8e44bf7589865517f786529b1f171059
[ "MIT" ]
null
null
null
// CG1_2DVector.cpp: implementation of the CG1_2DVector class. // ////////////////////////////////////////////////////////////////////// #include "CG1_2DVector.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// /********************************************************************/ CG1_2DVector::CG1_2DVector() { } /********************************************************************/ CG1_2DVector::CG1_2DVector(float X, float Y) { x = X; y = Y; } /********************************************************************/ CG1_2DVector::~CG1_2DVector() { } /********************************************************************/ float CG1_2DVector::operator*(const CG1_2DVector &v) // DOT-PRODUKT { return ((x * v.x) + (y * v.y)); } /********************************************************************/ CG1_2DVector &CG1_2DVector::operator=(const CG1_2DVector &v) // TOEKENNINGS-OPERATOR { x = v.x; y = v.y; return *this; } /********************************************************************/ CG1_2DVector CG1_2DVector::operator-() // NEGATIE { CG1_2DVector Neg; Neg.SetXY(-x, -y); return Neg; } /********************************************************************/ void CG1_2DVector::SetXY(float NewX, float NewY) { x = NewX; y = NewY; } /********************************************************************/ float CG1_2DVector::GetX() { return x; } /********************************************************************/ float CG1_2DVector::GetY() { return y; } /********************************************************************/
21.518072
85
0.285554
f01cea47e637935b9573a782878720ddcdf1d0fa
1,902
cpp
C++
CS208_Lab/huffman_code.cpp
zc-BEAR/Course_Repo
bbbcc83992f3e837dfb21615bb8e81d86f397f83
[ "MIT" ]
null
null
null
CS208_Lab/huffman_code.cpp
zc-BEAR/Course_Repo
bbbcc83992f3e837dfb21615bb8e81d86f397f83
[ "MIT" ]
null
null
null
CS208_Lab/huffman_code.cpp
zc-BEAR/Course_Repo
bbbcc83992f3e837dfb21615bb8e81d86f397f83
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct Node{ int c; int num; Node* fa; bool operator < (const Node &x)const{ return x.num < num; } }num[100]; int t, str_len, fa_index; int val[100]; long long ans; string str; int main(){ ios::sync_with_stdio(false); cin.tie(0); cin >> t; for (int i = 1; i <= 99; ++i) num[i].c = i + 96; while(t--){ cin>>str; fa_index = 27; str_len = str.size(); for (int i = 0; i < str_len; ++i) { num[str[i] - 96].num++; } priority_queue<Node> q; for(int i = 1;i <= 26;i++){ if(num[i].num)q.push(num[i]); } if(q.size()==1){ ans = q.top().num; cout<<ans<<"\n"; ans = 0; while(!q.empty())q.pop(); for (int i = 1; i <= 99; ++i) { num[i].num = 0,val[i] = 0,num[i].fa = nullptr; } continue; } while(!q.empty()){ int tmp1 = q.top().c - 96;q.pop(); if(q.empty())break; int tmp2 = q.top().c - 96;q.pop(); num[fa_index].num = num[tmp1].num + num[tmp2].num; num[tmp1].fa = &num[fa_index]; num[tmp2].fa = &num[fa_index]; q.push(num[fa_index]); fa_index++; } for (int i = 1; i <= 26; ++i) { val[i] = -1; } for(int i = 1;i <= 26;i++){ Node* pr = &num[i]; while(pr != nullptr ){ val[i]++; pr = pr->fa; } } for (int i = 1; i <= 26; ++i) { ans += num[i].num * val[i]; } cout<<ans<<"\n"; ans = 0; while(!q.empty())q.pop(); for (int i = 1; i <= 99; ++i) { num[i].num = 0,val[i] = 0,num[i].fa = nullptr; } } return 0; }
24.701299
62
0.388013
f01e5468ec34fc81f5bfb7f0da1d4d62e9107d7c
387
cpp
C++
leetcode/two-pointer/11.container-with-most-water.cpp
saurabhraj042/dsaPrep
0973a03bc565a2850003c7e48d99b97ff83b1d01
[ "MIT" ]
23
2021-10-30T04:11:52.000Z
2021-11-27T09:16:18.000Z
leetcode/two-pointer/11.container-with-most-water.cpp
Pawanupadhyay10/placement-prep
0449fa7cbc56e7933e6b090936ab7c15ca5f290f
[ "MIT" ]
null
null
null
leetcode/two-pointer/11.container-with-most-water.cpp
Pawanupadhyay10/placement-prep
0449fa7cbc56e7933e6b090936ab7c15ca5f290f
[ "MIT" ]
4
2021-10-30T03:26:05.000Z
2021-11-14T12:15:04.000Z
// saurabhraj042 class Solution { public: int maxArea(vector<int>& A) { int i = 0,j = A.size()-1; int mx = j * min( A[i],A[j] ); while( i < j ) { if( (j-i) * min( A[j],A[i] ) > mx) mx=(j-i)*min(A[j],A[i]); if( A[i] < A[j]) i++; else j--; } return mx; } };
19.35
46
0.330749
f01ebd1ec67d7007bf3487191f5484056bc66b78
5,238
cpp
C++
clang-tools-extra/test/pp-trace/pp-trace-pragma-general.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
clang-tools-extra/test/pp-trace/pp-trace-pragma-general.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang-tools-extra/test/pp-trace/pp-trace-pragma-general.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
// RUN: pp-trace -callbacks '*,-FileChanged,-MacroDefined' %s -- | FileCheck --strict-whitespace %s #pragma clang diagnostic push #pragma clang diagnostic pop #pragma clang diagnostic ignored "-Wformat" #pragma clang diagnostic warning "-Wformat" #pragma clang diagnostic error "-Wformat" #pragma clang diagnostic fatal "-Wformat" #pragma GCC diagnostic push #pragma GCC diagnostic pop #pragma GCC diagnostic ignored "-Wformat" #pragma GCC diagnostic warning "-Wformat" #pragma GCC diagnostic error "-Wformat" #pragma GCC diagnostic fatal "-Wformat" void foo() { #pragma clang __debug captured { } } // CHECK: --- // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:3:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDiagnosticPush // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:3:15" // CHECK-NEXT: Namespace: clang // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:4:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDiagnosticPop // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:4:15" // CHECK-NEXT: Namespace: clang // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:5:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDiagnostic // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:5:15" // CHECK-NEXT: Namespace: clang // CHECK-NEXT: Mapping: MAP_IGNORE // CHECK-NEXT: Str: -Wformat // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:6:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDiagnostic // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:6:15" // CHECK-NEXT: Namespace: clang // CHECK-NEXT: Mapping: MAP_WARNING // CHECK-NEXT: Str: -Wformat // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:7:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDiagnostic // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:7:15" // CHECK-NEXT: Namespace: clang // CHECK-NEXT: Mapping: MAP_ERROR // CHECK-NEXT: Str: -Wformat // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:8:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDiagnostic // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:8:15" // CHECK-NEXT: Namespace: clang // CHECK-NEXT: Mapping: MAP_FATAL // CHECK-NEXT: Str: -Wformat // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:10:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDiagnosticPush // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:10:13" // CHECK-NEXT: Namespace: GCC // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:11:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDiagnosticPop // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:11:13" // CHECK-NEXT: Namespace: GCC // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:12:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDiagnostic // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:12:13" // CHECK-NEXT: Namespace: GCC // CHECK-NEXT: Mapping: MAP_IGNORE // CHECK-NEXT: Str: -Wformat // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:13:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDiagnostic // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:13:13" // CHECK-NEXT: Namespace: GCC // CHECK-NEXT: Mapping: MAP_WARNING // CHECK-NEXT: Str: -Wformat // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:14:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDiagnostic // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:14:13" // CHECK-NEXT: Namespace: GCC // CHECK-NEXT: Mapping: MAP_ERROR // CHECK-NEXT: Str: -Wformat // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:15:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDiagnostic // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:15:13" // CHECK-NEXT: Namespace: GCC // CHECK-NEXT: Mapping: MAP_FATAL // CHECK-NEXT: Str: -Wformat // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:18:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDebug // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-general.cpp:18:23" // CHECK-NEXT: DebugType: captured // CHECK-NEXT: - Callback: EndOfMainFile // CHECK-NEXT: ...
44.016807
99
0.653685
f01f9b2b18a3d97fdf502b9b2fde13cba6e1418a
849
cpp
C++
Source/PluginPostEffects_Core1/Exports.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
3
2019-04-12T15:22:53.000Z
2022-01-05T02:59:56.000Z
Source/PluginPostEffects_Core1/Exports.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
null
null
null
Source/PluginPostEffects_Core1/Exports.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
2
2019-04-10T22:46:21.000Z
2020-05-27T16:21:37.000Z
#define DLL_EXPORT #include "Exports.h" #include "Plugins/IPostEffectFactory.h" #include "Factories.h" namespace Core { namespace Plugin { CPostEffectFactory_Bloom* Bloom = nullptr; CPostEffectFactory_Hdr* Hdr = nullptr; CPostEffectFactory_MotionBlur* MotionBlur = nullptr; CPostEffectFactory_SSAO* Ssao = nullptr; extern "C" { DECLDIR void GetFactories(Vector<IPostEffectFactory*>& list) { Bloom = new CPostEffectFactory_Bloom(); if(Bloom) list.push_back(Bloom); Hdr = new CPostEffectFactory_Hdr(); if(Hdr) list.push_back(Hdr); MotionBlur = new CPostEffectFactory_MotionBlur(); if(MotionBlur) list.push_back(MotionBlur); Ssao = new CPostEffectFactory_SSAO(); if(Ssao) list.push_back(Ssao); } DECLDIR E_PLUGIN GetPluginType(void) { return Core::Plugin::EP_POSTEFFECT; } } } }
19.295455
62
0.720848
f020af42a32e14a0c8a88f5f7986e92a282436ca
376
cpp
C++
moosh/src/msg_handler.cpp
mujido/moove
380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b
[ "Apache-2.0" ]
null
null
null
moosh/src/msg_handler.cpp
mujido/moove
380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b
[ "Apache-2.0" ]
null
null
null
moosh/src/msg_handler.cpp
mujido/moove
380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b
[ "Apache-2.0" ]
null
null
null
#include "msg_handler.hpp" #include <iostream> void MessageHandler::error(const std::string& msg, unsigned lineNum) { std::cerr << "Error, line " << lineNum + m_lineOffset << ": " << msg << std::endl; } void MessageHandler::warning(const std::string& msg, unsigned lineNum) { std::cerr << "Warning, line " << lineNum + m_lineOffset << ": " << msg << std::endl; }
25.066667
87
0.638298
f0226c78fa7c6e4f85aedf840418a5f8df8a9b15
10,309
cpp
C++
HaloTAS/TASDLL/tas_hooks.cpp
s3anyboy/HaloTAS
9584786f19e1475399298fda2d5783d47623cccd
[ "MIT" ]
6
2019-09-10T19:47:04.000Z
2020-11-26T08:32:36.000Z
HaloTAS/TASDLL/tas_hooks.cpp
s3anyboy/HaloTAS
9584786f19e1475399298fda2d5783d47623cccd
[ "MIT" ]
13
2018-11-24T09:37:49.000Z
2021-10-22T02:29:11.000Z
HaloTAS/TASDLL/tas_hooks.cpp
s3anyboy/HaloTAS
9584786f19e1475399298fda2d5783d47623cccd
[ "MIT" ]
3
2020-07-28T09:19:14.000Z
2020-09-02T04:48:49.000Z
#include "tas_hooks.h" #include "tas_logger.h" #include "tas_input_handler.h" #include "randomizer.h" #include "halo_engine.h" #include "render_d3d9.h" // Function Defs typedef HRESULT(__stdcall* GetDeviceState_t)(LPDIRECTINPUTDEVICE*, DWORD, LPVOID*); typedef HRESULT(__stdcall* GetDeviceData_t)(LPDIRECTINPUTDEVICE*, DWORD, LPDIDEVICEOBJECTDATA, LPDWORD, DWORD); typedef void(__cdecl* SimulateTick_t)(int); typedef char(__cdecl* AdvanceFrame_t)(float); typedef int(__cdecl* BeginLoop_t)(); typedef void(__cdecl* GetMouseKeyboardGamepadInput_t)(); typedef void(__cdecl* AdvanceEffectsTimer_t)(float); typedef HRESULT(__stdcall* D3D9BeginScene_t)(IDirect3DDevice9* pDevice); typedef HRESULT(__stdcall* D3D9EndScene_t)(IDirect3DDevice9* pDevice); typedef HRESULT(__stdcall* D3D9Present_t)(IDirect3DDevice9* pDevice, const RECT*, const RECT*, HWND, RGNDATA*); // Declarations HRESULT __stdcall hkGetDeviceState(LPDIRECTINPUTDEVICE* pDevice, DWORD cbData, LPVOID* lpvData); HRESULT __stdcall hkGetDeviceData(LPDIRECTINPUTDEVICE* pDevice, DWORD cbObjectData, LPDIDEVICEOBJECTDATA rgdod, LPDWORD pdwInOut, DWORD dwFlags); void __cdecl hkSimulateTick(int); char __cdecl hkAdvanceFrame(float); int __cdecl hkBeginLoop(); void __cdecl hkGetMouseKeyboardGamepadInput(); void __cdecl hkAdvanceEffectsTimer(float); HRESULT __stdcall hkD3D9EndScene(IDirect3DDevice9* pDevice); HRESULT __stdcall hkD3D9BeginScene(IDirect3DDevice9* pDevice); HRESULT __stdcall hkD3D9Present(IDirect3DDevice9* pDevice, const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, RGNDATA* pDirtyRegion); // Store original pointers to old functions GetDeviceState_t originalGetDeviceState; GetDeviceData_t originalGetDeviceData; SimulateTick_t originalSimulateTick = (SimulateTick_t)(0x45B780); AdvanceFrame_t originalAdvanceFrame = (AdvanceFrame_t)(0x470BF0); BeginLoop_t originalBeginLoop = (BeginLoop_t)(0x4C6E80); AdvanceEffectsTimer_t originalAdvanceEffectsTimer = (AdvanceEffectsTimer_t)(0x45b4f0); GetMouseKeyboardGamepadInput_t originalGetMouseKeyboardGamepadInput = (GetMouseKeyboardGamepadInput_t)(0x490760); D3D9EndScene_t originalD3D9EndScene; D3D9BeginScene_t originalD3D9BeginScene; D3D9Present_t originalD3D9Present; void tas_hooks::detours_error(LONG detourResult) { if (detourResult != NO_ERROR) { throw; } } void tas_hooks::hook_function(PVOID* originalFunc, PVOID replacementFunc) { DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); detours_error(DetourAttach(originalFunc, replacementFunc)); detours_error(DetourTransactionCommit()); } void tas_hooks::unhook_function(PVOID* originalFunc, PVOID replacementFunc) { DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourDetach(originalFunc, replacementFunc); DetourTransactionCommit(); } void tas_hooks::hook_dinput8() { // DIRECTINPUT8 LPDIRECTINPUT8 pDI8; DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&pDI8, NULL); if (!pDI8) { tas_logger::fatal("Couldn't get dinput8 handle."); exit(1); } LPDIRECTINPUTDEVICE8 pDI8Dev = nullptr; pDI8->CreateDevice(GUID_SysKeyboard, &pDI8Dev, NULL); if (!pDI8Dev) { pDI8->Release(); tas_logger::fatal("Couldn't create dinput8 device."); exit(1); } void** dinputVTable = *reinterpret_cast<void***>(pDI8Dev); originalGetDeviceState = (GetDeviceState_t)(dinputVTable[9]); originalGetDeviceData = (GetDeviceData_t)(dinputVTable[10]); pDI8Dev->Release(); pDI8->Release(); hook_function(&(PVOID&)originalGetDeviceState, hkGetDeviceState); hook_function(&(PVOID&)originalGetDeviceData, hkGetDeviceData); } void tas_hooks::hook_d3d9() { IDirect3D9* pD3D = Direct3DCreate9(D3D_SDK_VERSION); if (!pD3D) { tas_logger::fatal("Couldn't get d3d9 handle."); exit(1); } int mainMonitorX = GetSystemMetrics(SM_CXSCREEN); int mainMonitorY = GetSystemMetrics(SM_CYSCREEN); D3DPRESENT_PARAMETERS d3dpp = { 0 }; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.hDeviceWindow = GetForegroundWindow(); d3dpp.Windowed = TRUE; d3dpp.BackBufferCount = 1; d3dpp.BackBufferWidth = std::clamp(mainMonitorX, 800, 8000); d3dpp.BackBufferHeight = std::clamp(mainMonitorY, 600, 8000); IDirect3DDevice9* dummyD3D9Device = nullptr; pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, d3dpp.hDeviceWindow, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &dummyD3D9Device); if (!dummyD3D9Device) { pD3D->Release(); tas_logger::fatal("Couldn't create dummy d3d9 device."); exit(1); } void** d3d9VTable = *reinterpret_cast<void***>(dummyD3D9Device); #if _DEBUG // Breakpoint to find additional D3D functions if needed // Make sure symbols are loaded for (int i = 0; i < 180; i++) { auto funcPtr = d3d9VTable[i]; } #endif originalD3D9BeginScene = (D3D9BeginScene_t)(d3d9VTable[41]); hook_function(&(PVOID&)originalD3D9BeginScene, hkD3D9BeginScene); originalD3D9EndScene = (D3D9EndScene_t)(d3d9VTable[42]); hook_function(&(PVOID&)originalD3D9EndScene, hkD3D9EndScene); originalD3D9Present = (D3D9Present_t)(d3d9VTable[17]); hook_function(&(PVOID&)originalD3D9Present, hkD3D9Present); dummyD3D9Device->Release(); pD3D->Release(); } void tas_hooks::hook_halo_engine() { hook_function(&(PVOID&)originalSimulateTick, hkSimulateTick); hook_function(&(PVOID&)originalAdvanceFrame, hkAdvanceFrame); hook_function(&(PVOID&)originalBeginLoop, hkBeginLoop); hook_function(&(PVOID&)originalGetMouseKeyboardGamepadInput, hkGetMouseKeyboardGamepadInput); hook_function(&(PVOID&)originalAdvanceEffectsTimer, hkAdvanceEffectsTimer); } void tas_hooks::attach_all() { hook_dinput8(); hook_d3d9(); hook_halo_engine(); } void tas_hooks::detach_all() { unhook_function(&(PVOID&)originalGetDeviceState, hkGetDeviceState); unhook_function(&(PVOID&)originalGetDeviceData, hkGetDeviceData); unhook_function(&(PVOID&)originalSimulateTick, hkSimulateTick); unhook_function(&(PVOID&)originalAdvanceFrame, hkAdvanceFrame); unhook_function(&(PVOID&)originalBeginLoop, hkBeginLoop); unhook_function(&(PVOID&)originalGetMouseKeyboardGamepadInput, hkGetMouseKeyboardGamepadInput); unhook_function(&(PVOID&)originalAdvanceEffectsTimer, hkAdvanceEffectsTimer); unhook_function(&(PVOID&)originalD3D9EndScene, hkD3D9EndScene); unhook_function(&(PVOID&)originalD3D9BeginScene, hkD3D9BeginScene); unhook_function(&(PVOID&)originalD3D9Present, hkD3D9Present); } /* HOOKED FUNCTIONS */ static int32_t pressedMouseTick = 0; static bool btn_down[3] = { false, false, false }; static bool btn_queued[3] = { false, false, false }; HRESULT __stdcall hkGetDeviceState(LPDIRECTINPUTDEVICE* lpDevice, DWORD cbData, LPVOID* lpvData) // Mouse { HRESULT hResult = DI_OK; hResult = originalGetDeviceState(lpDevice, cbData, lpvData); return hResult; } static bool tab_down = false; static bool enter_down = false; static bool g_down = false; static DWORD lastsequence = 0; static int32_t pressedTick = 0; static bool enterPreviousFrame = false; static int32_t enterPressedFrame = 0; static bool queuedEnter = false; static bool queuedTab = false; static bool queuedG = false; HRESULT __stdcall hkGetDeviceData(LPDIRECTINPUTDEVICE* pDevice, DWORD cbObjectData, LPDIDEVICEOBJECTDATA rgdod, LPDWORD pdwInOut, DWORD dwFlags) // Keyboard { HRESULT hResult = DI_OK; auto& inputHandler = tas_input_handler::get(); if (inputHandler.this_tick_enter() && pressedTick != inputHandler.get_current_playback_tick()) { queuedEnter = true; } if (inputHandler.this_tick_tab() && pressedTick != inputHandler.get_current_playback_tick()) { queuedTab = true; } if (inputHandler.this_tick_g() && pressedTick != inputHandler.get_current_playback_tick()) { queuedG = true; } pressedTick = inputHandler.get_current_playback_tick(); if (queuedEnter) { if (enter_down) { rgdod->dwData = 0x80; } else { rgdod->dwData = 0x00; queuedEnter = false; } rgdod->dwOfs = DIK_RETURN; rgdod->dwTimeStamp = GetTickCount(); rgdod->dwSequence = ++lastsequence; enter_down = !enter_down; return hResult; } if (queuedTab) { if (tab_down) { rgdod->dwData = 0x80; } else { rgdod->dwData = 0x00; queuedTab = false; } rgdod->dwOfs = DIK_TAB; rgdod->dwTimeStamp = GetTickCount(); rgdod->dwSequence = ++lastsequence; tab_down = !tab_down; return hResult; } if (queuedG) { if (g_down) { rgdod->dwData = 0x80; } else { rgdod->dwData = 0x00; queuedG = false; } rgdod->dwOfs = DIK_G; rgdod->dwTimeStamp = GetTickCount(); rgdod->dwSequence = ++lastsequence; g_down = !g_down; return hResult; } hResult = originalGetDeviceData(pDevice, cbObjectData, rgdod, pdwInOut, dwFlags); return hResult; } void hkSimulateTick(int ticksAfterThis) { auto& gInputHandler = tas_input_handler::get(); auto& gRandomizer = randomizer::get(); auto& gEngine = halo_engine::get(); gRandomizer.pre_tick(); gInputHandler.pre_tick(); originalSimulateTick(ticksAfterThis); gInputHandler.post_tick(); gEngine.post_tick(); } char hkAdvanceFrame(float deltaTime) { auto& gInputHandler = tas_input_handler::get(); auto& gEngine = halo_engine::get(); gEngine.pre_frame(); gInputHandler.pre_frame(); char c = originalAdvanceFrame(deltaTime); gInputHandler.post_frame(); return c; } int __cdecl hkBeginLoop() { auto& gInputHandler = tas_input_handler::get(); auto& gRandomizer = randomizer::get(); auto& gEngine = halo_engine::get(); gRandomizer.pre_loop(); gInputHandler.pre_loop(); auto ret = originalBeginLoop(); gInputHandler.post_loop(); return ret; } void __cdecl hkGetMouseKeyboardGamepadInput() { originalGetMouseKeyboardGamepadInput(); } void __cdecl hkAdvanceEffectsTimer(float dt) { originalAdvanceEffectsTimer(dt); } HRESULT __stdcall hkD3D9BeginScene(IDirect3DDevice9* pDevice) { return originalD3D9BeginScene(pDevice); } HRESULT __stdcall hkD3D9Present(IDirect3DDevice9* pDevice, const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, RGNDATA* pDirtyRegion) { auto& gEngine = halo_engine::get(); if (gEngine.is_present_enabled()) { return originalD3D9Present(pDevice, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion); } return D3D_OK; } HRESULT __stdcall hkD3D9EndScene(IDirect3DDevice9* pDevice) { auto& d3d9 = render_d3d9::get(); d3d9.render(pDevice); return originalD3D9EndScene(pDevice); }
30.957958
156
0.776409
f026bc67bdc4dda563e2a3d5378892436baf88ce
1,201
cpp
C++
13. Friend and Static Member/01_friend_function_my.cpp
All-CODE-with-Explanation/CPP_deep_dive_-Abdul-Bari-
2717ce14487deb47fff4ccc2b7349f12643bbd38
[ "MIT" ]
null
null
null
13. Friend and Static Member/01_friend_function_my.cpp
All-CODE-with-Explanation/CPP_deep_dive_-Abdul-Bari-
2717ce14487deb47fff4ccc2b7349f12643bbd38
[ "MIT" ]
null
null
null
13. Friend and Static Member/01_friend_function_my.cpp
All-CODE-with-Explanation/CPP_deep_dive_-Abdul-Bari-
2717ce14487deb47fff4ccc2b7349f12643bbd38
[ "MIT" ]
1
2021-12-01T14:03:07.000Z
2021-12-01T14:03:07.000Z
/* This program is my experiment. Create a global function and return an object. Also, make this as friend function. */ #include <iostream> using namespace std; class Test { private: protected: public: int a; int b; int c; friend Test fun(); // Though function doesn't belongs to this class but is a friend function // and can access and manipulate values even from outside upon object but not directly. void setData(int n1, int n2) { a = n1; b = n2; } void display() { cout<< a << " + " << b << "i" << endl; } }; // We make a global function which tries to access and set values of all data members of Test. // Global function can do so only when we have defined fun as friend inside the class // Used for operator overloading mostly. Test fun(Test o1, Test o2) { Test obj; obj.setData( (o1.a + o2.a ), (o1.b + o2.b) ); return obj; } /* Say we have a class Test as above and we have private, protected and public data members of it. */ int main() { Test o1, o2, o3; o1.setData(2, 4); o2.setData(3, 3); o3 = fun(o1, o2); o3.display(); return 0; }
17.661765
110
0.602831
f02732e925b9bd7a3d1071c0ebc55a73fc0c1d0d
418
hpp
C++
pythran/pythonic/include/numpy/isscalar.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/numpy/isscalar.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/numpy/isscalar.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_INCLUDE_NUMPY_ISSCALAR_HPP #define PYTHONIC_INCLUDE_NUMPY_ISSCALAR_HPP #include "pythonic/include/utils/functor.hpp" #include "pythonic/include/types/traits.hpp" #include "pythonic/include/types/str.hpp" #include <type_traits> namespace pythonic { namespace numpy { template <class E> constexpr bool isscalar(E const &); DECLARE_FUNCTOR(pythonic::numpy, isscalar); } } #endif
17.416667
47
0.763158
f02e4a207cb97f3d4edb73883357be6961ea0058
1,583
cpp
C++
src/network/uber-profile-requestor.cpp
ghosalmartin/harbour-uber
b8d906f4050cfea8817aaebe1ade5c3466662109
[ "MIT" ]
2
2018-03-16T10:31:20.000Z
2018-10-02T15:50:56.000Z
src/network/uber-profile-requestor.cpp
ghosalmartin/harbour-uber
b8d906f4050cfea8817aaebe1ade5c3466662109
[ "MIT" ]
null
null
null
src/network/uber-profile-requestor.cpp
ghosalmartin/harbour-uber
b8d906f4050cfea8817aaebe1ade5c3466662109
[ "MIT" ]
null
null
null
#include "uber-profile-requestor.h" UberProfileRequestor::UberProfileRequestor(QObject *parent) : UberRequestor(parent){ connect(this, SIGNAL(profileChanged(Profile*)), this, SLOT(setProfile(Profile*))); } void UberProfileRequestor::fetchProfileFromNetwork(){ makeNetworkCall( UBER_ME_ENDPOINT, QNetworkAccessManager::Operation::GetOperation); } void UberProfileRequestor::setProfile(Profile *profile){ if(this->m_profile != profile){ this->m_profile = profile; emit profileChanged(profile); } } Profile* UberProfileRequestor::getProfile(){ return this->m_profile; } void UberProfileRequestor::deserialize(QByteArray data) { QString stringReply = (QString) data; QJsonDocument jsonResponse = QJsonDocument::fromJson(stringReply.toUtf8()); QJsonObject jsonObject = jsonResponse.object(); Profile *profile = new Profile(jsonObject["picture"].toString(), jsonObject["first_name"].toString(), jsonObject["last_name"].toString(), jsonObject["uuid"].toString(), jsonObject["rider_id"].toString(), jsonObject["email"].toString(), jsonObject["mobile_verified"].toString(), jsonObject["promo_code"].toString()); setProfile(profile); } void UberProfileRequestor::onError(QString errorString){ qDebug() << errorString; }
33.680851
76
0.602021
f0301b4fa363e12af3da418ae0df901ea49d2cc4
712
cpp
C++
example/src/main.cpp
MarPta/HT1621_universal
e7fd629732c4830de4701c282a0457b53812f52c
[ "MIT" ]
null
null
null
example/src/main.cpp
MarPta/HT1621_universal
e7fd629732c4830de4701c282a0457b53812f52c
[ "MIT" ]
null
null
null
example/src/main.cpp
MarPta/HT1621_universal
e7fd629732c4830de4701c282a0457b53812f52c
[ "MIT" ]
null
null
null
#include <Arduino.h> #include "HT1621_universal.h" const uint8_t csPin = 14; //Chip selection output const uint8_t wrPin = 27; //Read clock output const uint8_t dataPin = 26; //Serial data output HT1621_universal lcd(csPin, wrPin, dataPin); void setup() { lcd.init(); lcd.HT1621_all_on(16); delay(1000); lcd.Write_1621(0,lcd.num[0]); //0 lcd.Write_1621(2,lcd.num[1]); //1 lcd.Write_1621(4,lcd.num[2]); //2 lcd.Write_1621(6,lcd.num[3]); //3 lcd.Write_1621(8,lcd.num[4]); //4 lcd.Write_1621(10,lcd.num[5]); //5 delay(1000); lcd.HT1621_all_off(10); delay(1000); Serial.begin(115200); } void loop() { lcd.displayCelsius(18.3); delay(2000); }
23.733333
51
0.633427
f0345cefb360a8d7f49255d1ecb9b909df56d97e
244
hpp
C++
include/PrimeGenerator.hpp
sigalor/prime-plot
53bfa9e5f4d89d717d616620045a7c21c7cfe733
[ "Apache-2.0" ]
9
2018-04-10T09:38:16.000Z
2021-02-02T22:46:30.000Z
include/PrimeGenerator.hpp
sigalor/prime-plot
53bfa9e5f4d89d717d616620045a7c21c7cfe733
[ "Apache-2.0" ]
null
null
null
include/PrimeGenerator.hpp
sigalor/prime-plot
53bfa9e5f4d89d717d616620045a7c21c7cfe733
[ "Apache-2.0" ]
2
2018-07-31T04:31:10.000Z
2019-12-21T22:47:50.000Z
#pragma once #include <iostream> #include <vector> //#include <thread> namespace PrimeGenerator { long integerSqrt(long num); std::vector<long> findPrimes(long start, std::size_t num, long* lastCurrLimit, long end=-1); }
15.25
99
0.67623
f03624c4db456ba229b7c38e968a48cfa94cb403
7,796
cpp
C++
Beon/src/main.cpp
Riordan-DC/B-on
174390c08eddcdfbd0ae7441fc440a32641bcf28
[ "MIT" ]
null
null
null
Beon/src/main.cpp
Riordan-DC/B-on
174390c08eddcdfbd0ae7441fc440a32641bcf28
[ "MIT" ]
null
null
null
Beon/src/main.cpp
Riordan-DC/B-on
174390c08eddcdfbd0ae7441fc440a32641bcf28
[ "MIT" ]
null
null
null
#include "Beon.hpp" // Window parameters int windowWidth = 1980; int windowHeight = 1080; static bool running = true; //Get a handle on our light //GLuint LightID = glGetUniformLocation(mShader.ID, "LightPosition_worldspace"); // Forward declaration of functions void cleanup(); // Create window manager WindowManager* Manager = WindowManager::getInstance(); int main(int argc, char* argv[]) { if (Manager->initWindow("Beon", windowWidth, windowHeight) == -1) { std::cout << "Window failed to initialize." << std::endl; return -1; }; // Get window from window manager GLFWwindow* window = Manager->getWindow(); // Set GLFW call backs setBasicGLFWCallbacks(window); // Initalise camera controls CameraController controlled_cam(window, glm::vec3(0,10,10)); // Create render view with camera Renderer MainView(controlled_cam.camera, windowWidth, windowHeight); // Initalise Gui GUI::InitGui(window); // Load shaders Shader core_shader = Shader("../Beon/shaders/TransformVertexShader.vert", "../Beon/shaders/TextureFragmentShader.frag"); //Shader crysis_shader = Shader("../Beon/shaders/Toon.vert", "../Beon/shaders/Toon.frag"); Shader mCubmap = Shader("../Beon/shaders/CubeMap.vert", "../Beon/shaders/CubeMap.frag" ); // Load models //Model monkey_model(GetCurrentWorkingDir()+"/../Beon/assets/models/suzanne/suzanne.obj", false); //Model man_model(GetCurrentWorkingDir() + "/../Beon/assets/models/people/Male_Casual.obj", false); //Model crysis_model(GetCurrentWorkingDir() + "/../Beon/assets/models/nanosuit/nanosuit.obj", false); Model cube_model(GetCurrentWorkingDir() + "/../Beon/assets/models/cube/cube.obj", false); Model skybox; skybox.LoadSkyBox(GetCurrentWorkingDir()+"/../Beon/assets/skybox"); mCubmap.use(); mCubmap.setInt("skybox", 0); Object* crysis = new Object(cube_model, 0); crysis->AddShader("texture", core_shader); Object* monkey = new Object(cube_model, 1); monkey->AddShader("basic", core_shader); Object* man = new Object(cube_model, 562); man->AddShader("material", core_shader); Object* floor = new Object(cube_model, 30000); floor->AddShader("material", core_shader); //crysis_shader.use(); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); BulletSystem bulletSystem = StartBulletPhysics(); bulletSystem.dynamicsWorld->setGravity(btVector3(0,-5.1,0)); crysis->mass = 1.0; crysis->InitPhysics(bulletSystem.dynamicsWorld); crysis->SetPosition(glm::vec3(0.0,40.0,0.0)); man->mass = 1.0; man->InitPhysics(bulletSystem.dynamicsWorld); man->SetPosition(glm::vec3(0.0, 70.0,0.0)); monkey->mass = 1.0; monkey->InitPhysics(bulletSystem.dynamicsWorld); monkey->SetPosition(glm::vec3(0.f, 90.0, 0.0)); floor->mass = 0.0; floor->InitPhysics(bulletSystem.dynamicsWorld); floor->SetPosition(glm::vec3(0.0, 0.0, 0.0)); floor->SetScale(glm::vec3(1,10,10)); double lastTime = glfwGetTime(); // Game Loop // while (glfwWindowShouldClose(window) == false && running) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); getDeltaTime(); // UPDATE bulletSystem.dynamicsWorld->stepSimulation( deltaTime, // Time since last step 7, // Mas substep count btScalar(1.) / btScalar(60.)); // Fixed time step crysis->Update(deltaTime); man->Update(deltaTime); monkey->Update(deltaTime); floor->Update(deltaTime); // RENDER GUI::getFrame(); glClearColor(GUI::backgroundColor.x, GUI::backgroundColor.y, GUI::backgroundColor.z, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); MainView.Update(); MainView.UpdateShader(core_shader); core_shader.setBool("dirLight.On", true); core_shader.setVec3("dirLight.direction", glm::vec3(GUI::DirLightDirection.x, GUI::DirLightDirection.y, GUI::DirLightDirection.z)); core_shader.setVec3("dirLight.ambient", glm::vec3(GUI::DirLightAmbientColor.x, GUI::DirLightAmbientColor.y, GUI::DirLightAmbientColor.z)); core_shader.setVec3("dirLight.diffuse", glm::vec3(GUI::DirLightDiffuse, GUI::DirLightDiffuse, GUI::DirLightDiffuse)); core_shader.setVec3("dirLight.specular", glm::vec3(GUI::DirLightSpecular, GUI::DirLightSpecular, GUI::DirLightSpecular)); core_shader.setFloat("dirLight.shininess", GUI::DirLightShininess); core_shader.setBool("pointLights[0].On", false); core_shader.setVec3("pointLights[0].position", controlled_cam.camera->Position); core_shader.setVec3("pointLights[0].ambient", glm::vec3(GUI::DirLightAmbientColor.x, GUI::DirLightAmbientColor.y, GUI::DirLightAmbientColor.z)); core_shader.setVec3("pointLights[0].specular", glm::vec3(GUI::DirLightSpecular, GUI::DirLightSpecular, GUI::DirLightSpecular)); core_shader.setVec3("pointLights[0].diffuse", glm::vec3(GUI::DirLightDiffuse, GUI::DirLightDiffuse, GUI::DirLightDiffuse)); core_shader.setFloat("pointLights[0].quadratic", 0.032f); core_shader.setFloat("pointLights[0].linear", 0.09f); core_shader.setFloat("pointLights[0].constant", 3.0f); crysis->RenderObject(MainView); man->RenderObject(MainView); monkey->RenderObject(MainView); floor->RenderObject(MainView); if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT)) { glm::vec3 out_origin; glm::vec3 out_direction; double xpos, ypos; if (controlled_cam.trackMouse) { xpos = windowWidth / 2; ypos = windowHeight / 2; } else { glfwGetCursorPos(window, &xpos, &ypos); ypos = windowHeight - ypos; } ScreenPosToWorldRay( (int)xpos, (int)ypos, windowWidth, windowHeight, controlled_cam.camera->ViewMatrix, controlled_cam.camera->ProjectionMatrix, out_origin, out_direction ); glm::vec3 out_end = out_origin + out_direction * 1000.0f; btCollisionWorld::ClosestRayResultCallback RayCallback(btVector3(out_origin.x, out_origin.y, out_origin.z), btVector3(out_end.x, out_end.y, out_end.z)); bulletSystem.dynamicsWorld->rayTest(btVector3(out_origin.x, out_origin.y, out_origin.z), btVector3(out_end.x, out_end.y, out_end.z), RayCallback); if (RayCallback.hasHit()) { if (GUI::selected_object) { GUI::selected_object->Selected(false); } GUI::selected_object = (Object*)RayCallback.m_collisionObject->getUserPointer(); GUI::selected_object->Selected(true); //std::cout << "mesh " << GUI::selected_object->entity_tag << std::endl; } else { if (GUI::selected_object) { GUI::selected_object->Selected(false); } //std::cout << "background" << std::endl;; } } if (glfwGetKey(window, GLFW_KEY_TAB) == GLFW_PRESS) { // Escape camera mode GUI::fly_camera = false; } controlled_cam.Update(deltaTime); controlled_cam.trackMouse = GUI::fly_camera; glDepthFunc(GL_LEQUAL); MainView.UpdateShader(mCubmap); //skybox.DrawSkyBox(crysis_shader); skybox.DrawSkyBox(mCubmap); // Render GUI GUI::renderGui(); // In time left over, poll events again. while (glfwGetTime() < lastTime + (1.0 / 60.0)) { // Do nothing continue; } lastTime += (1.0 / 60.0); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) glfwSwapBuffers(window); glfwPollEvents(); } // de-allocate all resources once they've outlived their purpose: delete man; delete monkey; delete floor; delete crysis; GUI::killGui(); DestroyBulletPhysics(&bulletSystem); cleanup(); return 0; } void cleanup() { // Close OpenGL window and terminate GLFW glfwTerminate(); delete Manager; }
34.043668
156
0.685993
f036d2b4c7e72d0bc013732246952863da7336c2
1,773
cpp
C++
roo_material_icons/sharp/18/home.cpp
dejwk/roo_material_icons
f559ce25b6ee2fdf67ed4f8b0bedfce2aaefb885
[ "MIT" ]
null
null
null
roo_material_icons/sharp/18/home.cpp
dejwk/roo_material_icons
f559ce25b6ee2fdf67ed4f8b0bedfce2aaefb885
[ "MIT" ]
null
null
null
roo_material_icons/sharp/18/home.cpp
dejwk/roo_material_icons
f559ce25b6ee2fdf67ed4f8b0bedfce2aaefb885
[ "MIT" ]
null
null
null
#include "home.h" using namespace roo_display; // Image file ic_sharp_18_home_sensor_door 18x18, 4-bit Alpha, RLE, 60 bytes. static const uint8_t ic_sharp_18_home_sensor_door_data[] PROGMEM = { 0x80, 0xC3, 0x00, 0x18, 0x06, 0x30, 0x16, 0x06, 0xFB, 0x06, 0x60, 0x6F, 0xB0, 0x66, 0x06, 0xFB, 0x06, 0x60, 0x6F, 0xB0, 0x66, 0x06, 0xFB, 0x06, 0x60, 0x6E, 0x83, 0xE3, 0xAF, 0x66, 0x06, 0xE8, 0x3E, 0x3A, 0xF6, 0x60, 0x6F, 0xB0, 0x66, 0x06, 0xFB, 0x06, 0x60, 0x6F, 0xB0, 0x66, 0x06, 0xFB, 0x06, 0x60, 0x6F, 0xB0, 0x66, 0x01, 0x80, 0x63, 0x01, 0x80, 0xC3, 0x00, }; const RleImage4bppxBiased<Alpha4, PrgMemResource>& ic_sharp_18_home_sensor_door() { static RleImage4bppxBiased<Alpha4, PrgMemResource> value( 18, 18, ic_sharp_18_home_sensor_door_data, Alpha4(color::Black)); return value; } // Image file ic_sharp_18_home_sensor_window 18x18, 4-bit Alpha, RLE, 94 bytes. static const uint8_t ic_sharp_18_home_sensor_window_data[] PROGMEM = { 0x80, 0xC3, 0x00, 0x18, 0x06, 0x30, 0x16, 0x06, 0x0C, 0x80, 0x49, 0x0C, 0x06, 0x68, 0x16, 0x74, 0x80, 0x27, 0x81, 0x47, 0x66, 0x81, 0x67, 0x9E, 0x81, 0x97, 0x66, 0x81, 0x67, 0x9E, 0x81, 0x97, 0x66, 0x89, 0x26, 0x79, 0xFB, 0x33, 0xBF, 0x97, 0x66, 0x06, 0x07, 0x0F, 0x12, 0x0F, 0x10, 0x70, 0x66, 0x81, 0x67, 0x9E, 0x81, 0x97, 0x66, 0x81, 0x67, 0x9E, 0x81, 0x97, 0x66, 0x81, 0x67, 0x9E, 0x81, 0x97, 0x66, 0x81, 0x67, 0x9E, 0x81, 0x97, 0x66, 0x81, 0x67, 0x48, 0x02, 0x78, 0x14, 0x76, 0x60, 0x60, 0xC8, 0x04, 0x90, 0xC0, 0x66, 0x01, 0x80, 0x63, 0x01, 0x80, 0xC3, 0x00, }; const RleImage4bppxBiased<Alpha4, PrgMemResource>& ic_sharp_18_home_sensor_window() { static RleImage4bppxBiased<Alpha4, PrgMemResource> value( 18, 18, ic_sharp_18_home_sensor_window_data, Alpha4(color::Black)); return value; }
53.727273
97
0.716864
f0377dc35798653f437c55858a0ab0ae28426d9a
4,645
cc
C++
util/fuchsia/koid_utilities.cc
rbxeyl/crashpad
95b4e6276836283a91e18382fb258598bd77f8aa
[ "Apache-2.0" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
util/fuchsia/koid_utilities.cc
rbxeyl/crashpad
95b4e6276836283a91e18382fb258598bd77f8aa
[ "Apache-2.0" ]
113
2019-12-14T04:28:04.000Z
2021-09-26T18:40:27.000Z
util/fuchsia/koid_utilities.cc
rbxeyl/crashpad
95b4e6276836283a91e18382fb258598bd77f8aa
[ "Apache-2.0" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 The Crashpad 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 "util/fuchsia/koid_utilities.h" #include <lib/fdio/fdio.h> #include <lib/zx/channel.h> #include <lib/zx/job.h> #include <lib/zx/process.h> #include <vector> #include "base/files/file_path.h" #include "base/fuchsia/fuchsia_logging.h" #include "util/file/file_io.h" namespace crashpad { namespace { // Casts |handle| into a container of type T, returning a null handle if the // actual handle type does not match that of T. template <typename T> T CastHandle(zx::handle handle) { zx_info_handle_basic_t actual = {}; zx_status_t status = handle.get_info( ZX_INFO_HANDLE_BASIC, &actual, sizeof(actual), nullptr, nullptr); if (status != ZX_OK) { ZX_LOG(ERROR, status) << "zx_object_get_info"; return T(); } if (actual.type != T::TYPE) { LOG(ERROR) << "Wrong type: " << actual.type << ", expected " << T::TYPE; return T(); } return T(std::move(handle)); } // Returns null handle if |koid| is not found or an error occurs. If |was_found| // is non-null then it will be set, to distinguish not-found from other errors. template <typename T, typename U> T GetChildHandleByKoid(const U& parent, zx_koid_t child_koid, bool* was_found) { zx::handle handle; zx_status_t status = parent.get_child(child_koid, ZX_RIGHT_SAME_RIGHTS, &handle); if (was_found) *was_found = (status != ZX_ERR_NOT_FOUND); if (status != ZX_OK) { ZX_LOG(ERROR, status) << "zx_object_get_child"; return T(); } return CastHandle<T>(std::move(handle)); } } // namespace std::vector<zx_koid_t> GetChildKoids(const zx::object_base& parent_object, zx_object_info_topic_t child_kind) { size_t actual = 0; size_t available = 0; std::vector<zx_koid_t> result(100); zx::unowned_handle parent(parent_object.get()); // This is inherently racy. Better if the process is suspended, but there's // still no guarantee that a thread isn't externally created. As a result, // must be in a retry loop. for (;;) { zx_status_t status = parent->get_info(child_kind, result.data(), result.size() * sizeof(zx_koid_t), &actual, &available); // If the buffer is too small (even zero), the result is still ZX_OK, not // ZX_ERR_BUFFER_TOO_SMALL. if (status != ZX_OK) { ZX_LOG(ERROR, status) << "zx_object_get_info"; break; } if (actual == available) { break; } // Resize to the expected number next time, with a bit of slop to handle the // race between here and the next request. result.resize(available + 10); } result.resize(actual); return result; } std::vector<zx::thread> GetThreadHandles(const zx::process& parent) { auto koids = GetChildKoids(parent, ZX_INFO_PROCESS_THREADS); return GetHandlesForThreadKoids(parent, koids); } std::vector<zx::thread> GetHandlesForThreadKoids( const zx::process& parent, const std::vector<zx_koid_t>& koids) { std::vector<zx::thread> result; result.reserve(koids.size()); for (zx_koid_t koid : koids) { result.emplace_back(GetThreadHandleByKoid(parent, koid)); } return result; } zx::thread GetThreadHandleByKoid(const zx::process& parent, zx_koid_t child_koid) { return GetChildHandleByKoid<zx::thread>(parent, child_koid, nullptr); } zx_koid_t GetKoidForHandle(const zx::object_base& object) { zx_info_handle_basic_t info; zx_status_t status = zx_object_get_info(object.get(), ZX_INFO_HANDLE_BASIC, &info, sizeof(info), nullptr, nullptr); if (status != ZX_OK) { ZX_LOG(ERROR, status) << "zx_object_get_info"; return ZX_KOID_INVALID; } return info.koid; } } // namespace crashpad
32.711268
80
0.639182
f039d9bddaa3b8b6064b2f29637a92b5c15b3ba0
108
cpp
C++
src/test/sub.cpp
ifritJP/lctags
dd877c6f6f10b9299c59cfbc05755b7680c7dd80
[ "MIT" ]
17
2017-10-24T15:19:49.000Z
2021-12-19T00:49:48.000Z
src/test/sub.cpp
ifritJP/lctags
dd877c6f6f10b9299c59cfbc05755b7680c7dd80
[ "MIT" ]
1
2021-02-24T15:49:11.000Z
2021-02-26T07:45:05.000Z
src/test/sub.cpp
ifritJP/lctags
dd877c6f6f10b9299c59cfbc05755b7680c7dd80
[ "MIT" ]
1
2017-11-08T17:39:51.000Z
2017-11-08T17:39:51.000Z
#define NNNN #include <./hoge.h> #ifdef VVVVVVV int vvvvv; #endif namespace jjjjj { #include <field.h> }
9
19
0.685185
f040c8b9ee2c07b5d508dcc6f6c41cd4e4cd3511
8,596
hpp
C++
include/codegen/include/Zenject/FactoryFromBinder1Extensions.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Zenject/FactoryFromBinder1Extensions.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Zenject/FactoryFromBinder1Extensions.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:42 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Zenject namespace Zenject { // Forward declaring type: ArgConditionCopyNonLazyBinder class ArgConditionCopyNonLazyBinder; // Forward declaring type: FactoryFromBinder`2<TParam1, TContract> template<typename TParam1, typename TContract> class FactoryFromBinder_2; // Forward declaring type: ConcreteBinderGeneric`1<TContract> template<typename TContract> class ConcreteBinderGeneric_1; // Forward declaring type: IFactory`2<TValue, TParam1> template<typename TValue, typename TParam1> class IFactory_2; // Forward declaring type: IPoolable`2<TParam1, TParam2> template<typename TParam1, typename TParam2> class IPoolable_2; // Forward declaring type: IMemoryPool class IMemoryPool; // Forward declaring type: MemoryPoolInitialSizeMaxSizeBinder`1<TContract> template<typename TContract> class MemoryPoolInitialSizeMaxSizeBinder_1; // Forward declaring type: MemoryPool`3<TValue, TParam1, TParam2> template<typename TValue, typename TParam1, typename TParam2> class MemoryPool_3; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action`1<T> template<typename T> class Action_1; // Forward declaring type: Action`1<T> template<typename T> class Action_1; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Component class Component; } // Completed forward declares // Type namespace: Zenject namespace Zenject { // Autogenerated type: Zenject.FactoryFromBinder1Extensions class FactoryFromBinder1Extensions : public ::Il2CppObject { public: // Nested type: Zenject::FactoryFromBinder1Extensions::$$c__DisplayClass0_0_2<TParam1, TContract> template<typename TParam1, typename TContract> class $$c__DisplayClass0_0_2; // Nested type: Zenject::FactoryFromBinder1Extensions::$$c__1_2<TParam1, TContract> template<typename TParam1, typename TContract> class $$c__1_2; // Nested type: Zenject::FactoryFromBinder1Extensions::$$c__3_2<TParam1, TContract> template<typename TParam1, typename TContract> class $$c__3_2; // Nested type: Zenject::FactoryFromBinder1Extensions::$$c__5_3<TParam1, TContract, TMemoryPool> template<typename TParam1, typename TContract, typename TMemoryPool> class $$c__5_3; // Nested type: Zenject::FactoryFromBinder1Extensions::$$c__DisplayClass6_0_3<TParam1, TContract, TMemoryPool> template<typename TParam1, typename TContract, typename TMemoryPool> class $$c__DisplayClass6_0_3; // static public Zenject.ArgConditionCopyNonLazyBinder FromIFactory(Zenject.FactoryFromBinder`2<TParam1,TContract> fromBinder, System.Action`1<Zenject.ConcreteBinderGeneric`1<Zenject.IFactory`2<TParam1,TContract>>> factoryBindGenerator) // Offset: 0x13D1270 template<class TParam1, class TContract> static Zenject::ArgConditionCopyNonLazyBinder* FromIFactory(Zenject::FactoryFromBinder_2<TParam1, TContract>* fromBinder, System::Action_1<Zenject::ConcreteBinderGeneric_1<Zenject::IFactory_2<TParam1, TContract>*>*>* factoryBindGenerator) { return CRASH_UNLESS(il2cpp_utils::RunGenericMethod<Zenject::ArgConditionCopyNonLazyBinder*>("Zenject", "FactoryFromBinder1Extensions", "FromIFactory", {il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TParam1>::get(), il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TContract>::get()}, fromBinder, factoryBindGenerator)); } // static public Zenject.ArgConditionCopyNonLazyBinder FromPoolableMemoryPool(Zenject.FactoryFromBinder`2<TParam1,TContract> fromBinder) // Offset: 0x13D18B4 template<class TParam1, class TContract> static Zenject::ArgConditionCopyNonLazyBinder* FromPoolableMemoryPool(Zenject::FactoryFromBinder_2<TParam1, TContract>* fromBinder) { static_assert(std::is_convertible_v<TContract, Zenject::IPoolable_2<TParam1, Zenject::IMemoryPool*>*>); return CRASH_UNLESS(il2cpp_utils::RunGenericMethod<Zenject::ArgConditionCopyNonLazyBinder*>("Zenject", "FactoryFromBinder1Extensions", "FromPoolableMemoryPool", {il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TParam1>::get(), il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TContract>::get()}, fromBinder)); } // static public Zenject.ArgConditionCopyNonLazyBinder FromPoolableMemoryPool(Zenject.FactoryFromBinder`2<TParam1,TContract> fromBinder, System.Action`1<Zenject.MemoryPoolInitialSizeMaxSizeBinder`1<TContract>> poolBindGenerator) // Offset: 0x13D1A60 template<class TParam1, class TContract> static Zenject::ArgConditionCopyNonLazyBinder* FromPoolableMemoryPool(Zenject::FactoryFromBinder_2<TParam1, TContract>* fromBinder, System::Action_1<Zenject::MemoryPoolInitialSizeMaxSizeBinder_1<TContract>*>* poolBindGenerator) { static_assert(std::is_convertible_v<TContract, Zenject::IPoolable_2<TParam1, Zenject::IMemoryPool*>*>); return CRASH_UNLESS(il2cpp_utils::RunGenericMethod<Zenject::ArgConditionCopyNonLazyBinder*>("Zenject", "FactoryFromBinder1Extensions", "FromPoolableMemoryPool", {il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TParam1>::get(), il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TContract>::get()}, fromBinder, poolBindGenerator)); } // static public Zenject.ArgConditionCopyNonLazyBinder FromMonoPoolableMemoryPool(Zenject.FactoryFromBinder`2<TParam1,TContract> fromBinder) // Offset: 0x13D139C template<class TParam1, class TContract> static Zenject::ArgConditionCopyNonLazyBinder* FromMonoPoolableMemoryPool(Zenject::FactoryFromBinder_2<TParam1, TContract>* fromBinder) { static_assert(std::is_convertible_v<TContract, UnityEngine::Component*> && std::is_convertible_v<TContract, Zenject::IPoolable_2<TParam1, Zenject::IMemoryPool*>*>); return CRASH_UNLESS(il2cpp_utils::RunGenericMethod<Zenject::ArgConditionCopyNonLazyBinder*>("Zenject", "FactoryFromBinder1Extensions", "FromMonoPoolableMemoryPool", {il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TParam1>::get(), il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TContract>::get()}, fromBinder)); } // static public Zenject.ArgConditionCopyNonLazyBinder FromMonoPoolableMemoryPool(Zenject.FactoryFromBinder`2<TParam1,TContract> fromBinder, System.Action`1<Zenject.MemoryPoolInitialSizeMaxSizeBinder`1<TContract>> poolBindGenerator) // Offset: 0x13D1548 template<class TParam1, class TContract> static Zenject::ArgConditionCopyNonLazyBinder* FromMonoPoolableMemoryPool(Zenject::FactoryFromBinder_2<TParam1, TContract>* fromBinder, System::Action_1<Zenject::MemoryPoolInitialSizeMaxSizeBinder_1<TContract>*>* poolBindGenerator) { static_assert(std::is_convertible_v<TContract, UnityEngine::Component*> && std::is_convertible_v<TContract, Zenject::IPoolable_2<TParam1, Zenject::IMemoryPool*>*>); return CRASH_UNLESS(il2cpp_utils::RunGenericMethod<Zenject::ArgConditionCopyNonLazyBinder*>("Zenject", "FactoryFromBinder1Extensions", "FromMonoPoolableMemoryPool", {il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TParam1>::get(), il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TContract>::get()}, fromBinder, poolBindGenerator)); } // static public Zenject.ArgConditionCopyNonLazyBinder FromPoolableMemoryPool(Zenject.FactoryFromBinder`2<TParam1,TContract> fromBinder) // Offset: 0x13D1558 // ABORTED: conflicts with another method. static Zenject::ArgConditionCopyNonLazyBinder* FromPoolableMemoryPool(Zenject::FactoryFromBinder_2<TParam1, TContract>* fromBinder) // static public Zenject.ArgConditionCopyNonLazyBinder FromPoolableMemoryPool(Zenject.FactoryFromBinder`2<TParam1,TContract> fromBinder, System.Action`1<Zenject.MemoryPoolInitialSizeMaxSizeBinder`1<TContract>> poolBindGenerator) // Offset: 0x13D1704 // ABORTED: conflicts with another method. static Zenject::ArgConditionCopyNonLazyBinder* FromPoolableMemoryPool(Zenject::FactoryFromBinder_2<TParam1, TContract>* fromBinder, System::Action_1<Zenject::MemoryPoolInitialSizeMaxSizeBinder_1<TContract>*>* poolBindGenerator) }; // Zenject.FactoryFromBinder1Extensions } DEFINE_IL2CPP_ARG_TYPE(Zenject::FactoryFromBinder1Extensions*, "Zenject", "FactoryFromBinder1Extensions"); #pragma pack(pop)
73.470085
347
0.79665
f04378c7ee5b0e8ee964c93bb89f07a6b122379e
680
hpp
C++
include/jln/mp/functional/if.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
9
2020-07-04T16:46:13.000Z
2022-01-09T21:59:31.000Z
include/jln/mp/functional/if.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
null
null
null
include/jln/mp/functional/if.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
1
2021-05-23T13:37:40.000Z
2021-05-23T13:37:40.000Z
#pragma once #include <jln/mp/utility/conditional.hpp> #include <jln/mp/utility/always.hpp> #include <jln/mp/number/number.hpp> #include <jln/mp/functional/call.hpp> namespace jln::mp { /// \ingroup functional /// A conditional expression. /// \treturn \value template<class Pred, class TC, class FC = always<false_>> struct if_ { template<class... xs> using f = typename mp::conditional_c<bool(call<Pred, xs...>::value)> ::template f<TC, FC> ::template f<xs...>; }; namespace emp { template<class Pred, class TC, class FC, class... xs> using if_ = typename conditional<call<Pred, xs...>, TC, FC> ::template f<xs...>; } }
22.666667
72
0.636765
f043b2b0fde76b34dd159a94d2ffaa47995915cd
7,135
cpp
C++
src/zxing/zxing/oned/rss/expanded/decoders/FieldParser.cpp
favoritas37/qzxing
6ea2b31e26db9d43db027ba207f5c73dc9d759fc
[ "Apache-2.0" ]
608
2015-02-21T22:31:37.000Z
2022-03-31T05:05:36.000Z
src/zxing/zxing/oned/rss/expanded/decoders/FieldParser.cpp
favoritas37/qzxing
6ea2b31e26db9d43db027ba207f5c73dc9d759fc
[ "Apache-2.0" ]
512
2015-01-06T17:59:31.000Z
2022-03-31T13:21:49.000Z
src/zxing/zxing/oned/rss/expanded/decoders/FieldParser.cpp
favoritas37/qzxing
6ea2b31e26db9d43db027ba207f5c73dc9d759fc
[ "Apache-2.0" ]
281
2016-09-15T08:42:26.000Z
2022-03-21T17:55:00.000Z
#include "FieldParser.h" #include <algorithm> namespace zxing { namespace oned { namespace rss { static const int VARIABLE_LENGTH = 99999; struct DigitData { std::string digit; int variableLength; int length; }; static const DigitData TWO_DIGIT_DATA_LENGTH[] { // "DIGITS", new Integer(LENGTH) // or // "DIGITS", VARIABLE_LENGTH, new Integer(MAX_SIZE) { "00", 18, 0}, { "01", 14, 0}, { "02", 14, 0}, { "10", VARIABLE_LENGTH, 20}, { "11", 6, 0}, { "12", 6, 0}, { "13", 6, 0}, { "15", 6, 0}, { "17", 6, 0}, { "20", 2, 0}, { "21", VARIABLE_LENGTH, 20}, { "22", VARIABLE_LENGTH, 29}, { "30", VARIABLE_LENGTH, 8}, { "37", VARIABLE_LENGTH, 8}, //internal company codes { "90", VARIABLE_LENGTH, 30}, { "91", VARIABLE_LENGTH, 30}, { "92", VARIABLE_LENGTH, 30}, { "93", VARIABLE_LENGTH, 30}, { "94", VARIABLE_LENGTH, 30}, { "95", VARIABLE_LENGTH, 30}, { "96", VARIABLE_LENGTH, 30}, { "97", VARIABLE_LENGTH, 30}, { "98", VARIABLE_LENGTH, 30}, { "99", VARIABLE_LENGTH, 30}, }; static const DigitData THREE_DIGIT_DATA_LENGTH[] { // Same format as above { "240", VARIABLE_LENGTH, 30}, { "241", VARIABLE_LENGTH, 30}, { "242", VARIABLE_LENGTH, 6}, { "250", VARIABLE_LENGTH, 30}, { "251", VARIABLE_LENGTH, 30}, { "253", VARIABLE_LENGTH, 17}, { "254", VARIABLE_LENGTH, 20}, { "400", VARIABLE_LENGTH, 30}, { "401", VARIABLE_LENGTH, 30}, { "402", 17, 0}, { "403", VARIABLE_LENGTH, 30}, { "410", 13, 0}, { "411", 13, 0}, { "412", 13, 0}, { "413", 13, 0}, { "414", 13, 0}, { "420", VARIABLE_LENGTH, 20}, { "421", VARIABLE_LENGTH, 15}, { "422", 3, 0}, { "423", VARIABLE_LENGTH, 15}, { "424", 3, 0}, { "425", 3, 0}, { "426", 3, 0}, }; static const DigitData THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH[] { // Same format as above { "310", 6, 0}, { "311", 6, 0}, { "312", 6, 0}, { "313", 6, 0}, { "314", 6, 0}, { "315", 6, 0}, { "316", 6, 0}, { "320", 6, 0}, { "321", 6, 0}, { "322", 6, 0}, { "323", 6, 0}, { "324", 6, 0}, { "325", 6, 0}, { "326", 6, 0}, { "327", 6, 0}, { "328", 6, 0}, { "329", 6, 0}, { "330", 6, 0}, { "331", 6, 0}, { "332", 6, 0}, { "333", 6, 0}, { "334", 6, 0}, { "335", 6, 0}, { "336", 6, 0}, { "340", 6, 0}, { "341", 6, 0}, { "342", 6, 0}, { "343", 6, 0}, { "344", 6, 0}, { "345", 6, 0}, { "346", 6, 0}, { "347", 6, 0}, { "348", 6, 0}, { "349", 6, 0}, { "350", 6, 0}, { "351", 6, 0}, { "352", 6, 0}, { "353", 6, 0}, { "354", 6, 0}, { "355", 6, 0}, { "356", 6, 0}, { "357", 6, 0}, { "360", 6, 0}, { "361", 6, 0}, { "362", 6, 0}, { "363", 6, 0}, { "364", 6, 0}, { "365", 6, 0}, { "366", 6, 0}, { "367", 6, 0}, { "368", 6, 0}, { "369", 6, 0}, { "390", VARIABLE_LENGTH, 15}, { "391", VARIABLE_LENGTH, 18}, { "392", VARIABLE_LENGTH, 15}, { "393", VARIABLE_LENGTH, 18}, { "703", VARIABLE_LENGTH, 30}, }; static const DigitData FOUR_DIGIT_DATA_LENGTH[] { // Same format as above { "7001", 13, 0}, { "7002", VARIABLE_LENGTH, 30}, { "7003", 10, 0}, { "8001", 14, 0}, { "8002", VARIABLE_LENGTH, 20}, { "8003", VARIABLE_LENGTH, 30}, { "8004", VARIABLE_LENGTH, 30}, { "8005", 6, 0}, { "8006", 18, 0}, { "8007", VARIABLE_LENGTH, 30}, { "8008", VARIABLE_LENGTH, 12}, { "8018", 18, 0}, { "8020", VARIABLE_LENGTH, 25}, { "8100", 6, 0}, { "8101", 10, 0}, { "8102", 2, 0}, { "8110", VARIABLE_LENGTH, 70}, { "8200", VARIABLE_LENGTH, 70}, }; String FieldParser::parseFieldsInGeneralPurpose(String rawInformation) { if (rawInformation.getText().empty()) { return String(""); } // Processing 2-digit AIs if (rawInformation.length() < 2) { throw NotFoundException(); } String firstTwoDigits(rawInformation.substring(0, 2)->getText()); for (DigitData dataLength : TWO_DIGIT_DATA_LENGTH) { if (dataLength.digit == firstTwoDigits.getText()) { if (dataLength.variableLength == VARIABLE_LENGTH) { return processVariableAI(2, dataLength.length, rawInformation); } return processFixedAI(2, dataLength.variableLength, rawInformation); } } if (rawInformation.length() < 3) { throw NotFoundException(); } String firstThreeDigits(rawInformation.substring(0, 3)->getText()); for (DigitData dataLength : THREE_DIGIT_DATA_LENGTH) { if (dataLength.digit == firstThreeDigits.getText()) { if (dataLength.variableLength == VARIABLE_LENGTH) { return processVariableAI(3, dataLength.length, rawInformation); } return processFixedAI(3, dataLength.variableLength, rawInformation); } } for (DigitData dataLength : THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH) { if (dataLength.digit == firstThreeDigits.getText()) { if (dataLength.variableLength == VARIABLE_LENGTH) { return processVariableAI(4, dataLength.length, rawInformation); } return processFixedAI(4, dataLength.variableLength, rawInformation); } } if (rawInformation.length() < 4) { throw NotFoundException(); } String firstFourDigits(rawInformation.substring(0, 4)->getText()); for (DigitData dataLength : FOUR_DIGIT_DATA_LENGTH) { if (dataLength.digit == firstFourDigits.getText()) { if (dataLength.variableLength == VARIABLE_LENGTH) { return processVariableAI(4, dataLength.length, rawInformation); } return processFixedAI(4, dataLength.variableLength, rawInformation); } } throw NotFoundException(); } String FieldParser::processFixedAI(int aiSize, int fieldSize, String rawInformation) { if (rawInformation.length() < aiSize) { throw NotFoundException(); } String ai(rawInformation.substring(0, aiSize)->getText()); if (rawInformation.length() < aiSize + fieldSize) { throw NotFoundException(); } String field(rawInformation.substring(aiSize, /*aiSize +*/ fieldSize)->getText()); String remaining(rawInformation.substring(aiSize + fieldSize)->getText()); String result('(' + ai.getText() + ')' + field.getText()); String parsedAI = parseFieldsInGeneralPurpose(remaining); if (parsedAI.getText() == "") { return result; } else { result.append(parsedAI.getText()); return result; } } String FieldParser::processVariableAI(int aiSize, int variableFieldSize, String rawInformation) { String ai(rawInformation.substring(0, aiSize)->getText()); int maxSize = std::min(rawInformation.length(), aiSize + variableFieldSize); String field(rawInformation.substring(aiSize, maxSize - aiSize)->getText()); String remaining(rawInformation.substring(maxSize)->getText()); String result('(' + ai.getText() + ')' + field.getText()); String parsedAI = parseFieldsInGeneralPurpose(remaining); if (parsedAI.getText() == "") { return result; } else { result.append(parsedAI.getText()); return result; } } } } }
25.758123
95
0.571829
f045c323aed5df511f3059cb6ecfa62ee27afcee
1,198
hh
C++
GameLogic/Engine/piecefactory.hh
saarioka/Saaripeli
28145e49b4708e22fb7cb051c1ccddfa4a6a24f9
[ "MIT" ]
null
null
null
GameLogic/Engine/piecefactory.hh
saarioka/Saaripeli
28145e49b4708e22fb7cb051c1ccddfa4a6a24f9
[ "MIT" ]
null
null
null
GameLogic/Engine/piecefactory.hh
saarioka/Saaripeli
28145e49b4708e22fb7cb051c1ccddfa4a6a24f9
[ "MIT" ]
null
null
null
#ifndef PIECEFACTORY_HH #define PIECEFACTORY_HH #include <QJsonObject> #include <string> #include <vector> /** * @file * @brief Singleton class that creates pieces. */ namespace Logic { /** * @brief Singleton class for creating pieces. * * The factory is requested to read JSON file, after which it will requested to * return a data structure, which containts the read pieces. */ class PieceFactory { public: /** * @return A reference to the factory. */ static PieceFactory& getInstance(); /** * @brief readJSON reads pieces a JSON file. * @exception IOException Could not open the file Assets/pieces.json for reading. * @exception FormatException Format of the file Assets/pieces.json is invalid. * @post Exception quarantee: basic */ void readJSON(); /** * @brief Gets the pieces used in the game * @return The pieces read from the JSON file. If the file is not read, or the actors did not exist, will return an empty vector. * @post Exception quarantee: basic */ std::vector<std::pair<std::string,int>> getGamePieces() const; private: PieceFactory(); QJsonObject _json; }; } #endif
21.392857
133
0.673623
f04c4f700ec089a967ffa9bfa9b5e02c7dfa42ff
1,413
hpp
C++
lib/include/interlinck/Core/Syntax/IWithSimplifiedWidthAndPosition.hpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
null
null
null
lib/include/interlinck/Core/Syntax/IWithSimplifiedWidthAndPosition.hpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
50
2021-06-30T20:01:50.000Z
2021-11-28T16:21:26.000Z
lib/include/interlinck/Core/Syntax/IWithSimplifiedWidthAndPosition.hpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
null
null
null
#ifndef INTERLINCK_CORE_SYNTAX_IWITHSIMPLIFIEDWIDTHANDPOSITION_H #define INTERLINCK_CORE_SYNTAX_IWITHSIMPLIFIEDWIDTHANDPOSITION_H #include "interlinck/interlinck_global.hpp" #include "interlinck/Core/Text/TextSpan.hpp" #include "interlinck/Core/Types.hpp" namespace interlinck::Core::Syntax { /** * @brief Interface providing functions regarding positions and widths of syntax elements without trivia. */ class INTERLINCK_API IWithSimplifiedWidthAndPosition { public: virtual ~IWithSimplifiedWidthAndPosition() noexcept = default; /** * @brief Returns the width of the syntax elements. * @return The width of the syntax elements. */ virtual il_size width() const noexcept = 0; /** * @brief Returns the position of the syntax element. * @return The position of the syntax element. */ virtual il_size position() const noexcept = 0; /** * @brief Returns the position at which the syntax element ends. * @return The position at which the syntax element ends. */ virtual il_size endPosition() const noexcept = 0; /** * @brief Returns the <code>TextSpan</code> for the syntax element. * @return The <code>TextSpan</code> for the syntax element. */ virtual Text::TextSpan span() const noexcept = 0; }; } // end namespace interlinck::Core::Syntax #endif // INTERLINCK_CORE_SYNTAX_IWITHSIMPLIFIEDWIDTHANDPOSITION_H
30.06383
105
0.726115
f04dea21f0d983027c7a935bca810fd5ba8b0309
8,835
hpp
C++
src/core/imports/blas/Ger.hpp
pjt1988/Elemental
71d3e2b98829594e9f52980a8b1ef7c1e99c724b
[ "Apache-2.0" ]
473
2015-01-11T03:22:11.000Z
2022-03-31T05:28:39.000Z
src/core/imports/blas/Ger.hpp
pjt1988/Elemental
71d3e2b98829594e9f52980a8b1ef7c1e99c724b
[ "Apache-2.0" ]
205
2015-01-10T20:33:45.000Z
2021-07-25T14:53:25.000Z
src/core/imports/blas/Ger.hpp
pjt1988/Elemental
71d3e2b98829594e9f52980a8b1ef7c1e99c724b
[ "Apache-2.0" ]
109
2015-02-16T14:06:42.000Z
2022-03-23T21:34:26.000Z
/* Copyright (c) 2009-2016, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ extern "C" { void EL_BLAS(sger) ( const BlasInt* m, const BlasInt* n, const float* alpha, const float* x, const BlasInt* incx, const float* y, const BlasInt* incy, float* A, const BlasInt* ALDim ); void EL_BLAS(dger) ( const BlasInt* m, const BlasInt* n, const double* alpha, const double* x, const BlasInt* incx, const double* y, const BlasInt* incy, double* A, const BlasInt* ALDim ); void EL_BLAS(cgerc) ( const BlasInt* m, const BlasInt* n, const scomplex* alpha, const scomplex* x, const BlasInt* incx, const scomplex* y, const BlasInt* incy, scomplex* A, const BlasInt* ALDim ); void EL_BLAS(zgerc) ( const BlasInt* m, const BlasInt* n, const dcomplex* alpha, const dcomplex* x, const BlasInt* incx, const dcomplex* y, const BlasInt* incy, dcomplex* A, const BlasInt* ALDim ); void EL_BLAS(cgeru) ( const BlasInt* m, const BlasInt* n, const scomplex* alpha, const scomplex* x, const BlasInt* incx, const scomplex* y, const BlasInt* incy, scomplex* A, const BlasInt* ALDim ); void EL_BLAS(zgeru) ( const BlasInt* m, const BlasInt* n, const dcomplex* alpha, const dcomplex* x, const BlasInt* incx, const dcomplex* y, const BlasInt* incy, dcomplex* A, const BlasInt* ALDim ); } // extern "C" namespace El { namespace blas { template<typename T> void Ger ( BlasInt m, BlasInt n, const T& alpha, const T* x, BlasInt incx, const T* y, BlasInt incy, T* A, BlasInt ALDim ) { // NOTE: Temporaries are avoided since constructing a BigInt/BigFloat // involves a memory allocation // TODO: Special-case alpha=0? T gamma, delta; for( BlasInt j=0; j<n; ++j ) { Conj( y[j*incy], gamma ); gamma *= alpha; for( BlasInt i=0; i<m; ++i ) { // A[i+j*ALDim] += alpha*x[i*incx]*Conj(y[j*incy]); delta = x[i*incx]; delta *= gamma; A[i+j*ALDim] += delta; } } } template void Ger ( BlasInt m, BlasInt n, const Int& alpha, const Int* x, BlasInt incx, const Int* y, BlasInt incy, Int* A, BlasInt ALDim ); #ifdef EL_HAVE_QD template void Ger ( BlasInt m, BlasInt n, const DoubleDouble& alpha, const DoubleDouble* x, BlasInt incx, const DoubleDouble* y, BlasInt incy, DoubleDouble* A, BlasInt ALDim ); template void Ger ( BlasInt m, BlasInt n, const QuadDouble& alpha, const QuadDouble* x, BlasInt incx, const QuadDouble* y, BlasInt incy, QuadDouble* A, BlasInt ALDim ); template void Ger ( BlasInt m, BlasInt n, const Complex<DoubleDouble>& alpha, const Complex<DoubleDouble>* x, BlasInt incx, const Complex<DoubleDouble>* y, BlasInt incy, Complex<DoubleDouble>* A, BlasInt ALDim ); template void Ger ( BlasInt m, BlasInt n, const Complex<QuadDouble>& alpha, const Complex<QuadDouble>* x, BlasInt incx, const Complex<QuadDouble>* y, BlasInt incy, Complex<QuadDouble>* A, BlasInt ALDim ); #endif #ifdef EL_HAVE_QUAD template void Ger ( BlasInt m, BlasInt n, const Quad& alpha, const Quad* x, BlasInt incx, const Quad* y, BlasInt incy, Quad* A, BlasInt ALDim ); template void Ger ( BlasInt m, BlasInt n, const Complex<Quad>& alpha, const Complex<Quad>* x, BlasInt incx, const Complex<Quad>* y, BlasInt incy, Complex<Quad>* A, BlasInt ALDim ); #endif #ifdef EL_HAVE_MPC template void Ger ( BlasInt m, BlasInt n, const BigInt& alpha, const BigInt* x, BlasInt incx, const BigInt* y, BlasInt incy, BigInt* A, BlasInt ALDim ); template void Ger ( BlasInt m, BlasInt n, const BigFloat& alpha, const BigFloat* x, BlasInt incx, const BigFloat* y, BlasInt incy, BigFloat* A, BlasInt ALDim ); template void Ger ( BlasInt m, BlasInt n, const Complex<BigFloat>& alpha, const Complex<BigFloat>* x, BlasInt incx, const Complex<BigFloat>* y, BlasInt incy, Complex<BigFloat>* A, BlasInt ALDim ); #endif void Ger ( BlasInt m, BlasInt n, const float& alpha, const float* x, BlasInt incx, const float* y, BlasInt incy, float* A, BlasInt ALDim ) { EL_BLAS(sger)( &m, &n, &alpha, x, &incx, y, &incy, A, &ALDim ); } void Ger ( BlasInt m, BlasInt n, const double& alpha, const double* x, BlasInt incx, const double* y, BlasInt incy, double* A, BlasInt ALDim ) { EL_BLAS(dger)( &m, &n, &alpha, x, &incx, y, &incy, A, &ALDim ); } void Ger ( BlasInt m, BlasInt n, const scomplex& alpha, const scomplex* x, BlasInt incx, const scomplex* y, BlasInt incy, scomplex* A, BlasInt ALDim ) { EL_BLAS(cgerc)( &m, &n, &alpha, x, &incx, y, &incy, A, &ALDim ); } void Ger ( BlasInt m, BlasInt n, const dcomplex& alpha, const dcomplex* x, BlasInt incx, const dcomplex* y, BlasInt incy, dcomplex* A, BlasInt ALDim ) { EL_BLAS(zgerc)( &m, &n, &alpha, x, &incx, y, &incy, A, &ALDim ); } template<typename T> void Geru ( BlasInt m, BlasInt n, const T& alpha, const T* x, BlasInt incx, const T* y, BlasInt incy, T* A, BlasInt ALDim ) { // NOTE: Temporaries are avoided since constructing a BigInt/BigFloat // involves a memory allocation // TODO: Special-case alpha=0? T gamma, delta; for( BlasInt j=0; j<n; ++j ) { gamma = y[j*incy]; gamma *= alpha; for( BlasInt i=0; i<m; ++i ) { // A[i+j*ALDim] += alpha*x[i*incx]*y[j*incy]; delta = x[i*incx]; delta *= gamma; A[i+j*ALDim] += delta; } } } template void Geru ( BlasInt m, BlasInt n, const Int& alpha, const Int* x, BlasInt incx, const Int* y, BlasInt incy, Int* A, BlasInt ALDim ); #ifdef EL_HAVE_QD template void Geru ( BlasInt m, BlasInt n, const DoubleDouble& alpha, const DoubleDouble* x, BlasInt incx, const DoubleDouble* y, BlasInt incy, DoubleDouble* A, BlasInt ALDim ); template void Geru ( BlasInt m, BlasInt n, const QuadDouble& alpha, const QuadDouble* x, BlasInt incx, const QuadDouble* y, BlasInt incy, QuadDouble* A, BlasInt ALDim ); template void Geru ( BlasInt m, BlasInt n, const Complex<DoubleDouble>& alpha, const Complex<DoubleDouble>* x, BlasInt incx, const Complex<DoubleDouble>* y, BlasInt incy, Complex<DoubleDouble>* A, BlasInt ALDim ); template void Geru ( BlasInt m, BlasInt n, const Complex<QuadDouble>& alpha, const Complex<QuadDouble>* x, BlasInt incx, const Complex<QuadDouble>* y, BlasInt incy, Complex<QuadDouble>* A, BlasInt ALDim ); #endif #ifdef EL_HAVE_QUAD template void Geru ( BlasInt m, BlasInt n, const Quad& alpha, const Quad* x, BlasInt incx, const Quad* y, BlasInt incy, Quad* A, BlasInt ALDim ); template void Geru ( BlasInt m, BlasInt n, const Complex<Quad>& alpha, const Complex<Quad>* x, BlasInt incx, const Complex<Quad>* y, BlasInt incy, Complex<Quad>* A, BlasInt ALDim ); #endif #ifdef EL_HAVE_MPC template void Geru ( BlasInt m, BlasInt n, const BigInt& alpha, const BigInt* x, BlasInt incx, const BigInt* y, BlasInt incy, BigInt* A, BlasInt ALDim ); template void Geru ( BlasInt m, BlasInt n, const BigFloat& alpha, const BigFloat* x, BlasInt incx, const BigFloat* y, BlasInt incy, BigFloat* A, BlasInt ALDim ); template void Geru ( BlasInt m, BlasInt n, const Complex<BigFloat>& alpha, const Complex<BigFloat>* x, BlasInt incx, const Complex<BigFloat>* y, BlasInt incy, Complex<BigFloat>* A, BlasInt ALDim ); #endif void Geru ( BlasInt m, BlasInt n, const float& alpha, const float* x, BlasInt incx, const float* y, BlasInt incy, float* A, BlasInt ALDim ) { EL_BLAS(sger)( &m, &n, &alpha, x, &incx, y, &incy, A, &ALDim ); } void Geru ( BlasInt m, BlasInt n, const double& alpha, const double* x, BlasInt incx, const double* y, BlasInt incy, double* A, BlasInt ALDim ) { EL_BLAS(dger)( &m, &n, &alpha, x, &incx, y, &incy, A, &ALDim ); } void Geru ( BlasInt m, BlasInt n, const scomplex& alpha, const scomplex* x, BlasInt incx, const scomplex* y, BlasInt incy, scomplex* A, BlasInt ALDim ) { EL_BLAS(cgeru)( &m, &n, &alpha, x, &incx, y, &incy, A, &ALDim ); } void Geru ( BlasInt m, BlasInt n, const dcomplex& alpha, const dcomplex* x, BlasInt incx, const dcomplex* y, BlasInt incy, dcomplex* A, BlasInt ALDim ) { EL_BLAS(zgeru)( &m, &n, &alpha, x, &incx, y, &incy, A, &ALDim ); } } // namespace blas } // namespace El
29.158416
73
0.637917
f0536743f2f27114eb1aa65d2d52739f363aad92
1,111
cpp
C++
UVA/11582/17163602_AC_970ms_0kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
UVA/11582/17163602_AC_970ms_0kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
UVA/11582/17163602_AC_970ms_0kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
/** * @author Moe_Sakiya sakiya@tun.moe * @date 2018-11-24 14:58:37 * */ #include <iostream> #include <string> #include <algorithm> #include <set> #include <map> #include <vector> #include <stack> #include <queue> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> using namespace std; const int maxN = 10005; unsigned long long int fac[maxN]; unsigned long long int pm(unsigned long long int a, unsigned long long int b, unsigned long long int c) { unsigned long long int tmp = 1 % c; a = a % c; while (b > 0) { if (b % 2 == 1) tmp = (tmp * a) % c; b /= 2; a = (a * a) % c; } return tmp; } int main(void) { unsigned long long int t, n, mod = 0; unsigned long long int x, y; cin >> t; while (t--) { cin >> x >> y >> n; fac[0] = 0; fac[1] = 1 % n; for (int i = 2; i < maxN; i++) fac[i] = (fac[i - 1] + fac[i - 2]) % n; for (int i = 4; i < maxN - 10; i++) if (fac[1] == fac[i] && fac[2] == fac[i + 1] && fac[3] == fac[i + 2] && fac[4] == fac[i + 3]){ mod = i; break; } mod--; cout << fac[pm(x, y, mod)] << endl; } return 0; }
19.155172
105
0.545455
f0573ae4797675834357ceed30a2b0960325ab6e
1,281
hpp
C++
src/memory/Array.hpp
LU15W1R7H/lwirth-lib
f51cfb56b801790c200cea64d226730449d68f53
[ "MIT" ]
2
2018-04-04T17:26:32.000Z
2020-06-26T09:22:49.000Z
src/memory/Array.hpp
LU15W1R7H/lwirth-lib
f51cfb56b801790c200cea64d226730449d68f53
[ "MIT" ]
1
2018-08-27T14:35:45.000Z
2018-08-27T19:00:12.000Z
src/memory/Array.hpp
LU15W1R7H/lwirth-lib
f51cfb56b801790c200cea64d226730449d68f53
[ "MIT" ]
null
null
null
#pragma once #include "../Standard.hpp" #include <utility> #include <initializer_list> namespace lw { template<class T, size_t SIZE> class Array { private: T m_pData[SIZE]; public: constexpr Array() : m_pData{} { } constexpr Array(const std::initializer_list<T>& il) { static_assert(il.end() - il.begin() == SIZE, "Wrong length"); size_t i = 0; for (auto iter = 0; iter != il.end(); iter++) { m_pData[i] = *iter; i++; } } Array(Array<T, SIZE> const& other) { std::copy(other.m_pData, other.m_pData + SIZE, m_pData); } Array(Array<T, SIZE>&& other) { for (size_t i = 0; i < SIZE; i++) { m_pData[i] = std::move(other.m_pData[i]); } } Array& operator=(Array<T, SIZE> const& other) { std::copy(other.m_pData, other.m_pData + LENGTH, m_pData); return *this; } Array& operator=(Array<T, LENGTH>&& other) { for (size_t i = 0; i < LENGTH; i++) { m_pData[i] = std::move(other.m_pData[i]); } return *this; } ~Array() { } T& operator[](u32 index) { return m_pData[index]; } T const& operator[](u32 index) const { return m_pData[index]; } constexpr u32 size() const { return LENGTH; } T* raw() const { return m_pData; } }; }
14.233333
64
0.569087
f05afcaf3ed05ba253818a720fa5abcfd082bd35
261
cc
C++
test/mocks/grpc/mocks.cc
htuch/envoy
f466a86e4bba81c18f5b59f0c56ea36aa663e174
[ "Apache-2.0" ]
2
2017-07-31T15:03:19.000Z
2018-02-20T16:18:49.000Z
test/mocks/grpc/mocks.cc
htuch/envoy
f466a86e4bba81c18f5b59f0c56ea36aa663e174
[ "Apache-2.0" ]
null
null
null
test/mocks/grpc/mocks.cc
htuch/envoy
f466a86e4bba81c18f5b59f0c56ea36aa663e174
[ "Apache-2.0" ]
null
null
null
#include "mocks.h" namespace Envoy { namespace Grpc { MockRpcChannelCallbacks::MockRpcChannelCallbacks() {} MockRpcChannelCallbacks::~MockRpcChannelCallbacks() {} MockRpcChannel::MockRpcChannel() {} MockRpcChannel::~MockRpcChannel() {} } // Grpc } // Envoy
18.642857
54
0.754789
f05c0ab5100891ab71ff4d255acf39c1eb3592cd
1,426
cpp
C++
Algorithms/lab1/QuickSort_1.0.cpp
chaohu/Daily-Learning
0e8d14a3497ad319eda20bc4682cec08d5d6fb08
[ "MIT" ]
12
2016-04-09T15:43:02.000Z
2022-03-22T01:58:25.000Z
Algorithms/lab1/QuickSort_1.0.cpp
chaohu/Daily-Learning
0e8d14a3497ad319eda20bc4682cec08d5d6fb08
[ "MIT" ]
null
null
null
Algorithms/lab1/QuickSort_1.0.cpp
chaohu/Daily-Learning
0e8d14a3497ad319eda20bc4682cec08d5d6fb08
[ "MIT" ]
2
2018-08-23T07:34:59.000Z
2019-06-20T10:17:31.000Z
#include <iostream> #include <stack> using namespace std; #define MAX 0x7FFFFFFF int PARTITION(int p,int j); stack<int> s; //栈s,存储较大的部分的编号 int *A; //待分类的数据(1:n) int main() { int n = 0,i = 0,j = 0; int p = 0,q = 0,x = 0,y = 0; cout<<"输入待分类数据个数:"; cin>>n; A = (int *)malloc(sizeof(int) * (n + 2)); A[n+1] = MAX; cout<<"输入待分类数据:"; for(i = 1;i <= n;i++) cin>>A[i]; cout<<"输入分类区域(1-"<<n<<"):"; cin>>p>>q; x = p; y = q; while(1) { while(p < q) { j = q + 1; j = PARTITION(p,j); if(j - p < q - j) { s.push(j + 1); s.push(q); q = j - 1; } else { s.push(p); s.push(j - 1); p = j + 1; } } if(s.empty()) break; else { q = s.top(); s.pop(); p = s.top(); s.pop(); } } for(i = x;i <= y;i++) cout<<A[i]<<' '; cout<<'\n'; return 1; } int PARTITION(int m,int p) { int i = 0,v = 0,temp = 0; v = A[m]; i = m; while(1) { do i = i + 1; while(A[i] < v); do p = p - 1; while(A[p] > v); if(i < p) { temp = A[i]; A[i] = A[p]; A[p] = temp; } else break; } A[m] = A[p]; A[p] = v; return p; }
19.805556
45
0.3331
f05d0fb0bad04d57d1e34c6959370d81a322c039
3,847
cpp
C++
BlackVision/LibBlackVision/Source/Engine/Types/Values/ValuesFactory.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
1
2022-01-28T11:43:47.000Z
2022-01-28T11:43:47.000Z
BlackVision/LibBlackVision/Source/Engine/Types/Values/ValuesFactory.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
null
null
null
BlackVision/LibBlackVision/Source/Engine/Types/Values/ValuesFactory.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ValuesFactory.h" namespace bv { // *********************** // ValueBoolPtr ValuesFactory::CreateValueBool ( const std::string & name ) { return std::make_shared< ValueBool >( name ); } // *********************** // ValueBoolPtr ValuesFactory::CreateValueBool ( const std::string & name, bool initVal ) { auto val = CreateValueBool( name ); val->SetValue( initVal ); return val; } // ******************************* // ValueIntPtr ValuesFactory::CreateValueInt ( const std::string & name ) { return std::make_shared< ValueInt >( name ); } // ******************************* // ValueIntPtr ValuesFactory::CreateValueInt ( const std::string & name, Int32 initVal ) { auto val = CreateValueInt( name ); val->SetValue( initVal ); return val; } // ******************************* // ValueFloatPtr ValuesFactory::CreateValueFloat ( const std::string & name ) { return std::make_shared< ValueFloat >( name ); } // ******************************* // ValueFloatPtr ValuesFactory::CreateValueFloat ( const std::string & name, Float32 initVal ) { auto val = CreateValueFloat( name ); val ->SetValue( initVal ); return val; } // ******************************* // ValueDoublePtr ValuesFactory::CreateValueDouble ( const std::string & name ) { return std::make_shared< ValueDouble >( name ); } // ******************************* // ValueDoublePtr ValuesFactory::CreateValueDouble ( const std::string & name, Float64 initVal ) { auto val = CreateValueDouble( name ); val->SetValue( initVal ); return val; } // ******************************* // ValueVec2Ptr ValuesFactory::CreateValueVec2 ( const std::string & name ) { return std::make_shared< ValueVec2 >( name ); } // ******************************* // ValueVec3Ptr ValuesFactory::CreateValueVec3 ( const std::string & name ) { return std::make_shared< ValueVec3 >( name ); } // ******************************* // ValueVec4Ptr ValuesFactory::CreateValueVec4 ( const std::string & name ) { return std::make_shared< ValueVec4 >( name ); } // ******************************* // ValueVec4Ptr ValuesFactory::CreateValueVec4 ( const std::string & name, const glm::vec4 & initVal ) { auto val = CreateValueVec4( name ); val->SetValue( initVal ); return val; } // ******************************* // ValueMat2Ptr ValuesFactory::CreateValueMat2 ( const std::string & name ) { return std::make_shared< ValueMat2 >( name ); } // ******************************* // ValueMat4Ptr ValuesFactory::CreateValueMat4 ( const std::string & name ) { return std::make_shared< ValueMat4 >( name ); } // ******************************* // ValueStringPtr ValuesFactory::CreateValueString ( const std::string & name ) { return std::make_shared< ValueString >( name ); } // ******************************* // ValueStringPtr ValuesFactory::CreateValueString ( const std::string & name, const std::string & initVal ) { auto val = CreateValueString( name ); val->SetValue( initVal ); return val; } // ******************************* // ValueWStringPtr ValuesFactory::CreateValueWString ( const std::string & name ) { return std::make_shared< ValueWString >( name ); } // ******************************* // ValueWStringPtr ValuesFactory::CreateValueWString( const std::string & name, const std::wstring & initVal ) { auto val = CreateValueWString( name ); val->SetValue( initVal ); return val; } } // bv
23.601227
115
0.514947
f05e815d93655bacfc70fe1ce478ee32625984dd
881
cpp
C++
src/functions.cpp
cbries/tetrisgl
a40f22140d05c2cf6116946459a99a0477c1569a
[ "MIT" ]
1
2015-02-23T19:06:04.000Z
2015-02-23T19:06:04.000Z
src/functions.cpp
cbries/tetrisgl
a40f22140d05c2cf6116946459a99a0477c1569a
[ "MIT" ]
null
null
null
src/functions.cpp
cbries/tetrisgl
a40f22140d05c2cf6116946459a99a0477c1569a
[ "MIT" ]
null
null
null
/* * Copyright (c) 2008 Christian Benjamin Ries * License: MIT * Website: https://github.com/cbries/tetrisgl */ #include "functions.h" #include <GL/gl.h> void Enter2DMode( int startx, int starty, int width, int height ) { glPushAttrib(GL_ENABLE_BIT); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glViewport(startx, starty, width, height); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho((GLdouble)startx, (GLdouble)width, (GLdouble)starty, (GLdouble)height, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); } void Leave2DMode() { glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); }
21.487805
92
0.702611
f0616ccc3e6e3633664c0f16c8791c09aeb718d5
549
cpp
C++
C++/Cracking-the-Coding-Interview/1.3.cpp
dvt32/cpp-journey
afd7db7a1ad106c41601fb09e963902187ae36e6
[ "MIT" ]
1
2018-05-24T11:30:05.000Z
2018-05-24T11:30:05.000Z
C++/Cracking-the-Coding-Interview/1.3.cpp
dvt32/cpp-journey
afd7db7a1ad106c41601fb09e963902187ae36e6
[ "MIT" ]
null
null
null
C++/Cracking-the-Coding-Interview/1.3.cpp
dvt32/cpp-journey
afd7db7a1ad106c41601fb09e963902187ae36e6
[ "MIT" ]
2
2017-08-11T06:53:30.000Z
2017-08-29T12:07:52.000Z
// Design an algorithm and write code to remove the duplicate characters in a string. #include <iostream> #include <string> #include <unordered_map> int main() { std::string input = "aabbccd"; std::string output = ""; std::unordered_map<char, int> numberOfInstances; for (int i = 0; i < input.length(); ++i) { char currentCharacter = input[i]; numberOfInstances[currentCharacter]++; if (numberOfInstances[currentCharacter] > 1) { continue; } else { output += input[i]; } } std::cout << output << std::endl; return 0; }
20.333333
85
0.666667
f06568948b9a5dd22a8d25344b24347add5cd753
967
cpp
C++
sdk/workspaces/vc10/LidarWrapper/LidarWrapper.cpp
maaks/ldrwrap
64e40908fc7f270b6378c3720e5c6539e989a77e
[ "BSD-2-Clause" ]
null
null
null
sdk/workspaces/vc10/LidarWrapper/LidarWrapper.cpp
maaks/ldrwrap
64e40908fc7f270b6378c3720e5c6539e989a77e
[ "BSD-2-Clause" ]
null
null
null
sdk/workspaces/vc10/LidarWrapper/LidarWrapper.cpp
maaks/ldrwrap
64e40908fc7f270b6378c3720e5c6539e989a77e
[ "BSD-2-Clause" ]
null
null
null
#include "pch.h" #include "LidarWrapper.h" #include "rplidar_cmd.h" using namespace rp::standalone::rplidar; LidarWrapper::Wrapper::Wrapper() { } bool LidarWrapper::Wrapper::connect(const char* com, _u32 baud) { drv = RPlidarDriver::CreateDriver(0x0); if (!drv) { return false; } rplidar_response_device_info_t devinfo; bool connectSuccess = false; if (IS_OK(drv->connect(com, baud))) { if (IS_OK(drv->getDeviceInfo(devinfo))) { connectSuccess = true; } else { delete drv; drv = nullptr; return false; } } return false; } bool LidarWrapper::Wrapper::startMotor() { drv->startMotor(); return true; } bool LidarWrapper::Wrapper::stopMotor() { drv->stopMotor(); return true; } void LidarWrapper::Wrapper::DisposeDriver() { RPlidarDriver::DisposeDriver(drv); drv = nullptr; }
15.596774
63
0.587384
f065d57c662e513c19451436adce905eb462d9cb
1,056
cpp
C++
C++/1214-Two-Sum-BSTs/soln.cpp
wyaadarsh/LeetCode-Solutions
3719f5cb059eefd66b83eb8ae990652f4b7fd124
[ "MIT" ]
5
2020-07-24T17:48:59.000Z
2020-12-21T05:56:00.000Z
C++/1214-Two-Sum-BSTs/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
null
null
null
C++/1214-Two-Sum-BSTs/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
2
2020-07-24T17:49:01.000Z
2020-08-31T19:57:35.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) { vector<int> vals1, vals2; Dfs(root1, &vals1); Dfs(root2, &vals2); sort(vals2.begin(), vals2.end()); for(int val : vals1) { auto it = lower_bound(vals2.begin(), vals2.end(), target - val); if(it != vals2.end() && *it == target - val) { return true; } } return false; } private: void Dfs(TreeNode * node, vector<int> * vals) { if(node != nullptr) { vals->push_back(node->val); Dfs(node->left, vals); Dfs(node->right, vals); } } };
28.540541
93
0.517045
f0661040e34c42c182ca269d08eafe3d14b1291c
1,350
hpp
C++
include/onepass/trackable.hpp
inql/OnePass
6e24d6bd6bcb70fdac4de5e4a155fcea68ea85ef
[ "Unlicense" ]
4
2021-10-20T17:40:33.000Z
2022-02-14T09:39:46.000Z
include/onepass/trackable.hpp
inql/OnePass
6e24d6bd6bcb70fdac4de5e4a155fcea68ea85ef
[ "Unlicense" ]
null
null
null
include/onepass/trackable.hpp
inql/OnePass
6e24d6bd6bcb70fdac4de5e4a155fcea68ea85ef
[ "Unlicense" ]
null
null
null
#ifndef TRACKABLE_HPP #define TRACKABLE_HPP namespace onepass { namespace core { template<class T> class Trackable { private: unsigned id_; time_t created_; time_t accessed_; friend class boost::serialization::access; public: T val_; Trackable() : id_(0) { } Trackable(unsigned i) : id_(i) { initialize(); } Trackable(unsigned i, T tracked) : id_(i), val_(tracked) { initialize(); } template<typename Archive> void serialize(Archive &ar, const unsigned int) { ar &id_; ar &created_; ar &accessed_; ar &val_; } unsigned getId() const { return id_; } time_t getCreated() const { return created_; } time_t getAccessed() const { return accessed_; } void initialize() { created_ = accessed_ = time(0); } void seen() { accessed_ = time(0); } std::string toString(time_t t) { char buffer[32]; std::tm *pmt = std::localtime(&t); std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S", pmt); return std::string{ buffer }; } }; } // namespace core } // namespace onepass #endif // TRACKABLE_HPP
19.285714
62
0.508889
f06c0f25f37e1f31691505bc5a0f838dd83c8a8e
48,489
cpp
C++
Temp/il2cppOutput/il2cppOutput/Il2CppCompilerCalculateTypeValues_19Table.cpp
408794550/871AR
3f903d01ae05522413f7be7abb286d1944d00bbb
[ "Apache-2.0" ]
1
2018-08-16T10:43:30.000Z
2018-08-16T10:43:30.000Z
Temp/il2cppOutput/il2cppOutput/Il2CppCompilerCalculateTypeValues_19Table.cpp
408794550/871AR
3f903d01ae05522413f7be7abb286d1944d00bbb
[ "Apache-2.0" ]
null
null
null
Temp/il2cppOutput/il2cppOutput/Il2CppCompilerCalculateTypeValues_19Table.cpp
408794550/871AR
3f903d01ae05522413f7be7abb286d1944d00bbb
[ "Apache-2.0" ]
null
null
null
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include "class-internals.h" #include "codegen/il2cpp-codegen.h" #include "UnityEngine_UI_UnityEngine_UI_PositionAsUV11102546563.h" #include "UnityEngine_UI_UnityEngine_UI_Shadow4269599528.h" #include "UnityEngine_UI_U3CPrivateImplementationDetailsU3E1486305137.h" #include "UnityEngine_UI_U3CPrivateImplementationDetailsU3E_1568637717.h" #include "DOTween43_U3CModuleU3E3783534214.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43301896125.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43_U3CU3Ec_426334720.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43_U3CU3Ec_426334751.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43_U3CU3Ec_426334817.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43_U3CU3Ec_426334918.h" #include "DOTween46_U3CModuleU3E3783534214.h" #include "DOTween46_DG_Tweening_DOTweenUtils461550156519.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46705180652.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec3371939845.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec3371939942.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec3371939977.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec3017480080.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec3582130305.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec_591124924.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec4039117214.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec_308799891.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec3582130274.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec_591124893.h" #include "DOTweenPro_U3CModuleU3E3783534214.h" #include "DOTweenPro_DG_Tweening_DOTweenVisualManager2945673405.h" #include "DOTweenPro_DG_Tweening_HandlesDrawMode3273484032.h" #include "DOTweenPro_DG_Tweening_HandlesType3201532857.h" #include "DOTweenPro_DG_Tweening_DOTweenInspectorMode2739551672.h" #include "DOTweenPro_DG_Tweening_DOTweenPath1397145371.h" #include "DOTweenPro_DG_Tweening_Core_ABSAnimationComponent2205594551.h" #include "DOTweenPro_DG_Tweening_Core_DOTweenAnimationType119935370.h" #include "DOTweenPro_DG_Tweening_Core_OnDisableBehaviour125315118.h" #include "DOTweenPro_DG_Tweening_Core_OnEnableBehaviour285142911.h" #include "DOTweenPro_DG_Tweening_Core_TargetType2706200073.h" #include "DOTweenPro_DG_Tweening_Core_VisualManagerPreset4087939440.h" #include "LitJson_U3CModuleU3E3783534214.h" #include "LitJson_LitJson_JsonType3145703806.h" #include "LitJson_LitJson_JsonData269267574.h" #include "LitJson_LitJson_OrderedDictionaryEnumerator3437478891.h" #include "LitJson_LitJson_JsonException613047007.h" #include "LitJson_LitJson_PropertyMetadata3693826136.h" #include "LitJson_LitJson_ArrayMetadata2008834462.h" #include "LitJson_LitJson_ObjectMetadata3995922398.h" #include "LitJson_LitJson_JsonMapper800426905.h" #include "LitJson_LitJson_JsonToken2852816099.h" #include "LitJson_LitJson_JsonReader1077921503.h" #include "LitJson_LitJson_Condition1980525237.h" #include "LitJson_LitJson_WriterContext4137194742.h" #include "LitJson_LitJson_JsonWriter1927598499.h" #include "LitJson_LitJson_FsmContext1296252303.h" #include "LitJson_LitJson_Lexer186508296.h" #include "LitJson_LitJson_Lexer_StateHandler387387051.h" #include "LitJson_LitJson_ParserToken1554180950.h" #include "LitJson_LitJson_ExporterFunc408878057.h" #include "LitJson_LitJson_ImporterFunc2977850894.h" #include "LitJson_LitJson_WrapperFactory2219329745.h" #include "LitJson_U3CPrivateImplementationDetailsU3E1486305137.h" #include "LitJson_U3CPrivateImplementationDetailsU3E_U24Arra4007721333.h" #include "Vuforia_UnityExtensions_U3CModuleU3E3783534214.h" #include "Vuforia_UnityExtensions_Vuforia_ARController2638793709.h" #include "Vuforia_UnityExtensions_Vuforia_ARController_U3CU32604000414.h" #include "Vuforia_UnityExtensions_Vuforia_DigitalEyewearARCo1398758191.h" #include "Vuforia_UnityExtensions_Vuforia_DigitalEyewearARCo2121820252.h" #include "Vuforia_UnityExtensions_Vuforia_DigitalEyewearARCo3746630162.h" #include "Vuforia_UnityExtensions_Vuforia_DigitalEyewearARCon342269456.h" #include "Vuforia_UnityExtensions_Vuforia_DigitalEyewearARCo2750347603.h" #include "Vuforia_UnityExtensions_Vuforia_EyewearDevice1202635122.h" #include "Vuforia_UnityExtensions_Vuforia_EyewearDevice_EyeID642957731.h" #include "Vuforia_UnityExtensions_Vuforia_EyewearDevice_Eyew1521251591.h" #include "Vuforia_UnityExtensions_Vuforia_NullHoloLensApiAbs1386933393.h" #include "Vuforia_UnityExtensions_Vuforia_DeviceTracker2183873360.h" #include "Vuforia_UnityExtensions_Vuforia_DeviceTrackerARCon3939888793.h" #include "Vuforia_UnityExtensions_Vuforia_DistortionRenderin3766399464.h" #include "Vuforia_UnityExtensions_Vuforia_DistortionRenderin2945034146.h" #include "Vuforia_UnityExtensions_Vuforia_DelegateHelper1202011487.h" #include "Vuforia_UnityExtensions_Vuforia_PlayModeEyewearUser117253723.h" #include "Vuforia_UnityExtensions_Vuforia_PlayModeEyewearCal3632467967.h" #include "Vuforia_UnityExtensions_Vuforia_PlayModeEyewearDev2977282393.h" #include "Vuforia_UnityExtensions_Vuforia_DedicatedEyewearDevi22891981.h" #include "Vuforia_UnityExtensions_Vuforia_CameraConfiguratio3904398347.h" #include "Vuforia_UnityExtensions_Vuforia_BaseCameraConfigurat38459502.h" #include "Vuforia_UnityExtensions_Vuforia_BaseStereoViewerCa1102239676.h" #include "Vuforia_UnityExtensions_Vuforia_StereoViewerCamera3365023487.h" #include "Vuforia_UnityExtensions_Vuforia_HoloLensExtendedTr3502001541.h" #include "Vuforia_UnityExtensions_Vuforia_HoloLensExtendedTr1161658011.h" #include "Vuforia_UnityExtensions_Vuforia_HoloLensExtendedTr3432166560.h" #include "Vuforia_UnityExtensions_Vuforia_VuforiaExtendedTra2074328369.h" #include "Vuforia_UnityExtensions_Vuforia_VuMarkManagerImpl1660847547.h" #include "Vuforia_UnityExtensions_Vuforia_InstanceIdImpl3955455590.h" #include "Vuforia_UnityExtensions_Vuforia_VuMarkTargetImpl2700679413.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1900 = { sizeof (PositionAsUV1_t1102546563), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1901 = { sizeof (Shadow_t4269599528), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1901[4] = { Shadow_t4269599528::get_offset_of_m_EffectColor_3(), Shadow_t4269599528::get_offset_of_m_EffectDistance_4(), Shadow_t4269599528::get_offset_of_m_UseGraphicAlpha_5(), 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1902 = { sizeof (U3CPrivateImplementationDetailsU3E_t1486305142), -1, sizeof(U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1902[1] = { U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields::get_offset_of_U24fieldU2D7BBE37982E6C057ED87163CAFC7FD6E5E42EEA46_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1903 = { sizeof (U24ArrayTypeU3D12_t1568637717)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU3D12_t1568637717 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1904 = { sizeof (U3CModuleU3E_t3783534221), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1905 = { sizeof (ShortcutExtensions43_t301896125), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1906 = { sizeof (U3CU3Ec__DisplayClass2_0_t426334720), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1906[1] = { U3CU3Ec__DisplayClass2_0_t426334720::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1907 = { sizeof (U3CU3Ec__DisplayClass3_0_t426334751), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1907[1] = { U3CU3Ec__DisplayClass3_0_t426334751::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1908 = { sizeof (U3CU3Ec__DisplayClass5_0_t426334817), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1908[1] = { U3CU3Ec__DisplayClass5_0_t426334817::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1909 = { sizeof (U3CU3Ec__DisplayClass8_0_t426334918), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1909[1] = { U3CU3Ec__DisplayClass8_0_t426334918::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1910 = { sizeof (U3CModuleU3E_t3783534222), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1911 = { sizeof (DOTweenUtils46_t1550156519), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1912 = { sizeof (ShortcutExtensions46_t705180652), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1913 = { sizeof (U3CU3Ec__DisplayClass0_0_t3371939845), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1913[1] = { U3CU3Ec__DisplayClass0_0_t3371939845::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1914 = { sizeof (U3CU3Ec__DisplayClass3_0_t3371939942), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1914[1] = { U3CU3Ec__DisplayClass3_0_t3371939942::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1915 = { sizeof (U3CU3Ec__DisplayClass4_0_t3371939977), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1915[1] = { U3CU3Ec__DisplayClass4_0_t3371939977::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1916 = { sizeof (U3CU3Ec__DisplayClass16_0_t3017480080), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1916[1] = { U3CU3Ec__DisplayClass16_0_t3017480080::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1917 = { sizeof (U3CU3Ec__DisplayClass22_0_t3582130305), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1917[1] = { U3CU3Ec__DisplayClass22_0_t3582130305::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1918 = { sizeof (U3CU3Ec__DisplayClass23_0_t591124924), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1918[1] = { U3CU3Ec__DisplayClass23_0_t591124924::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1919 = { sizeof (U3CU3Ec__DisplayClass25_0_t4039117214), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1919[1] = { U3CU3Ec__DisplayClass25_0_t4039117214::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1920 = { sizeof (U3CU3Ec__DisplayClass31_0_t308799891), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1920[1] = { U3CU3Ec__DisplayClass31_0_t308799891::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1921 = { sizeof (U3CU3Ec__DisplayClass32_0_t3582130274), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1921[1] = { U3CU3Ec__DisplayClass32_0_t3582130274::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1922 = { sizeof (U3CU3Ec__DisplayClass33_0_t591124893), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1922[1] = { U3CU3Ec__DisplayClass33_0_t591124893::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1923 = { sizeof (U3CModuleU3E_t3783534223), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1924 = { sizeof (DOTweenVisualManager_t2945673405), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1924[4] = { DOTweenVisualManager_t2945673405::get_offset_of_preset_2(), DOTweenVisualManager_t2945673405::get_offset_of_onEnableBehaviour_3(), DOTweenVisualManager_t2945673405::get_offset_of_onDisableBehaviour_4(), DOTweenVisualManager_t2945673405::get_offset_of__requiresRestartFromSpawnPoint_5(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1925 = { sizeof (HandlesDrawMode_t3273484032)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1925[3] = { HandlesDrawMode_t3273484032::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1926 = { sizeof (HandlesType_t3201532857)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1926[3] = { HandlesType_t3201532857::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1927 = { sizeof (DOTweenInspectorMode_t2739551672)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1927[3] = { DOTweenInspectorMode_t2739551672::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1928 = { sizeof (DOTweenPath_t1397145371), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1928[36] = { DOTweenPath_t1397145371::get_offset_of_delay_17(), DOTweenPath_t1397145371::get_offset_of_duration_18(), DOTweenPath_t1397145371::get_offset_of_easeType_19(), DOTweenPath_t1397145371::get_offset_of_easeCurve_20(), DOTweenPath_t1397145371::get_offset_of_loops_21(), DOTweenPath_t1397145371::get_offset_of_id_22(), DOTweenPath_t1397145371::get_offset_of_loopType_23(), DOTweenPath_t1397145371::get_offset_of_orientType_24(), DOTweenPath_t1397145371::get_offset_of_lookAtTransform_25(), DOTweenPath_t1397145371::get_offset_of_lookAtPosition_26(), DOTweenPath_t1397145371::get_offset_of_lookAhead_27(), DOTweenPath_t1397145371::get_offset_of_autoPlay_28(), DOTweenPath_t1397145371::get_offset_of_autoKill_29(), DOTweenPath_t1397145371::get_offset_of_relative_30(), DOTweenPath_t1397145371::get_offset_of_isLocal_31(), DOTweenPath_t1397145371::get_offset_of_isClosedPath_32(), DOTweenPath_t1397145371::get_offset_of_pathResolution_33(), DOTweenPath_t1397145371::get_offset_of_pathMode_34(), DOTweenPath_t1397145371::get_offset_of_lockRotation_35(), DOTweenPath_t1397145371::get_offset_of_assignForwardAndUp_36(), DOTweenPath_t1397145371::get_offset_of_forwardDirection_37(), DOTweenPath_t1397145371::get_offset_of_upDirection_38(), DOTweenPath_t1397145371::get_offset_of_wps_39(), DOTweenPath_t1397145371::get_offset_of_fullWps_40(), DOTweenPath_t1397145371::get_offset_of_path_41(), DOTweenPath_t1397145371::get_offset_of_inspectorMode_42(), DOTweenPath_t1397145371::get_offset_of_pathType_43(), DOTweenPath_t1397145371::get_offset_of_handlesType_44(), DOTweenPath_t1397145371::get_offset_of_livePreview_45(), DOTweenPath_t1397145371::get_offset_of_handlesDrawMode_46(), DOTweenPath_t1397145371::get_offset_of_perspectiveHandleSize_47(), DOTweenPath_t1397145371::get_offset_of_showIndexes_48(), DOTweenPath_t1397145371::get_offset_of_showWpLength_49(), DOTweenPath_t1397145371::get_offset_of_pathColor_50(), DOTweenPath_t1397145371::get_offset_of_lastSrcPosition_51(), DOTweenPath_t1397145371::get_offset_of_wpsDropdown_52(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1929 = { sizeof (ABSAnimationComponent_t2205594551), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1929[15] = { ABSAnimationComponent_t2205594551::get_offset_of_updateType_2(), ABSAnimationComponent_t2205594551::get_offset_of_isSpeedBased_3(), ABSAnimationComponent_t2205594551::get_offset_of_hasOnStart_4(), ABSAnimationComponent_t2205594551::get_offset_of_hasOnPlay_5(), ABSAnimationComponent_t2205594551::get_offset_of_hasOnUpdate_6(), ABSAnimationComponent_t2205594551::get_offset_of_hasOnStepComplete_7(), ABSAnimationComponent_t2205594551::get_offset_of_hasOnComplete_8(), ABSAnimationComponent_t2205594551::get_offset_of_hasOnTweenCreated_9(), ABSAnimationComponent_t2205594551::get_offset_of_onStart_10(), ABSAnimationComponent_t2205594551::get_offset_of_onPlay_11(), ABSAnimationComponent_t2205594551::get_offset_of_onUpdate_12(), ABSAnimationComponent_t2205594551::get_offset_of_onStepComplete_13(), ABSAnimationComponent_t2205594551::get_offset_of_onComplete_14(), ABSAnimationComponent_t2205594551::get_offset_of_onTweenCreated_15(), ABSAnimationComponent_t2205594551::get_offset_of_tween_16(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1930 = { sizeof (DOTweenAnimationType_t119935370)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1930[23] = { DOTweenAnimationType_t119935370::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1931 = { sizeof (OnDisableBehaviour_t125315118)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1931[7] = { OnDisableBehaviour_t125315118::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1932 = { sizeof (OnEnableBehaviour_t285142911)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1932[5] = { OnEnableBehaviour_t285142911::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1933 = { sizeof (TargetType_t2706200073)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1933[17] = { TargetType_t2706200073::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1934 = { sizeof (VisualManagerPreset_t4087939440)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1934[3] = { VisualManagerPreset_t4087939440::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1935 = { sizeof (U3CModuleU3E_t3783534224), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1936 = { sizeof (JsonType_t3145703806)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1936[9] = { JsonType_t3145703806::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1937 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1938 = { sizeof (JsonData_t269267574), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1938[10] = { JsonData_t269267574::get_offset_of_inst_array_0(), JsonData_t269267574::get_offset_of_inst_boolean_1(), JsonData_t269267574::get_offset_of_inst_double_2(), JsonData_t269267574::get_offset_of_inst_int_3(), JsonData_t269267574::get_offset_of_inst_long_4(), JsonData_t269267574::get_offset_of_inst_object_5(), JsonData_t269267574::get_offset_of_inst_string_6(), JsonData_t269267574::get_offset_of_json_7(), JsonData_t269267574::get_offset_of_type_8(), JsonData_t269267574::get_offset_of_object_list_9(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1939 = { sizeof (OrderedDictionaryEnumerator_t3437478891), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1939[1] = { OrderedDictionaryEnumerator_t3437478891::get_offset_of_list_enumerator_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1940 = { sizeof (JsonException_t613047007), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1941 = { sizeof (PropertyMetadata_t3693826136)+ sizeof (Il2CppObject), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1941[3] = { PropertyMetadata_t3693826136::get_offset_of_Info_0() + static_cast<int32_t>(sizeof(Il2CppObject)), PropertyMetadata_t3693826136::get_offset_of_IsField_1() + static_cast<int32_t>(sizeof(Il2CppObject)), PropertyMetadata_t3693826136::get_offset_of_Type_2() + static_cast<int32_t>(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1942 = { sizeof (ArrayMetadata_t2008834462)+ sizeof (Il2CppObject), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1942[3] = { ArrayMetadata_t2008834462::get_offset_of_element_type_0() + static_cast<int32_t>(sizeof(Il2CppObject)), ArrayMetadata_t2008834462::get_offset_of_is_array_1() + static_cast<int32_t>(sizeof(Il2CppObject)), ArrayMetadata_t2008834462::get_offset_of_is_list_2() + static_cast<int32_t>(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1943 = { sizeof (ObjectMetadata_t3995922398)+ sizeof (Il2CppObject), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1943[3] = { ObjectMetadata_t3995922398::get_offset_of_element_type_0() + static_cast<int32_t>(sizeof(Il2CppObject)), ObjectMetadata_t3995922398::get_offset_of_is_dictionary_1() + static_cast<int32_t>(sizeof(Il2CppObject)), ObjectMetadata_t3995922398::get_offset_of_properties_2() + static_cast<int32_t>(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1944 = { sizeof (JsonMapper_t800426905), -1, sizeof(JsonMapper_t800426905_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1944[38] = { JsonMapper_t800426905_StaticFields::get_offset_of_max_nesting_depth_0(), JsonMapper_t800426905_StaticFields::get_offset_of_datetime_format_1(), JsonMapper_t800426905_StaticFields::get_offset_of_base_exporters_table_2(), JsonMapper_t800426905_StaticFields::get_offset_of_custom_exporters_table_3(), JsonMapper_t800426905_StaticFields::get_offset_of_base_importers_table_4(), JsonMapper_t800426905_StaticFields::get_offset_of_custom_importers_table_5(), JsonMapper_t800426905_StaticFields::get_offset_of_array_metadata_6(), JsonMapper_t800426905_StaticFields::get_offset_of_array_metadata_lock_7(), JsonMapper_t800426905_StaticFields::get_offset_of_conv_ops_8(), JsonMapper_t800426905_StaticFields::get_offset_of_conv_ops_lock_9(), JsonMapper_t800426905_StaticFields::get_offset_of_object_metadata_10(), JsonMapper_t800426905_StaticFields::get_offset_of_object_metadata_lock_11(), JsonMapper_t800426905_StaticFields::get_offset_of_type_properties_12(), JsonMapper_t800426905_StaticFields::get_offset_of_type_properties_lock_13(), JsonMapper_t800426905_StaticFields::get_offset_of_static_writer_14(), JsonMapper_t800426905_StaticFields::get_offset_of_static_writer_lock_15(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache10_16(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache11_17(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache12_18(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache13_19(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache14_20(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache15_21(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache16_22(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache17_23(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache18_24(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache19_25(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache1A_26(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache1B_27(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache1C_28(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache1D_29(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache1E_30(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache1F_31(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache20_32(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache21_33(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache22_34(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache23_35(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache24_36(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache27_37(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1945 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable1945[1] = { 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1946 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable1946[1] = { 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1947 = { sizeof (JsonToken_t2852816099)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1947[13] = { JsonToken_t2852816099::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1948 = { sizeof (JsonReader_t1077921503), -1, sizeof(JsonReader_t1077921503_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1948[14] = { JsonReader_t1077921503_StaticFields::get_offset_of_parse_table_0(), JsonReader_t1077921503::get_offset_of_automaton_stack_1(), JsonReader_t1077921503::get_offset_of_current_input_2(), JsonReader_t1077921503::get_offset_of_current_symbol_3(), JsonReader_t1077921503::get_offset_of_end_of_json_4(), JsonReader_t1077921503::get_offset_of_end_of_input_5(), JsonReader_t1077921503::get_offset_of_lexer_6(), JsonReader_t1077921503::get_offset_of_parser_in_string_7(), JsonReader_t1077921503::get_offset_of_parser_return_8(), JsonReader_t1077921503::get_offset_of_read_started_9(), JsonReader_t1077921503::get_offset_of_reader_10(), JsonReader_t1077921503::get_offset_of_reader_is_owned_11(), JsonReader_t1077921503::get_offset_of_token_value_12(), JsonReader_t1077921503::get_offset_of_token_13(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1949 = { sizeof (Condition_t1980525237)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1949[6] = { Condition_t1980525237::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1950 = { sizeof (WriterContext_t4137194742), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1950[5] = { WriterContext_t4137194742::get_offset_of_Count_0(), WriterContext_t4137194742::get_offset_of_InArray_1(), WriterContext_t4137194742::get_offset_of_InObject_2(), WriterContext_t4137194742::get_offset_of_ExpectingValue_3(), WriterContext_t4137194742::get_offset_of_Padding_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1951 = { sizeof (JsonWriter_t1927598499), -1, sizeof(JsonWriter_t1927598499_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1951[11] = { JsonWriter_t1927598499_StaticFields::get_offset_of_number_format_0(), JsonWriter_t1927598499::get_offset_of_context_1(), JsonWriter_t1927598499::get_offset_of_ctx_stack_2(), JsonWriter_t1927598499::get_offset_of_has_reached_end_3(), JsonWriter_t1927598499::get_offset_of_hex_seq_4(), JsonWriter_t1927598499::get_offset_of_indentation_5(), JsonWriter_t1927598499::get_offset_of_indent_value_6(), JsonWriter_t1927598499::get_offset_of_inst_string_builder_7(), JsonWriter_t1927598499::get_offset_of_pretty_print_8(), JsonWriter_t1927598499::get_offset_of_validate_9(), JsonWriter_t1927598499::get_offset_of_writer_10(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1952 = { sizeof (FsmContext_t1296252303), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1952[4] = { FsmContext_t1296252303::get_offset_of_Return_0(), FsmContext_t1296252303::get_offset_of_NextState_1(), FsmContext_t1296252303::get_offset_of_L_2(), FsmContext_t1296252303::get_offset_of_StateStack_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1953 = { sizeof (Lexer_t186508296), -1, sizeof(Lexer_t186508296_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1953[14] = { Lexer_t186508296_StaticFields::get_offset_of_fsm_return_table_0(), Lexer_t186508296_StaticFields::get_offset_of_fsm_handler_table_1(), Lexer_t186508296::get_offset_of_allow_comments_2(), Lexer_t186508296::get_offset_of_allow_single_quoted_strings_3(), Lexer_t186508296::get_offset_of_end_of_input_4(), Lexer_t186508296::get_offset_of_fsm_context_5(), Lexer_t186508296::get_offset_of_input_buffer_6(), Lexer_t186508296::get_offset_of_input_char_7(), Lexer_t186508296::get_offset_of_reader_8(), Lexer_t186508296::get_offset_of_state_9(), Lexer_t186508296::get_offset_of_string_buffer_10(), Lexer_t186508296::get_offset_of_string_value_11(), Lexer_t186508296::get_offset_of_token_12(), Lexer_t186508296::get_offset_of_unichar_13(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1954 = { sizeof (StateHandler_t387387051), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1955 = { sizeof (ParserToken_t1554180950)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1955[20] = { ParserToken_t1554180950::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1956 = { sizeof (ExporterFunc_t408878057), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1957 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1958 = { sizeof (ImporterFunc_t2977850894), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1959 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1960 = { sizeof (WrapperFactory_t2219329745), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1961 = { sizeof (U3CPrivateImplementationDetailsU3E_t1486305143), -1, sizeof(U3CPrivateImplementationDetailsU3E_t1486305143_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1961[1] = { U3CPrivateImplementationDetailsU3E_t1486305143_StaticFields::get_offset_of_U24U24fieldU2D0_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1962 = { sizeof (U24ArrayTypeU24112_t4007721333)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU24112_t4007721333 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1963 = { sizeof (U3CModuleU3E_t3783534225), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1964 = { sizeof (ARController_t2638793709), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1964[1] = { ARController_t2638793709::get_offset_of_mVuforiaBehaviour_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1965 = { sizeof (U3CU3Ec__DisplayClass11_0_t2604000414), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1965[1] = { U3CU3Ec__DisplayClass11_0_t2604000414::get_offset_of_controller_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1966 = { sizeof (DigitalEyewearARController_t1398758191), -1, sizeof(DigitalEyewearARController_t1398758191_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1966[28] = { 0, 0, 0, 0, 0, 0, DigitalEyewearARController_t1398758191::get_offset_of_mCameraOffset_7(), DigitalEyewearARController_t1398758191::get_offset_of_mDistortionRenderingMode_8(), DigitalEyewearARController_t1398758191::get_offset_of_mDistortionRenderingLayer_9(), DigitalEyewearARController_t1398758191::get_offset_of_mEyewearType_10(), DigitalEyewearARController_t1398758191::get_offset_of_mStereoFramework_11(), DigitalEyewearARController_t1398758191::get_offset_of_mSeeThroughConfiguration_12(), DigitalEyewearARController_t1398758191::get_offset_of_mViewerName_13(), DigitalEyewearARController_t1398758191::get_offset_of_mViewerManufacturer_14(), DigitalEyewearARController_t1398758191::get_offset_of_mUseCustomViewer_15(), DigitalEyewearARController_t1398758191::get_offset_of_mCustomViewer_16(), DigitalEyewearARController_t1398758191::get_offset_of_mCentralAnchorPoint_17(), DigitalEyewearARController_t1398758191::get_offset_of_mParentAnchorPoint_18(), DigitalEyewearARController_t1398758191::get_offset_of_mPrimaryCamera_19(), DigitalEyewearARController_t1398758191::get_offset_of_mPrimaryCameraOriginalRect_20(), DigitalEyewearARController_t1398758191::get_offset_of_mSecondaryCamera_21(), DigitalEyewearARController_t1398758191::get_offset_of_mSecondaryCameraOriginalRect_22(), DigitalEyewearARController_t1398758191::get_offset_of_mSecondaryCameraDisabledLocally_23(), DigitalEyewearARController_t1398758191::get_offset_of_mVuforiaBehaviour_24(), DigitalEyewearARController_t1398758191::get_offset_of_mDistortionRenderingBhvr_25(), DigitalEyewearARController_t1398758191::get_offset_of_mSetFocusPlaneAutomatically_26(), DigitalEyewearARController_t1398758191_StaticFields::get_offset_of_mInstance_27(), DigitalEyewearARController_t1398758191_StaticFields::get_offset_of_mPadlock_28(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1967 = { sizeof (EyewearType_t2121820252)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1967[4] = { EyewearType_t2121820252::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1968 = { sizeof (StereoFramework_t3746630162)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1968[4] = { StereoFramework_t3746630162::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1969 = { sizeof (SeeThroughConfiguration_t342269456)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1969[3] = { SeeThroughConfiguration_t342269456::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1970 = { sizeof (SerializableViewerParameters_t2750347603), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1970[11] = { SerializableViewerParameters_t2750347603::get_offset_of_Version_0(), SerializableViewerParameters_t2750347603::get_offset_of_Name_1(), SerializableViewerParameters_t2750347603::get_offset_of_Manufacturer_2(), SerializableViewerParameters_t2750347603::get_offset_of_ButtonType_3(), SerializableViewerParameters_t2750347603::get_offset_of_ScreenToLensDistance_4(), SerializableViewerParameters_t2750347603::get_offset_of_InterLensDistance_5(), SerializableViewerParameters_t2750347603::get_offset_of_TrayAlignment_6(), SerializableViewerParameters_t2750347603::get_offset_of_LensCenterToTrayDistance_7(), SerializableViewerParameters_t2750347603::get_offset_of_DistortionCoefficients_8(), SerializableViewerParameters_t2750347603::get_offset_of_FieldOfView_9(), SerializableViewerParameters_t2750347603::get_offset_of_ContainsMagnet_10(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1971 = { sizeof (EyewearDevice_t1202635122), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1972 = { sizeof (EyeID_t642957731)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1972[4] = { EyeID_t642957731::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1973 = { sizeof (EyewearCalibrationReading_t1521251591)+ sizeof (Il2CppObject), sizeof(EyewearCalibrationReading_t1521251591_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable1973[5] = { EyewearCalibrationReading_t1521251591::get_offset_of_pose_0() + static_cast<int32_t>(sizeof(Il2CppObject)), EyewearCalibrationReading_t1521251591::get_offset_of_scale_1() + static_cast<int32_t>(sizeof(Il2CppObject)), EyewearCalibrationReading_t1521251591::get_offset_of_centerX_2() + static_cast<int32_t>(sizeof(Il2CppObject)), EyewearCalibrationReading_t1521251591::get_offset_of_centerY_3() + static_cast<int32_t>(sizeof(Il2CppObject)), EyewearCalibrationReading_t1521251591::get_offset_of_unused_4() + static_cast<int32_t>(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1974 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1975 = { sizeof (NullHoloLensApiAbstraction_t1386933393), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1976 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1977 = { sizeof (DeviceTracker_t2183873360), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1978 = { sizeof (DeviceTrackerARController_t3939888793), -1, sizeof(DeviceTrackerARController_t3939888793_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1978[13] = { DeviceTrackerARController_t3939888793_StaticFields::get_offset_of_DEFAULT_HEAD_PIVOT_1(), DeviceTrackerARController_t3939888793_StaticFields::get_offset_of_DEFAULT_HANDHELD_PIVOT_2(), DeviceTrackerARController_t3939888793::get_offset_of_mAutoInitTracker_3(), DeviceTrackerARController_t3939888793::get_offset_of_mAutoStartTracker_4(), DeviceTrackerARController_t3939888793::get_offset_of_mPosePrediction_5(), DeviceTrackerARController_t3939888793::get_offset_of_mModelCorrectionMode_6(), DeviceTrackerARController_t3939888793::get_offset_of_mModelTransformEnabled_7(), DeviceTrackerARController_t3939888793::get_offset_of_mModelTransform_8(), DeviceTrackerARController_t3939888793::get_offset_of_mTrackerStarted_9(), DeviceTrackerARController_t3939888793::get_offset_of_mTrackerWasActiveBeforePause_10(), DeviceTrackerARController_t3939888793::get_offset_of_mTrackerWasActiveBeforeDisabling_11(), DeviceTrackerARController_t3939888793_StaticFields::get_offset_of_mInstance_12(), DeviceTrackerARController_t3939888793_StaticFields::get_offset_of_mPadlock_13(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1979 = { sizeof (DistortionRenderingMode_t3766399464)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1979[4] = { DistortionRenderingMode_t3766399464::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1980 = { sizeof (DistortionRenderingBehaviour_t2945034146), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1980[12] = { DistortionRenderingBehaviour_t2945034146::get_offset_of_mSingleTexture_2(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mRenderLayer_3(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mOriginalCullingMasks_4(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mStereoCameras_5(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mMeshes_6(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mTextures_7(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mStarted_8(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mVideoBackgroundChanged_9(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mOriginalLeftViewport_10(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mOriginalRightViewport_11(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mDualTextureLeftViewport_12(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mDualTextureRightViewport_13(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1981 = { sizeof (DelegateHelper_t1202011487), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1982 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1983 = { sizeof (PlayModeEyewearUserCalibratorImpl_t117253723), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1984 = { sizeof (PlayModeEyewearCalibrationProfileManagerImpl_t3632467967), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1985 = { sizeof (PlayModeEyewearDevice_t2977282393), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1985[3] = { PlayModeEyewearDevice_t2977282393::get_offset_of_mProfileManager_1(), PlayModeEyewearDevice_t2977282393::get_offset_of_mCalibrator_2(), PlayModeEyewearDevice_t2977282393::get_offset_of_mDummyPredictiveTracking_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1986 = { sizeof (DedicatedEyewearDevice_t22891981), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1986[2] = { DedicatedEyewearDevice_t22891981::get_offset_of_mProfileManager_1(), DedicatedEyewearDevice_t22891981::get_offset_of_mCalibrator_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1987 = { sizeof (CameraConfigurationUtility_t3904398347), -1, sizeof(CameraConfigurationUtility_t3904398347_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1987[6] = { CameraConfigurationUtility_t3904398347_StaticFields::get_offset_of_MIN_CENTER_0(), CameraConfigurationUtility_t3904398347_StaticFields::get_offset_of_MAX_CENTER_1(), CameraConfigurationUtility_t3904398347_StaticFields::get_offset_of_MAX_BOTTOM_2(), CameraConfigurationUtility_t3904398347_StaticFields::get_offset_of_MAX_TOP_3(), CameraConfigurationUtility_t3904398347_StaticFields::get_offset_of_MAX_LEFT_4(), CameraConfigurationUtility_t3904398347_StaticFields::get_offset_of_MAX_RIGHT_5(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1988 = { sizeof (BaseCameraConfiguration_t38459502), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1988[10] = { BaseCameraConfiguration_t38459502::get_offset_of_mCameraDeviceMode_0(), BaseCameraConfiguration_t38459502::get_offset_of_mLastVideoBackGroundMirroredFromSDK_1(), BaseCameraConfiguration_t38459502::get_offset_of_mOnVideoBackgroundConfigChanged_2(), BaseCameraConfiguration_t38459502::get_offset_of_mVideoBackgroundBehaviours_3(), BaseCameraConfiguration_t38459502::get_offset_of_mVideoBackgroundViewportRect_4(), BaseCameraConfiguration_t38459502::get_offset_of_mRenderVideoBackground_5(), BaseCameraConfiguration_t38459502::get_offset_of_mProjectionOrientation_6(), BaseCameraConfiguration_t38459502::get_offset_of_mInitialReflection_7(), BaseCameraConfiguration_t38459502::get_offset_of_mBackgroundPlaneBehaviour_8(), BaseCameraConfiguration_t38459502::get_offset_of_mCameraParameterChanged_9(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1989 = { sizeof (BaseStereoViewerCameraConfiguration_t1102239676), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1989[5] = { BaseStereoViewerCameraConfiguration_t1102239676::get_offset_of_mPrimaryCamera_10(), BaseStereoViewerCameraConfiguration_t1102239676::get_offset_of_mSecondaryCamera_11(), BaseStereoViewerCameraConfiguration_t1102239676::get_offset_of_mSkewFrustum_12(), BaseStereoViewerCameraConfiguration_t1102239676::get_offset_of_mScreenWidth_13(), BaseStereoViewerCameraConfiguration_t1102239676::get_offset_of_mScreenHeight_14(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1990 = { sizeof (StereoViewerCameraConfiguration_t3365023487), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1990[7] = { 0, StereoViewerCameraConfiguration_t3365023487::get_offset_of_mLastAppliedLeftNearClipPlane_16(), StereoViewerCameraConfiguration_t3365023487::get_offset_of_mLastAppliedLeftFarClipPlane_17(), StereoViewerCameraConfiguration_t3365023487::get_offset_of_mLastAppliedRightNearClipPlane_18(), StereoViewerCameraConfiguration_t3365023487::get_offset_of_mLastAppliedRightFarClipPlane_19(), StereoViewerCameraConfiguration_t3365023487::get_offset_of_mCameraOffset_20(), StereoViewerCameraConfiguration_t3365023487::get_offset_of_mIsDistorted_21(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1991 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1992 = { sizeof (HoloLensExtendedTrackingManager_t3502001541), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1992[15] = { HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mNumFramesStablePose_0(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMaxPoseRelDistance_1(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMaxPoseAngleDiff_2(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMaxCamPoseAbsDistance_3(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMaxCamPoseAngleDiff_4(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMinNumFramesPoseOff_5(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMinPoseUpdateRelDistance_6(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMinPoseUpdateAngleDiff_7(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mTrackableSizeInViewThreshold_8(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMaxDistanceFromViewCenterForPoseUpdate_9(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mSetWorldAnchors_10(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mTrackingList_11(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mTrackablesExtendedTrackingEnabled_12(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mTrackablesCurrentlyExtendedTracked_13(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mExtendedTrackablesState_14(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1993 = { sizeof (PoseInfo_t1161658011)+ sizeof (Il2CppObject), sizeof(PoseInfo_t1161658011 ), 0, 0 }; extern const int32_t g_FieldOffsetTable1993[3] = { PoseInfo_t1161658011::get_offset_of_Position_0() + static_cast<int32_t>(sizeof(Il2CppObject)), PoseInfo_t1161658011::get_offset_of_Rotation_1() + static_cast<int32_t>(sizeof(Il2CppObject)), PoseInfo_t1161658011::get_offset_of_NumFramesPoseWasOff_2() + static_cast<int32_t>(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1994 = { sizeof (PoseAgeEntry_t3432166560)+ sizeof (Il2CppObject), sizeof(PoseAgeEntry_t3432166560 ), 0, 0 }; extern const int32_t g_FieldOffsetTable1994[3] = { PoseAgeEntry_t3432166560::get_offset_of_Pose_0() + static_cast<int32_t>(sizeof(Il2CppObject)), PoseAgeEntry_t3432166560::get_offset_of_CameraPose_1() + static_cast<int32_t>(sizeof(Il2CppObject)), PoseAgeEntry_t3432166560::get_offset_of_Age_2() + static_cast<int32_t>(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1995 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1996 = { sizeof (VuforiaExtendedTrackingManager_t2074328369), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1997 = { sizeof (VuMarkManagerImpl_t1660847547), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1997[6] = { VuMarkManagerImpl_t1660847547::get_offset_of_mBehaviours_0(), VuMarkManagerImpl_t1660847547::get_offset_of_mActiveVuMarkTargets_1(), VuMarkManagerImpl_t1660847547::get_offset_of_mDestroyedBehaviours_2(), VuMarkManagerImpl_t1660847547::get_offset_of_mOnVuMarkDetected_3(), VuMarkManagerImpl_t1660847547::get_offset_of_mOnVuMarkLost_4(), VuMarkManagerImpl_t1660847547::get_offset_of_mOnVuMarkBehaviourDetected_5(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1998 = { sizeof (InstanceIdImpl_t3955455590), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1998[5] = { InstanceIdImpl_t3955455590::get_offset_of_mDataType_0(), InstanceIdImpl_t3955455590::get_offset_of_mBuffer_1(), InstanceIdImpl_t3955455590::get_offset_of_mNumericValue_2(), InstanceIdImpl_t3955455590::get_offset_of_mDataLength_3(), InstanceIdImpl_t3955455590::get_offset_of_mCachedStringValue_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1999 = { sizeof (VuMarkTargetImpl_t2700679413), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1999[5] = { VuMarkTargetImpl_t2700679413::get_offset_of_mVuMarkTemplate_0(), VuMarkTargetImpl_t2700679413::get_offset_of_mInstanceId_1(), VuMarkTargetImpl_t2700679413::get_offset_of_mTargetId_2(), VuMarkTargetImpl_t2700679413::get_offset_of_mInstanceImage_3(), VuMarkTargetImpl_t2700679413::get_offset_of_mInstanceImageHeader_4(), }; #ifdef __clang__ #pragma clang diagnostic pop #endif
54.789831
211
0.855761
f06ee92972823d6b60af68a5fc9664e81b799368
646
hpp
C++
test/split.hpp
ortfero/chineseroom
6532df6af72f0ab7597e70e00c7f50c45af43c28
[ "MIT" ]
null
null
null
test/split.hpp
ortfero/chineseroom
6532df6af72f0ab7597e70e00c7f50c45af43c28
[ "MIT" ]
null
null
null
test/split.hpp
ortfero/chineseroom
6532df6af72f0ab7597e70e00c7f50c45af43c28
[ "MIT" ]
null
null
null
#pragma once #include <doctest/doctest.h> #include <chineseroom/split.hpp> TEST_CASE("splitting string '1,2,,3,'") { auto const splitted = chineseroom::split(std::string{"1,2,,3,"}, ','); REQUIRE(splitted.size() == 3); REQUIRE(splitted[0] == "1"); REQUIRE(splitted[1] == "2"); REQUIRE(splitted[2] == "3"); } TEST_CASE("strictly splitting string '1,2,,3,'") { auto const splitted = chineseroom::split_strictly(std::string{"1,2,,3,"}, ','); REQUIRE(splitted.size() == 5); REQUIRE(splitted[0] == "1"); REQUIRE(splitted[1] == "2"); REQUIRE(splitted[2] == ""); REQUIRE(splitted[3] == "3"); REQUIRE(splitted[4] == ""); }
23.925926
81
0.608359
7eb7a059af5ad373bdf75c3559c30c7b4abc159a
4,987
cpp
C++
source/Dream/Events/Source.cpp
kurocha/dream-events
b2cf5a188d8e3be2a07a5b7d36ed3eebc812cb72
[ "MIT", "Unlicense" ]
null
null
null
source/Dream/Events/Source.cpp
kurocha/dream-events
b2cf5a188d8e3be2a07a5b7d36ed3eebc812cb72
[ "MIT", "Unlicense" ]
null
null
null
source/Dream/Events/Source.cpp
kurocha/dream-events
b2cf5a188d8e3be2a07a5b7d36ed3eebc812cb72
[ "MIT", "Unlicense" ]
null
null
null
// // Events/Source.cpp // This file is part of the "Dream" project, and is released under the MIT license. // // Created by Samuel Williams on 9/12/08. // Copyright (c) 2008 Samuel Williams. All rights reserved. // // #include "Source.hpp" #include "Loop.hpp" #include <fcntl.h> #include <iostream> #include <unistd.h> #include <Dream/Core/Logger.hpp> namespace Dream { namespace Events { // MARK: - // MARK: class NotificationSource NotificationSource::NotificationSource (CallbackT callback) : _callback(callback) { } void NotificationSource::process_events (Loop * event_loop, Event event) { if (event == NOTIFICATION) _callback(event_loop, this, event); } NotificationSource::~NotificationSource () { } static void stop_run_loop_callback (Loop * event_loop, NotificationSource * note, Event enent) { event_loop->stop(); } Ref<NotificationSource> NotificationSource::stop_loop_notification () { return new NotificationSource(stop_run_loop_callback); } // MARK: - // MARK: class TimerSource TimerSource::TimerSource (CallbackT callback, TimeT duration, bool repeats, bool strict) : _cancelled(false), _repeats(repeats), _strict(strict), _duration(duration), _callback(callback) { } TimerSource::~TimerSource () { } void TimerSource::process_events (Loop * rl, Event events) { if (!_cancelled) _callback(rl, this, events); } bool TimerSource::repeats () const { if (_cancelled) return false; return _repeats; } TimeT TimerSource::next_timeout (const TimeT & last_timeout, const TimeT & current_time) const { // This means that TimerSource will attempt to "catch-up" //return last_timeout + _duration; // This means that TimerSource will process updates as is possible, and might drop // updates if they are in the past if (!_strict && last_timeout + _duration < current_time) return current_time; else return last_timeout + _duration; } void TimerSource::cancel () { _cancelled = true; } // MARK: - // MARK: class IFileDescriptorSource void IFileDescriptorSource::debug_file_descriptor_flags(int fd) { std::stringstream log_buffer; int flags = fcntl(fd, F_GETFL); log_buffer << "Flags for #" << fd << ":"; if (flags & O_NONBLOCK) log_buffer << " NONBLOCK"; int access_mode = flags & O_ACCMODE; if (access_mode == O_RDONLY) log_buffer << " RDONLY"; else if (access_mode == O_WRONLY) log_buffer << " WRONLY"; else log_buffer << " RDWR"; if (flags & O_APPEND) log_buffer << " APPEND"; if (flags & O_CREAT) log_buffer << " CREATE"; if (flags & O_TRUNC) log_buffer << " TRUNCATE"; log_debug(log_buffer.str()); } void IFileDescriptorSource::set_will_block (bool value) { FileDescriptor curfd = file_descriptor(); if (value == false) { fcntl(curfd, F_SETFL, fcntl(curfd, F_GETFL) | O_NONBLOCK); } else { fcntl(curfd, F_SETFL, fcntl(curfd, F_GETFL) & ~O_NONBLOCK); } } bool IFileDescriptorSource::will_block () { return !(fcntl(file_descriptor(), F_GETFL) & O_NONBLOCK); } // MARK: - // MARK: class FileDescriptorSource FileDescriptorSource::FileDescriptorSource (CallbackT callback, FileDescriptor file_descriptor) : _file_descriptor(file_descriptor), _callback(callback) { } FileDescriptorSource::~FileDescriptorSource () { } void FileDescriptorSource::process_events (Loop * event_loop, Event events) { _callback(event_loop, this, events); } FileDescriptor FileDescriptorSource::file_descriptor () const { return _file_descriptor; } Ref<FileDescriptorSource> FileDescriptorSource::for_standard_in (CallbackT callback) { return new FileDescriptorSource(callback, STDIN_FILENO); } Ref<FileDescriptorSource> FileDescriptorSource::for_standard_out (CallbackT callback) { return new FileDescriptorSource(callback, STDOUT_FILENO); } Ref<FileDescriptorSource> FileDescriptorSource::for_standard_error (CallbackT callback) { return new FileDescriptorSource(callback, STDERR_FILENO); } // MARK: - // MARK: class NotificationPipeSource NotificationPipeSource::NotificationPipeSource () { int result = pipe(_file_descriptors); DREAM_ASSERT(result == 0); } NotificationPipeSource::~NotificationPipeSource () { close(_file_descriptors[0]); close(_file_descriptors[1]); } FileDescriptor NotificationPipeSource::file_descriptor () const { // Read end return _file_descriptors[0]; } void NotificationPipeSource::notify_event_loop () const { // Send a byte down the pipe write(_file_descriptors[1], "\0", 1); } void NotificationPipeSource::process_events (Loop * loop, Event event) { const std::size_t COUNT = 32; char buffer[COUNT]; // Discard all notification bytes: read(_file_descriptors[0], &buffer, COUNT); // Process urgent notifications: loop->process_notifications(); } } }
22.263393
188
0.697814
7eb7e0c4ee1bb77198967e12661cf0d495b0eb3f
2,172
cpp
C++
mainWindowTetris.cpp
karimob/Tetris-mi-parcours
f8252f1b8924b8e085403765055408c71555f112
[ "MIT" ]
null
null
null
mainWindowTetris.cpp
karimob/Tetris-mi-parcours
f8252f1b8924b8e085403765055408c71555f112
[ "MIT" ]
null
null
null
mainWindowTetris.cpp
karimob/Tetris-mi-parcours
f8252f1b8924b8e085403765055408c71555f112
[ "MIT" ]
null
null
null
#include "precompiledHeader.h" #include "mainWindowTetris.h" #include "ui_mainWindowTetris.h" #include "tetrixwindow.h" MainWindowTetris::MainWindowTetris(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindowTetris) { ui->setupUi(this); TetrixWindow *window = new TetrixWindow; QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(window); setCentralWidget(new QWidget); centralWidget()->setLayout(layout); setFixedSize(500, 670); this->setWindowTitle("THE BEST TETRIX GAME"); this->setWindowIcon(QIcon(":/picture/TETRIX_ICON.jpg")); createMenuBar(); } void MainWindowTetris::createMenuBar() { QMenu *helpMenu = menuBar()->addMenu(tr("&AIDE")); QAction *aboutAct = helpMenu->addAction(tr("&Commandes"), this, &MainWindowTetris::commande); aboutAct = helpMenu->addAction(tr("&A propos"), this, &MainWindowTetris::about); aboutAct->setStatusTip(tr("Montre le a propos")); } void MainWindowTetris::commande() { QMessageBox::about(this, tr("commande Game"), tr("<br><b>flèche → :</b> Permet de bouger à GAUCHE \n</br>" "<br><b>flèche ← :</b> Permet de bouger à DROIT \n</br>" "<br><b>flèche ↓ :</b> Permet de faire une rotation DROITE \n</br>" "<br><b>flèche ↑ :</b> Permet de faire une rotation GAUCHE \n</br>" "<br><b>touche espace :</b> Descendre rapidement \n</br>" "<br><b>touche D :</b> Descendre d'une ligne</br>")); } void MainWindowTetris::about() { QMessageBox::about(this, tr("A propos Application"), tr("Le but du jeu est d'empiler les pièces tombées du haut de la zone de jeu afin qu'elles remplissent des rangées entières au bas de la zone de jeu." " Lorsqu'une rangée est remplie, tous les blocs de cette rangée sont supprimés, le joueur gagne un certain nombre de points et les pièces ci-dessus sont déplacées vers le bas pour occuper cette rangée. Si plus d'une ligne est remplie, les blocs de chaque ligne sont supprimés et le joueur gagne des points supplémentaires." )); } //Destructeur MainWindowTetris::~MainWindowTetris() { delete ui; }
36.2
337
0.668969
7eb8f1d7a2ef4df245e9f013d0b1844198240c44
1,191
cpp
C++
ESOBrowser/ESODatabaseModel.cpp
moon-touched/ESOExplorer
a57e6c5d545d48f783664f624cbeee5c5b542ef3
[ "MIT" ]
2
2020-07-25T01:51:34.000Z
2021-07-12T20:35:28.000Z
ESOBrowser/ESODatabaseModel.cpp
moon-touched/ESOExplorer
a57e6c5d545d48f783664f624cbeee5c5b542ef3
[ "MIT" ]
null
null
null
ESOBrowser/ESODatabaseModel.cpp
moon-touched/ESOExplorer
a57e6c5d545d48f783664f624cbeee5c5b542ef3
[ "MIT" ]
null
null
null
#include "ESODatabaseModel.h" #include <ESOData/Database/ESODatabase.h> ESODatabaseModel::ESODatabaseModel(const esodata::ESODatabase* database, QObject* parent) : QAbstractItemModel(parent), m_database(database) { } ESODatabaseModel::~ESODatabaseModel() = default; int ESODatabaseModel::columnCount(const QModelIndex& parent) const { if (parent.isValid()) return 0; return 1; } QVariant ESODatabaseModel::data(const QModelIndex& index, int role) const { auto def = static_cast<esodata::ESODatabaseDef*>(index.internalPointer()); switch (role) { case Qt::DisplayRole: return QString::fromStdString(def->name()); default: return QVariant(); } } QModelIndex ESODatabaseModel::index(int row, int column, const QModelIndex& parent) const { if(parent.isValid() || column != 0) return QModelIndex(); return createIndex(row, column, const_cast<esodata::ESODatabaseDef *>(&m_database->defs()[row])); } QModelIndex ESODatabaseModel::parent(const QModelIndex& index) const { (void)index; return QModelIndex(); } int ESODatabaseModel::rowCount(const QModelIndex& parent) const { if (parent.isValid()) return 0; return static_cast<int>(m_database->defs().size()); }
24.8125
142
0.745592
7ec25261c39def588dac7424a1a1b276fad3ab59
11,445
cpp
C++
sdk/src/config.cpp
Appdynamics/iot-cpp-sdk
abb7d70b2364089495ac73adf2a992c0af6eaf8c
[ "Apache-2.0" ]
3
2018-09-13T21:26:27.000Z
2022-01-25T06:15:06.000Z
sdk/src/config.cpp
Appdynamics/iot-cpp-sdk
abb7d70b2364089495ac73adf2a992c0af6eaf8c
[ "Apache-2.0" ]
11
2018-01-30T00:42:23.000Z
2019-10-20T07:19:37.000Z
sdk/src/config.cpp
Appdynamics/iot-cpp-sdk
abb7d70b2364089495ac73adf2a992c0af6eaf8c
[ "Apache-2.0" ]
5
2018-01-29T18:52:21.000Z
2019-05-19T02:38:18.000Z
/* * Copyright (c) 2018 AppDynamics LLC and its affiliates * * 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 "config.hpp" #include "beacon.hpp" #include "log.hpp" static appd_sdk_config_t global_sdk_config; static std::string appd_iot_eum_collector_url_appkey_prefix = "eumcollector/iot/v1/application/"; static std::string appd_iot_eum_collector_url_beacons_suffix = "/beacons"; static std::string appd_iot_eum_collector_url_enabled_suffix = "/enabled"; static std::string default_eum_collector_url = "https://iot-col.eum-appdynamics.com"; //Server Correlation headers in {key,value} format static const appd_iot_data_t global_correlation_headers[APPD_IOT_NUM_SERVER_CORRELATION_HEADERS] = { {"ADRUM", {"isAjax:true"}, APPD_IOT_STRING}, {"ADRUM_1", {"isMobile:true"}, APPD_IOT_STRING} }; static appd_iot_sdk_state_t global_sdk_state = APPD_IOT_SDK_UNINITIALIZED; /** * @brief This method Initializes the SDK. <br> * This method should be called atleast once, early in your application's start up sequence. * @param sdkcfg contains sdk configuration such as collector url, appkey etc * @param devcfg contains device information such as device type/name and hw/fw/sw versions * @return appd_iot_error_code_t Error code indicating if the function call is a success or fail. * Error code returned provides more details on the type of error occurred. */ appd_iot_error_code_t appd_iot_init_sdk(appd_iot_sdk_config_t sdkcfg, appd_iot_device_config_t devcfg) { std::string eum_collector_url; appd_iot_error_code_t retcode; /* Process Log Config */ if (sdkcfg.log_level >= APPD_IOT_LOG_OFF && sdkcfg.log_level <= APPD_IOT_LOG_ALL) { global_sdk_config.log_level = sdkcfg.log_level; } else { global_sdk_config.log_level = APPD_IOT_LOG_ERROR; } if (global_sdk_config.log_level != APPD_IOT_LOG_OFF) { global_sdk_config.log_write_cb = sdkcfg.log_write_cb; } /* Process Device Config */ retcode = appd_iot_init_device_config(devcfg); if (retcode != APPD_IOT_SUCCESS) { appd_iot_log(APPD_IOT_LOG_ERROR, "Device Config Initialization Failed"); return retcode; } /* Process SDK Config */ if (sdkcfg.appkey == NULL) { appd_iot_log(APPD_IOT_LOG_ERROR, "AppKey cannot be NULL"); return APPD_IOT_ERR_INVALID_INPUT; } global_sdk_config.appkey = sdkcfg.appkey; if (sdkcfg.eum_collector_url == NULL) { eum_collector_url = default_eum_collector_url; appd_iot_log(APPD_IOT_LOG_ERROR, "EUM collector URL is NULL, setting to default:%s", default_eum_collector_url.c_str()); } else { eum_collector_url = sdkcfg.eum_collector_url; } if (eum_collector_url.at(eum_collector_url.length() - 1) != '/') { eum_collector_url = eum_collector_url + "/"; } global_sdk_config.eum_collector_url = eum_collector_url + appd_iot_eum_collector_url_appkey_prefix + global_sdk_config.appkey + appd_iot_eum_collector_url_beacons_suffix; global_sdk_config.eum_appkey_enabled_url = eum_collector_url + appd_iot_eum_collector_url_appkey_prefix + global_sdk_config.appkey + appd_iot_eum_collector_url_enabled_suffix; appd_iot_log(APPD_IOT_LOG_INFO, "EUM Collector URL %s", global_sdk_config.eum_collector_url.c_str()); if (sdkcfg.sdk_state_change_cb != NULL) { global_sdk_config.sdk_state_change_cb = sdkcfg.sdk_state_change_cb; } appd_iot_set_sdk_state(APPD_IOT_SDK_ENABLED); return APPD_IOT_SUCCESS; } /** * @brief This method registers network interface <br> * This method should be called atleast once, early in your application's start up sequence. * @param http_cb contains function pointers for http request send and http response done callbacks <br>. * http request send callback will be called when appd_iot_send_all_events is triggered. <br> * http response done callback will be called after send http request callback returns and * response is processed. * @return appd_iot_error_code_t Error code indicating if the function call is a success or fail. * Error code returned provides more details on the type of error occurred. */ appd_iot_error_code_t appd_iot_register_network_interface(appd_iot_http_cb_t http_cb) { if (http_cb.http_req_send_cb == NULL) { appd_iot_log(APPD_IOT_LOG_ERROR, "http_req_send_cb is NULL"); return APPD_IOT_ERR_INVALID_INPUT; } if (http_cb.http_resp_done_cb == NULL) { appd_iot_log(APPD_IOT_LOG_ERROR, "http_resp_done_cb is NULL"); return APPD_IOT_ERR_INVALID_INPUT; } global_sdk_config.http_cb.http_req_send_cb = http_cb.http_req_send_cb; global_sdk_config.http_cb.http_resp_done_cb = http_cb.http_resp_done_cb; return APPD_IOT_SUCCESS; } /** * @brief Get http request send callback function pointer * @return callback function pointer */ appd_iot_http_req_send_cb_t appd_iot_get_http_req_send_cb(void) { return global_sdk_config.http_cb.http_req_send_cb; } /** * @brief Get http response done callback function pointer * @return callback function pointer */ appd_iot_http_resp_done_cb_t appd_iot_get_http_resp_done_cb(void) { return global_sdk_config.http_cb.http_resp_done_cb; } /** * @brief Get Log Level configured as part of SDK Initialization * @return appd_iot_log_level_t contains log level enum */ appd_iot_log_level_t appd_iot_get_log_level(void) { return global_sdk_config.log_level; } /** * @brief Get Log Write Callback Function Pointer. * @return appd_iot_log_write_cb_t contains log_write_cb fun ptr */ appd_iot_log_write_cb_t appd_iot_get_log_write_cb(void) { return global_sdk_config.log_write_cb; } /** * @brief Get Configured EUM Collector URL * @return URL in string format */ const char* appd_iot_get_eum_collector_url(void) { return global_sdk_config.eum_collector_url.c_str(); } /** * @brief Get Server Correlation headers in {key,value} format that need to be added to * every outgoing http request to enable capturing Business Transaction (BT). * @return Server Correlation Headers. Total number of headers present is given by * macro APPD_IOT_NUM_SERVER_CORRELATION_HEADERS. Do not modify or free returned headers. */ const appd_iot_data_t* appd_iot_get_server_correlation_headers(void) { return global_correlation_headers; } /** * @brief Set SDK State * @param new_state indicates the new sdk state that need to be set */ void appd_iot_set_sdk_state(appd_iot_sdk_state_t new_state) { if (global_sdk_state == new_state) { appd_iot_log(APPD_IOT_LOG_WARN, "SDK state update with same state as current:%s", appd_iot_sdk_state_to_str(global_sdk_state)); return; } global_sdk_state = new_state; appd_iot_log(APPD_IOT_LOG_INFO, "New SDK state :%s", appd_iot_sdk_state_to_str(global_sdk_state)); if (global_sdk_config.sdk_state_change_cb != NULL) { global_sdk_config.sdk_state_change_cb(global_sdk_state); } } /** * @brief Get Current SDK State * @return appd_iot_sdk_state_t with current sdk state */ appd_iot_sdk_state_t appd_iot_get_sdk_state(void) { return global_sdk_state; } /** * @brief Set SDK state to disabled state based on the HTTP Response Code * @param http_resp_code indicates the response code from the Collector */ void appd_iot_disable_sdk(int http_resp_code) { if (http_resp_code == 403) { appd_iot_log(APPD_IOT_LOG_ERROR, "Resp Code:%d Application on Controller is Disabled", http_resp_code); appd_iot_set_sdk_state(APPD_IOT_SDK_DISABLED_KILL_SWITCH); } else if (http_resp_code == 429) { appd_iot_log(APPD_IOT_LOG_ERROR, "Resp Code:%d Application Data Limit Exceeded", http_resp_code); appd_iot_set_sdk_state(APPD_IOT_SDK_DISABLED_DATA_LIMIT_EXCEEDED); } else if (http_resp_code == 402) { appd_iot_log(APPD_IOT_LOG_ERROR, "Resp Code:%d Application License Expired", http_resp_code); appd_iot_set_sdk_state(APPD_IOT_SDK_DISABLED_LICENSE_EXPIRED); } else { appd_iot_log(APPD_IOT_LOG_INFO, "Resp Code:%d not supported to disable SDK", http_resp_code); } } /** * @brief Use this API to check with AppDynamics Collector on the status of IoT Application on * AppDynamics Controller, whether instrumentation is enabled or not. If the Collector returns Success, SDK * gets ENABLED in case it has been DISABLED previously by Collector due to license expiry, kill switch or * data limit exceeded. <br> * It is required that SDK initialization is already done using the API appd_iot_init_sdk() before * calling this function. * @return appd_iot_error_code_t will indicate success if app is enabled */ appd_iot_error_code_t appd_iot_check_app_status(void) { appd_iot_sdk_state_t curr_sdk_state = appd_iot_get_sdk_state(); if (curr_sdk_state == APPD_IOT_SDK_UNINITIALIZED) { appd_iot_log(APPD_IOT_LOG_ERROR, "SDK is Uninitalized. Call Init SDK before calling this API"); return APPD_IOT_ERR_SDK_NOT_ENABLED; } /* Init all the data structures - REQ and RESP */ appd_iot_http_req_t http_req; appd_iot_http_resp_t* http_resp = NULL; appd_iot_error_code_t retcode = APPD_IOT_SUCCESS; appd_iot_http_req_send_cb_t http_req_send_cb = appd_iot_get_http_req_send_cb(); appd_iot_http_resp_done_cb_t http_resp_done_cb = appd_iot_get_http_resp_done_cb(); if (http_req_send_cb == NULL) { appd_iot_log(APPD_IOT_LOG_ERROR, "Network Interface Not Available"); return APPD_IOT_ERR_NETWORK_NOT_AVAILABLE; } appd_iot_init_to_zero(&http_req, sizeof(http_req)); http_req.type = "GET"; http_req.url = global_sdk_config.eum_appkey_enabled_url.c_str(); http_resp = http_req_send_cb(&http_req); /* check if any error present in http response */ if (http_resp != NULL) { retcode = http_resp->error; } else { appd_iot_log(APPD_IOT_LOG_ERROR, "NULL HTTP Response Returned"); retcode = APPD_IOT_ERR_NULL_PTR; } /* Return if there is an error executing http req */ if (retcode != APPD_IOT_SUCCESS) { appd_iot_log(APPD_IOT_LOG_ERROR, "Error Executing HTTP Request, ErrorCode:%d", retcode); if (http_resp_done_cb != NULL) { http_resp_done_cb(http_resp); } return retcode; } if (http_resp->resp_code >= 200 && http_resp->resp_code < 300) { appd_iot_set_sdk_state(APPD_IOT_SDK_ENABLED); appd_iot_log(APPD_IOT_LOG_INFO, "RespCode:%d Application is Enabled on Controller", http_resp->resp_code); retcode = APPD_IOT_SUCCESS; } else if ((http_resp->resp_code == 402) || (http_resp->resp_code == 403) || (http_resp->resp_code == 429)) { appd_iot_disable_sdk(http_resp->resp_code); retcode = APPD_IOT_ERR_NETWORK_REJECT; } else { appd_iot_log(APPD_IOT_LOG_ERROR, "Resp Code:%d Network Request to Check App Status Failed", http_resp->resp_code); retcode = APPD_IOT_ERR_NETWORK_ERROR; } if (http_resp_done_cb != NULL) { http_resp_done_cb(http_resp); } return retcode; }
31.703601
110
0.757886
7ec322b6f9f602c5011df5edd6031a7aa189a19b
1,899
cpp
C++
Antiplagiat/Antiplagiat/bin/Debug/u42682_518_E_10004263.cpp
DmitryTheFirst/AntiplagiatVkCup
556d3fe2e5a630d06a7aa49f2af5dcb28667275a
[ "Apache-2.0" ]
1
2015-07-04T14:45:32.000Z
2015-07-04T14:45:32.000Z
Antiplagiat/Antiplagiat/bin/Debug/u42682_518_E_10004263.cpp
DmitryTheFirst/AntiplagiatVkCup
556d3fe2e5a630d06a7aa49f2af5dcb28667275a
[ "Apache-2.0" ]
null
null
null
Antiplagiat/Antiplagiat/bin/Debug/u42682_518_E_10004263.cpp
DmitryTheFirst/AntiplagiatVkCup
556d3fe2e5a630d06a7aa49f2af5dcb28667275a
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define ll long long #define gc getchar int a[500005]; bool v[500005]; int read(int i) { char c = gc(); while((c<'0' || c>'9') && c!='?' && c!='-') c = gc(); bool sig = 1; if(c=='?') { v[i] = 1; return 0; } if(c=='-') { c = gc(); sig = 0; } int ret = 0; while(c>='0' && c<='9') { ret = 10 * ret + c - 48; c = gc(); } if(sig) return ret; return -ret; } int main(){ ios_base::sync_with_stdio(0); int n,k; n = read(0); k = read(0); //cout<<n<<" "<<k<<endl; for(int i=0; i<n; i++) { a[i] = read(i); //cout<<a[i]<<" "<<v[i]<<endl; } bool ov = true; for(int i=0; i<k; i++) { int l = i-k; while(l+k<n) { int r = l+k; int p = 0; while(r<n && v[r]) { r+=k; p++; } //cout<<"1: "<<l<<" "<<r<<endl; int r2 = r; if(l<0 && r>=n) { int cur = -(p/2); r = l+k; while(r<n) { a[r] = cur; cur++; r+=k; } } else if(l<0) { int cur = a[r]-1; if(cur>p/2) cur = p/2; r-=k; while(r>=0) { a[r] = cur; cur--; r-=k; } } else if(r>=n) { int cur = a[l]+1; if(cur<-(p/2)) cur = -(p/2); r = l+k; while(r<n) { a[r] = cur; cur++; r+=k; } } else if(a[r]-p-1<a[l]) { ov = false; } else if(a[l]>0) { int cur = a[l]+1; r = l+k; while(r<n && v[r]) { a[r] = cur; cur++; r+=k; } } else if(a[r]<0) { int cur = a[r]-1; r-=k; while(r>=0 && v[r]) { a[r] = cur; cur--; r-=k; } } else { int cur = -(p/2); if(cur<a[l]+1) cur = a[l]+1; else { while(cur+p>a[r]) cur--; } r = l+k; while(r<n && v[r]) { a[r] = cur; cur++; r+=k; } } l = r2; } } if(!ov) { cout<<"Incorrect sequence"<<endl; } else { for(int i=0; i<n; i++) cout<<a[i]<<" "; cout<<endl; } return 0; }
22.879518
64
0.382833
7ec43bb8d48251e102fd7ca0fb5c2e2e4e91bbc4
302
cpp
C++
dojo/first/06_coroutine_ts/main.cpp
adrianimboden/cppusergroup-adynchronous-programming
d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4
[ "MIT" ]
null
null
null
dojo/first/06_coroutine_ts/main.cpp
adrianimboden/cppusergroup-adynchronous-programming
d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4
[ "MIT" ]
null
null
null
dojo/first/06_coroutine_ts/main.cpp
adrianimboden/cppusergroup-adynchronous-programming
d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4
[ "MIT" ]
null
null
null
#include "http_client.h" namespace coroutines_ts { task<std::vector<std::string>> request_uris(HttpClient& http_client, const std::vector<std::string>& uris_to_request) { (void)http_client; (void)uris_to_request; co_return std::vector<std::string>{{"42"}}; } }
23.230769
63
0.652318
7ec468508f106eac6bf99e10ec8bd756222a6851
1,165
hpp
C++
src/serial/SerialPlayer.hpp
stu-inc/DataCapture
d2bd01cd431867ec8372687542150391344022d6
[ "MIT" ]
null
null
null
src/serial/SerialPlayer.hpp
stu-inc/DataCapture
d2bd01cd431867ec8372687542150391344022d6
[ "MIT" ]
null
null
null
src/serial/SerialPlayer.hpp
stu-inc/DataCapture
d2bd01cd431867ec8372687542150391344022d6
[ "MIT" ]
null
null
null
#pragma once #include <QReadWriteLock> #include <QSharedPointer> #include <QThread> #include <QtSerialPort> class QFile; class QElapsedTimer; class SerialPlayer : public QThread { public: explicit SerialPlayer(QObject *parent = nullptr); virtual ~SerialPlayer() override; void start(); void stop(); void restart(); qint64 getCurrentTime() const; void setPortName(const QString &portName); void setFileName(const QString &fileName); void setBaundRate(QSerialPort::BaudRate baudRate); void setDataBits(QSerialPort::DataBits dataBits); void setParity(QSerialPort::Parity parity); void setStopBits(QSerialPort::StopBits stopBits); void setByteOrder(QSysInfo::Endian byteOrder); protected: virtual void run() override; private: mutable QReadWriteLock mLock; QSharedPointer<QSerialPort> mSerialPort; QSharedPointer<QFile> mFile; QSharedPointer<QDataStream> mDataStream; QSharedPointer<QElapsedTimer> mTimer; QString mPortName; QString mFileName; QSerialPort::BaudRate mBaundRate; QSerialPort::DataBits mDataBits; QSerialPort::Parity mParity; QSerialPort::StopBits mStopBits; QSysInfo::Endian mByteOrder; };
22.843137
52
0.771674
7ec85697288a121d2e81564097e612303ade086f
1,049
cpp
C++
Ejercicio4Tema11/Ejercicio4Tema11/Rio.cpp
gejors55/Algorithm
107d6cf4eb8fc7f4d0cebfe9b4e7b2811ac10533
[ "MIT" ]
null
null
null
Ejercicio4Tema11/Ejercicio4Tema11/Rio.cpp
gejors55/Algorithm
107d6cf4eb8fc7f4d0cebfe9b4e7b2811ac10533
[ "MIT" ]
null
null
null
Ejercicio4Tema11/Ejercicio4Tema11/Rio.cpp
gejors55/Algorithm
107d6cf4eb8fc7f4d0cebfe9b4e7b2811ac10533
[ "MIT" ]
null
null
null
#include "Rio.h" Rio::Rio() {} float Rio::embalsado_pantano(const string& pantano) const { return buscar_pantano(pantano).vol(); } float Rio::embalsado_total() const { DiccionarioHash<string, Pantano>::ConstIterator ipantano = _pantanos.cbegin(); DiccionarioHash<string, Pantano>::ConstIterator ifin = _pantanos.cend(); int suma =0; while (ipantano != ifin){ suma += ipantano.valor().vol(); ipantano.next(); } return suma; } const Pantano& Rio::buscar_pantano(const string& pantano) const { DiccionarioHash<string, Pantano>::ConstIterator ipantano = _pantanos.cbusca(pantano); DiccionarioHash<string, Pantano>::ConstIterator ifin = _pantanos.cend(); if (ipantano == ifin) throw EPantanoNoExiste(); return ipantano.valor(); } Pantano Rio::busca( string pantano) { DiccionarioHash<string, Pantano>::Iterator ipantano = _pantanos.busca(pantano); DiccionarioHash<string, Pantano>::Iterator ifin = _pantanos.end(); if (ipantano == ifin) throw EPantanoNoExiste(); return ipantano.valor(); }
29.971429
87
0.711153
7ece0d313e1768940414c5fe1f211ce55e1716ec
18,342
cpp
C++
ccct.cpp
Taromati2/yaya-shiori
c49e3d4d03f167a8833f2e68810fb46dc33bac90
[ "BSD-3-Clause" ]
null
null
null
ccct.cpp
Taromati2/yaya-shiori
c49e3d4d03f167a8833f2e68810fb46dc33bac90
[ "BSD-3-Clause" ]
2
2022-01-12T03:25:46.000Z
2022-01-12T07:15:38.000Z
ccct.cpp
Taromati2/yaya-shiori
c49e3d4d03f167a8833f2e68810fb46dc33bac90
[ "BSD-3-Clause" ]
null
null
null
// // AYA version 5 // // 文字コード変換クラス Ccct // // 変換部分のコードは以下のサイトで公開されているものを利用しております。 // class CUnicodeF // kamoland // http://kamoland.com/comp/unicode.html // #if defined(WIN32) || defined(_WIN32_WCE) # include "stdafx.h" #endif #include <string.h> #include <clocale> #include <string> #include "ccct.h" #include "manifest.h" #include "globaldef.h" //#include "babel/babel.h" #ifdef POSIX # include <ctype.h> #endif /* #define PRIMARYLANGID(lgid) ((WORD)(lgid) & 0x3ff) */ //////////DEBUG///////////////////////// #ifdef _WINDOWS #ifdef _DEBUG #include <crtdbg.h> #define new new( _NORMAL_BLOCK, __FILE__, __LINE__) #endif #endif //////////////////////////////////////// #ifdef POSIX namespace { int wcsicmp(const wchar_t* a, const wchar_t* b) { size_t lenA = wcslen(a); size_t lenB = wcslen(b); if (lenA != lenB) { return lenA - lenB; } else { for (size_t i = 0; i < lenA; i++) { wchar_t A = tolower(a[i]); wchar_t B = tolower(b[i]); if (A != B) { return A - B; } } return 0; } } int stricmp(const char* a, const char* b) { size_t lenA = strlen(a); size_t lenB = strlen(b); if (lenA != lenB) { return lenA - lenB; } else { for (size_t i = 0; i < lenA; i++) { wchar_t A = tolower(a[i]); wchar_t B = tolower(b[i]); if (A != B) { return A - B; } } return 0; } } } #endif /* ----------------------------------------------------------------------- * 関数名 : Ccct::CheckCharset * 機能概要: Charset IDのチェック * ----------------------------------------------------------------------- */ bool Ccct::CheckInvalidCharset(int charset) { if (charset != CHARSET_SJIS && charset != CHARSET_UTF8 && charset != CHARSET_EUCJP && charset != CHARSET_BIG5 && charset != CHARSET_GB2312 && charset != CHARSET_EUCKR && charset != CHARSET_JIS && charset != CHARSET_BINARY && charset != CHARSET_DEFAULT) { return true; } return false; } /* ----------------------------------------------------------------------- * 関数名 : Ccct::CharsetTextToID * 機能概要: Charset 文字列->Charset ID * ----------------------------------------------------------------------- */ int Ccct::CharsetTextToID(const wchar_t *ctxt) { if (!wcsicmp(L"UTF-8",ctxt) || !wcsicmp(L"UTF8",ctxt)) return CHARSET_UTF8; else if (!wcsicmp(L"default",ctxt) || !wcsicmp(L"OSNative",ctxt)) return CHARSET_DEFAULT; else if (!wcsicmp(L"Shift_JIS",ctxt) || !wcsicmp(L"ShiftJIS",ctxt) || !wcsicmp(L"SJIS",ctxt)) return CHARSET_SJIS; else if (!wcsicmp(L"EUC_JP",ctxt) || !wcsicmp(L"EUC-JP",ctxt) || !wcsicmp(L"EUCJP",ctxt)) return CHARSET_EUCJP; else if (!wcsicmp(L"ISO-2022-JP",ctxt) || !wcsicmp(L"JIS",ctxt)) return CHARSET_JIS; else if (!wcsicmp(L"BIG5",ctxt) || !wcsicmp(L"BIG-5",ctxt)) return CHARSET_BIG5; else if (!wcsicmp(L"GB2312",ctxt) || !wcsicmp(L"GB-2312",ctxt)) return CHARSET_GB2312; else if (!wcsicmp(L"EUC_KR",ctxt) || !wcsicmp(L"EUC-KR",ctxt) || !wcsicmp(L"EUCKR",ctxt)) return CHARSET_EUCKR; else if (!wcsicmp(L"binary",ctxt)) return CHARSET_BINARY; return CHARSET_DEFAULT; } int Ccct::CharsetTextToID(const char *ctxt) { if (!stricmp("UTF-8",ctxt) || !stricmp("UTF8",ctxt)) return CHARSET_UTF8; else if (!stricmp("default",ctxt) || !stricmp("OSNative",ctxt)) return CHARSET_DEFAULT; else if (!stricmp("Shift_JIS",ctxt) || !stricmp("ShiftJIS",ctxt) || !stricmp("SJIS",ctxt)) return CHARSET_SJIS; else if (!stricmp("EUC_JP",ctxt) || !stricmp("EUC-JP",ctxt) || !stricmp("EUCJP",ctxt)) return CHARSET_EUCJP; else if (!stricmp("ISO-2022-JP",ctxt) || !stricmp("JIS",ctxt)) return CHARSET_JIS; else if (!stricmp("BIG5",ctxt) || !stricmp("BIG-5",ctxt)) return CHARSET_BIG5; else if (!stricmp("GB2312",ctxt) || !stricmp("GB-2312",ctxt)) return CHARSET_GB2312; else if (!stricmp("EUC_KR",ctxt) || !stricmp("EUC-KR",ctxt) || !stricmp("EUCKR",ctxt)) return CHARSET_EUCKR; else if (!stricmp("binary",ctxt)) return CHARSET_BINARY; return CHARSET_DEFAULT; } /* ----------------------------------------------------------------------- * 関数名 : Ccct::CharsetIDToText(A/W) * 機能概要: Charset 文字列->Charset ID * ----------------------------------------------------------------------- */ const wchar_t *Ccct::CharsetIDToTextW(const int charset) { if ( charset == CHARSET_UTF8 ) { return L"UTF-8"; } if ( charset == CHARSET_SJIS ) { return L"Shift_JIS"; } if ( charset == CHARSET_EUCJP ) { return L"EUC_JP"; } if ( charset == CHARSET_JIS ) { return L"ISO-2022-JP"; } if ( charset == CHARSET_BIG5 ) { return L"BIG5"; } if ( charset == CHARSET_GB2312 ) { return L"GB2312"; } if ( charset == CHARSET_EUCKR ) { return L"EUC_KR"; } if ( charset == CHARSET_BINARY ) { return L"binary"; } return L"default"; } const char *Ccct::CharsetIDToTextA(const int charset) { if ( charset == CHARSET_UTF8 ) { return "UTF-8"; } if ( charset == CHARSET_SJIS ) { return "Shift_JIS"; } if ( charset == CHARSET_EUCJP ) { return "EUC_JP"; } if ( charset == CHARSET_JIS ) { return "ISO-2022-JP"; } if ( charset == CHARSET_BIG5 ) { return "BIG5"; } if ( charset == CHARSET_GB2312 ) { return "GB2312"; } if ( charset == CHARSET_EUCKR ) { return "EUC_KR"; } if ( charset == CHARSET_BINARY ) { return "binary"; } return "default"; } /* ----------------------------------------------------------------------- * UTF-8変換用先行宣言 * ----------------------------------------------------------------------- */ size_t Ccct_ConvUTF8ToUnicode(aya::string_t &buf,const char* pStrIn); size_t Ccct_ConvUnicodeToUTF8(std::string &buf,const aya::char_t *pStrw); /* ----------------------------------------------------------------------- * 関数名 : Ccct::Ucs2ToMbcs * 機能概要: UTF-16BE -> MBCS へ文字列のコード変換 * ----------------------------------------------------------------------- */ static char* string_to_malloc(const std::string &str) { char* pch = (char*)malloc(str.length()+1); memcpy(pch,str.c_str(),str.length()+1); return pch; } char *Ccct::Ucs2ToMbcs(const aya::char_t *wstr, int charset) { return Ucs2ToMbcs(aya::string_t(wstr), charset); } //---- char *Ccct::Ucs2ToMbcs(const aya::string_t &wstr, int charset) { /*if ( charset == CHARSET_UTF8 ) { return string_to_malloc(babel::unicode_to_utf8(wstr)); } else if ( charset == CHARSET_SJIS ) { return string_to_malloc(babel::unicode_to_sjis(wstr)); } else if ( charset == CHARSET_EUCJP ) { return string_to_malloc(babel::unicode_to_euc(wstr)); } else if ( charset == CHARSET_JIS ) { return string_to_malloc(babel::unicode_to_jis(wstr)); }*/ if ( charset == CHARSET_UTF8 ) { std::string buf; Ccct_ConvUnicodeToUTF8(buf,wstr.c_str()); return string_to_malloc(buf); } else { return utf16be_to_mbcs(wstr.c_str(),charset); } } /* ----------------------------------------------------------------------- * 関数名 : Ccct::MbcsToUcs2 * 機能概要: MBCS -> UTF-16BE へ文字列のコード変換 * ----------------------------------------------------------------------- */ static aya::char_t* wstring_to_malloc(const aya::string_t &str) { size_t sz = (str.length()+1) * sizeof(aya::char_t); aya::char_t* pch = (aya::char_t*)malloc(sz); memcpy(pch,str.c_str(),sz); return pch; } aya::char_t *Ccct::MbcsToUcs2(const char *mstr, int charset) { return MbcsToUcs2(std::string(mstr), charset); } //---- aya::char_t *Ccct::MbcsToUcs2(const std::string &mstr, int charset) { /*if ( charset == CHARSET_UTF8 ) { return wstring_to_malloc(babel::utf8_to_unicode(mstr)); } else if ( charset == CHARSET_SJIS ) { return wstring_to_malloc(babel::sjis_to_unicode(mstr)); } else if ( charset == CHARSET_EUCJP ) { return wstring_to_malloc(babel::euc_to_unicode(mstr)); } else if ( charset == CHARSET_JIS ) { return wstring_to_malloc(babel::jis_to_unicode(mstr)); }*/ if ( charset == CHARSET_UTF8 ) { aya::string_t buf; Ccct_ConvUTF8ToUnicode(buf,mstr.c_str()); return wstring_to_malloc(buf); } else { return mbcs_to_utf16be(mstr.c_str(),charset); } } /* ----------------------------------------------------------------------- * 関数名 : Ccct::sys_setlocale * 機能概要: OSデフォルトの言語IDでロケール設定する * ----------------------------------------------------------------------- */ char *Ccct::sys_setlocale(int category) { return setlocale(category,""); } /* ----------------------------------------------------------------------- * 関数名 : Ccct::ccct_getcodepage * 機能概要: 言語ID->Windows CP * ----------------------------------------------------------------------- */ unsigned int Ccct::ccct_getcodepage(int charset) { if (charset == CHARSET_SJIS) { return 932; } else if (charset == CHARSET_EUCJP) { return 20932; } else if (charset == CHARSET_BIG5) { return 950; } else if (charset == CHARSET_GB2312) { return 936; } else if (charset == CHARSET_EUCKR) { return 949; } else if (charset == CHARSET_JIS) { return 50222; } else { #if defined(WIN32) || defined(_WIN32_WCE) return ::AreFileApisANSI() ? ::GetACP() : ::GetOEMCP(); #else return 0; #endif } } /* ----------------------------------------------------------------------- * 関数名 : Ccct::ccct_setlocale * 機能概要: 言語IDでロケール設定する * ----------------------------------------------------------------------- */ char *Ccct::ccct_setlocale(int category, int charset) { #ifdef POSIX if (charset == CHARSET_SJIS) { return setlocale(category, "ja_JP.SJIS"); } else if (charset == CHARSET_EUCJP) { return setlocale(category, "ja_JP.eucJP"); } else if (charset == CHARSET_BIG5) { return setlocale(category, "zh_TW.Big5"); } else if (charset == CHARSET_GB2312) { return setlocale(category, "zh_CN.GB2312"); } else if (charset == CHARSET_EUCKR) { return setlocale(category, "ko_KR.eucKR"); } else if (charset == CHARSET_JIS) { return setlocale(category, "ja_JP.SJIS"); } #else if (charset == CHARSET_SJIS) { return setlocale(category, ".932"); } else if (charset == CHARSET_EUCJP) { return setlocale(category, ".20932"); } else if (charset == CHARSET_BIG5) { return setlocale(category, ".950"); } else if (charset == CHARSET_GB2312) { return setlocale(category, ".936"); } else if (charset == CHARSET_EUCKR) { return setlocale(category, ".949"); } else if (charset == CHARSET_JIS) { return setlocale(category, ".50222"); } #endif else { return sys_setlocale(category); } } /* ----------------------------------------------------------------------- * setlocaleバリア * ----------------------------------------------------------------------- */ class CcctSetLocaleSwitcher { private: const char *m_oldLocale; int m_category; public: CcctSetLocaleSwitcher(int category,int charset) { m_category = category; m_oldLocale = setlocale(category,NULL); Ccct::ccct_setlocale(category,charset); } ~CcctSetLocaleSwitcher() { if ( m_oldLocale ) { setlocale(m_category,m_oldLocale); } } }; /* ----------------------------------------------------------------------- * 関数名 : Ccct::utf16be_to_mbcs * 機能概要: UTF-16BE -> MBCS へ文字列のコード変換 * ----------------------------------------------------------------------- */ char *Ccct::utf16be_to_mbcs(const aya::char_t *pUcsStr, int charset) { char *pAnsiStr = NULL; if (!pUcsStr) { return NULL; } if (!*pUcsStr) { char *p = (char*)malloc(1); p[0] = 0; return p; } #if defined(WIN32) || defined(_WIN32_WCE) int cp = ccct_getcodepage(charset); int alen = ::WideCharToMultiByte(cp,0,pUcsStr,-1,NULL,0,NULL,NULL); if ( alen <= 0 ) { return NULL; } pAnsiStr = (char*)malloc(alen+1+5); //add +5 for safety alen = ::WideCharToMultiByte(cp,0,pUcsStr,-1,pAnsiStr,alen+1,NULL,NULL); if ( alen <= 0 ) { return NULL; } pAnsiStr[alen] = 0; #else CcctSetLocaleSwitcher loc(LC_CTYPE, charset); size_t nLen = wcslen( pUcsStr); if (charset != CHARSET_BINARY) { if (pUcsStr[0] == static_cast<aya::char_t>(0xfeff) || pUcsStr[0] == static_cast<aya::char_t>(0xfffe)) { pUcsStr++; // 先頭にBOM(byte Order Mark)があれば,スキップする nLen--; } } //文字長×マルチバイト最大長+ゼロ終端 pAnsiStr = (char *)malloc((nLen*MB_CUR_MAX)+1); if (!pAnsiStr) { return NULL; } // 1文字ずつ変換する。 // まとめて変換すると、変換不能文字への対応が困難なので size_t i, nMbpos = 0; int nRet; for (i = 0; i < nLen; i++) { if (charset != CHARSET_BINARY) { nRet = wctomb(pAnsiStr+nMbpos, pUcsStr[i]); } else { pAnsiStr[nMbpos] = (char)(0x00ff & pUcsStr[i]); nRet = 1; } if ( nRet <= 0 ) { // can not conversion pAnsiStr[nMbpos++] = ' '; } else { nMbpos += nRet; } } pAnsiStr[nMbpos] = 0; #endif return pAnsiStr; } /* ----------------------------------------------------------------------- * 関数名 : Ccct::mbcs_to_utf16be * 機能概要: MBCS -> UTF-16 へ文字列のコード変換 * ----------------------------------------------------------------------- */ aya::char_t *Ccct::mbcs_to_utf16be(const char *pAnsiStr, int charset) { if (!pAnsiStr) { return NULL; } if (!*pAnsiStr) { aya::char_t* p = (aya::char_t*)malloc(2); p[0] = 0; return p; } #if defined(WIN32) || defined(_WIN32_WCE) size_t nLen = strlen(pAnsiStr); int cp = ccct_getcodepage(charset); int wlen = ::MultiByteToWideChar(cp,0,pAnsiStr,nLen,NULL,0); if ( wlen <= 0 ) { return NULL; } aya::char_t* pUcsStr = (aya::char_t*)malloc((wlen + 1 + 5) * sizeof(aya::char_t)); //add +5 for safety wlen = ::MultiByteToWideChar(cp,0,pAnsiStr,nLen,pUcsStr,wlen+1); if ( wlen <= 0 ) { return NULL; } pUcsStr[wlen] = 0; #else CcctSetLocaleSwitcher loc(LC_CTYPE, charset); size_t nLen = strlen(pAnsiStr); aya::char_t *pUcsStr = (aya::char_t *)malloc(sizeof(aya::char_t)*(nLen+7)); if (!pUcsStr) { return NULL; } // 1文字ずつ変換する。 // まとめて変換すると、変換不能文字への対応が困難なので size_t i, nMbpos = 0; int nRet; for (i = 0; i < nLen; ) { if (charset != CHARSET_BINARY) { nRet = mbtowc(pUcsStr+nMbpos, pAnsiStr+i, nLen-i); } else { pUcsStr[i]=static_cast<aya::char_t>(pAnsiStr[i]); nRet = 1; } if ( nRet <= 0 ) { // can not conversion pUcsStr[nMbpos++] = L' '; i += 1; } else { ++nMbpos; i += nRet; } } pUcsStr[nMbpos] = 0; #endif return pUcsStr; } /*-------------------------------------------- UTF-9をUTF-16に --------------------------------------------*/ size_t Ccct_ConvUTF8ToUnicode(aya::string_t &buf,const char* pStrIn) { unsigned char *pStr = (unsigned char*)pStrIn; unsigned char *pStrLast = pStr + strlen(pStrIn); unsigned char c; unsigned long tmp; while( pStr < pStrLast ){ c = *(pStr++); if( (c & 0x80) == 0 ){ //1Byte - 0??????? buf.append(1,(WORD)c); } /*else if( (c & 0xc0) == 0x80 ){ //1Byte - 10?????? -> 必ず2バイト目以降のため、単体で出たら不正 m_Str.Add() = (WORD)c; }*/ else if( (c & 0xe0) == 0xc0 ){ //2Byte - 110????? tmp = static_cast<DWORD>(c & 0x1f) << 6; //下5bit - 10-6 tmp |= static_cast<DWORD>(*(pStr++) & 0x3f); //下6bit - 5-0 buf.append(1,static_cast<WORD>(tmp)); } else if( (c & 0xf0) == 0xe0 ){ //3Byte - 1110???? tmp = static_cast<DWORD>(c & 0x0f) << 12; //下4bit - 15-12 tmp |= static_cast<DWORD>(*(pStr++) & 0x3f) << 6; //下6bit - 11-6 tmp |= static_cast<DWORD>(*(pStr++) & 0x3f); //下6bit - 5-0 if ( tmp != 0xfeff && tmp != 0xfffe ) { //BOMでない buf.append(1,static_cast<WORD>(tmp)); } } else if( (c & 0xf8) == 0xf0 ){ //4Byte - 11110??? UTF-16 Surrogate tmp = static_cast<DWORD>(c & 0x07) << 18; //下3bit -> 20-18 tmp |= static_cast<DWORD>(*(pStr++) & 0x3f) << 12; //下6bit - 17-12 tmp |= static_cast<DWORD>(*(pStr++) & 0x3f) << 6; //下6bit - 11-6 tmp |= static_cast<DWORD>(*(pStr++) & 0x3f); //下6bit - 5-0 tmp -= 0x10000; buf.append(1,(WORD)(0xD800U | ((tmp >> 10) & 0x3FF))); //上位サロゲート buf.append(1,(WORD)(0xDC00U | (tmp & 0x3FF))); //下位サロゲート } else if( (c & 0xfc) == 0xf8 ){ //5Byte - 111110?? -- UCS-4 pStr += 4; //無視 } else if( (c & 0xfe) == 0xfc ){ //6Byte - 1111110? -- UCS-4 pStr += 5; //無視 } /*else { // - 11111110 , 11111111 (0xfe,0xff) - そんな文字あるかい! m_Str.Add() = (WORD)c; }*/ } return buf.length(); } /*-------------------------------------------- UTF-16をUTF-8に --------------------------------------------*/ size_t Ccct_ConvUnicodeToUTF8(std::string &buf,const aya::char_t *pStrw) { aya::char_t w; unsigned long surrogateTemp; size_t length = wcslen(pStrw); size_t i = 0; buf.reserve(length*4+1); //4倍まで (UTF-8 5-6byte領域はUCS-2からの変換では存在しない) while(i < length){ w = pStrw[i++]; if (w < 0x80) { //1byte buf.append(1,(char)(BYTE)w); //5-0 } else if ( w < 0x0800 ) { //2byte buf.append(1,(char)(BYTE)((w >> 6) & 0x001f) | 0xc0); //10-6 buf.append(1,(char)(BYTE)(w & 0x3f) | 0x80); //5-0 } else { if ( (w & 0xF800) == 0xD800 ) { //4byte サロゲートページ D800->DFFF surrogateTemp = ( ( (w & 0x3FF) << 10 ) | (pStrw[i++] & 0x3FF) ) + 0x10000; buf.append(1,(char)(BYTE)((surrogateTemp >> 18) & 0x07) | 0xf0); //20-18 buf.append(1,(char)(BYTE)((surrogateTemp >> 12) & 0x3f) | 0x80); //17-12 buf.append(1,(char)(BYTE)((surrogateTemp >> 6 ) & 0x3f) | 0x80); //11-6 buf.append(1,(char)(BYTE)(surrogateTemp & 0x3f) | 0x80); //5-0 } else { //3byte buf.append(1,(char)(BYTE)((w >> 12) & 0x0f) | 0xe0); //15-12 buf.append(1,(char)(BYTE)((w >> 6) & 0x3f) | 0x80); //11-6 buf.append(1,(char)(BYTE)(w & 0x3f) | 0x80); //5-0 } } } return buf.length(); }
26.737609
104
0.522953
7ed02d68dd213deeafc9942003012d4865f18e14
10,429
hh
C++
extern/glow/src/glow/objects/Program.hh
huzjkevin/portal_maze_zgl
efb32b1c3430f20638c1401095999ecb4d0af5aa
[ "MIT" ]
null
null
null
extern/glow/src/glow/objects/Program.hh
huzjkevin/portal_maze_zgl
efb32b1c3430f20638c1401095999ecb4d0af5aa
[ "MIT" ]
null
null
null
extern/glow/src/glow/objects/Program.hh
huzjkevin/portal_maze_zgl
efb32b1c3430f20638c1401095999ecb4d0af5aa
[ "MIT" ]
null
null
null
#pragma once #include <glow/common/gltypeinfo.hh> #include <glow/common/macro_join.hh> #include <glow/common/nodiscard.hh> #include <glow/common/non_copyable.hh> #include <glow/common/property.hh> #include <glow/common/shared.hh> #include <glow/gl.hh> #include <glow/util/LocationMapping.hh> #include "NamedObject.hh" #include "raii/UsedProgram.hh" #include <map> #include <string> #include <vector> // only vec/mat types #include <glm/matrix.hpp> namespace glow { GLOW_SHARED(class, Sampler); GLOW_SHARED(class, Shader); GLOW_SHARED(class, Program); GLOW_SHARED(class, LocationMapping); GLOW_SHARED(class, UniformState); GLOW_SHARED(class, Texture); GLOW_SHARED(class, Texture2D); GLOW_SHARED(class, UniformBuffer); GLOW_SHARED(class, ShaderStorageBuffer); GLOW_SHARED(class, AtomicCounterBuffer); GLOW_SHARED(class, Buffer); class Program final : public NamedObject<Program, GL_PROGRAM> { public: struct UniformInfo { std::string name; GLint location = -1; GLint size = -1; GLenum type = GL_INVALID_ENUM; bool wasSet = false; }; private: /// If true, shader check for shader reloading periodically static bool sCheckShaderReloading; /// OpenGL object name GLuint mObjectName; /// List of attached shader std::vector<SharedShader> mShader; /// Last time of reload checking int64_t mLastReloadCheck = 0; /// Last time this shader was linked int64_t mLastTimeLinked = 0; /// Uniform lookup cache /// Invalidates after link mutable std::vector<UniformInfo> mUniformCache; /// Texture unit mapping LocationMapping mTextureUnitMapping; /// Bounds texture (idx = unit) std::vector<SharedTexture> mTextures; /// Bounds texture sampler (idx = unit) std::vector<SharedSampler> mSamplers; /// Locations for in-VS-attributes /// At any point, the mapping saved here must be consistent (i.e. a superset) of the GPU mapping SharedLocationMapping mAttributeMapping; /// Locations for out-FS-attributes /// At any point, the mapping saved here must be consistent (i.e. a superset) of the GPU mapping SharedLocationMapping mFragmentMapping; /// Friend for negotiating mAttributeMapping friend class VertexArray; friend struct BoundVertexArray; /// Friend for negotiating mFragmentMapping friend class Framebuffer; friend struct BoundFramebuffer; /// Mapping for uniform buffers LocationMapping mUniformBufferMapping; /// Bound uniform buffer std::map<std::string, SharedUniformBuffer> mUniformBuffers; /// Mapping for shaderStorage buffers LocationMapping mShaderStorageBufferMapping; /// Bound shaderStorage buffer std::map<std::string, SharedShaderStorageBuffer> mShaderStorageBuffers; /// Bound AtomicCounter buffer std::map<int, SharedAtomicCounterBuffer> mAtomicCounterBuffers; /// List of varyings for transform feedback std::vector<std::string> mTransformFeedbackVaryings; /// Buffer mode for transform feedback GLenum mTransformFeedbackMode; /// if true, this program is linked properly for transform feedback bool mIsLinkedForTransformFeedback = false; /// true if already checked for layout(loc) bool mCheckedForAttributeLocationLayout = false; /// true if already checked for layout(loc) bool mCheckedForFragmentLocationLayout = false; /// disables unchanged uniform warning bool mWarnOnUnchangedUniforms = true; /// true if already checked for unchanged uniforms bool mCheckedUnchangedUniforms = false; private: /// Internal linking /// returns false on errors bool linkAndCheckErrors(); /// Restores additional "program state", like textures and shader buffers void restoreExtendedState(); /// Reset frag location check /// Necessary because frags cannot be queried ... void resetFragmentLocationCheck() { mCheckedForFragmentLocationLayout = false; } /// see public: version UniformInfo* getUniformInfo(std::string const& name); /// returns uniform location and sets "wasSet" to true /// Also verifies that the uniform types match GLint useUniformLocationAndVerify(std::string const& name, GLint size, GLenum type); public: // properties GLuint getObjectName() const { return mObjectName; } std::vector<SharedShader> const& getShader() const { return mShader; } SharedLocationMapping const& getAttributeMapping() const { return mAttributeMapping; } SharedLocationMapping const& getFragmentMapping() const { return mFragmentMapping; } LocationMapping const& getTextureUnitMapping() const { return mTextureUnitMapping; } GLOW_GETTER(LastTimeLinked); GLOW_PROPERTY(WarnOnUnchangedUniforms); /// returns true iff a shader with this type is attached bool hasShaderType(GLenum type) const; /// Gets the currently used program (nullptr if none) static UsedProgram* getCurrentProgram(); /// Modifies shader reloading state static void setShaderReloading(bool enabled); public: /// Checks if all bound textures have valid mipmaps void validateTextureMipmaps() const; /// if not already done so: /// checks if any uniform is used but not set void checkUnchangedUniforms(); public: // gl functions without use /// Returns the in-shader location of the given uniform name /// Is -1 if not found or optimized out (!) /// Uses an internal cache to speedup the call GLint getUniformLocation(std::string const& name) const; /// Returns information about a uniform /// If location is -1, information is nullptr /// (Returned pointer is invalidated if shader is relinked) UniformInfo const* getUniformInfo(std::string const& name) const; /// Returns the index of a uniform block GLuint getUniformBlockIndex(std::string const& name) const; /// ========================================= UNIFORMS - START ========================================= /// Getter for uniforms /// If you get linker errors, the type is not supported /// Returns default-constructed values for optimized uniforms /// Usage: /// auto pos = prog->getUniform<glm::vec3>("uPosition"); /// /// LIMITATIONS: /// currently doesn't work for arrays/structs /// /// Supported types: /// * bool /// * float /// * int /// * unsigned int /// * [ uib]vec[234] /// * mat[234] /// * mat[234]x[234] template <typename DataT> DataT getUniform(std::string const& name) const { DataT value; auto loc = getUniformLocation(name); if (loc >= 0) implGetUniform(glTypeOf<DataT>::basetype, loc, (void*)&value); else value = DataT{}; return value; } /// ========================================== UNIFORMS - END ========================================== private: /// Internal generic getter for uniforms void implGetUniform(detail::glBaseType type, GLint loc, void* data) const; public: Program(); ~Program(); /// Returns true iff program is linked properly bool isLinked() const; /// Returns a list of all attribute locations /// Depending on driver, this only returns "used" attributes std::vector<std::pair<std::string, int>> extractAttributeLocations(); /// Attaches the given shader to this program /// Requires re-linking! void attachShader(SharedShader const& shader); /// Links all attached shader into the program. /// Has to be done each time shader and/or IO locations are changed /// CAUTION: linking deletes all currently set uniform values! void link(bool saveUniformState = true); /// Configures this shader for use with transform feedback /// NOTE: cannot be done while shader is in use void configureTransformFeedback(std::vector<std::string> const& varyings, GLenum bufferMode = GL_INTERLEAVED_ATTRIBS); /// Returns true if transform feedback can be used bool isConfiguredForTransformFeedback() const { return mTransformFeedbackVaryings.size() > 0; } /// Extracts all active uniforms and saves them into a UniformState object /// This function should not be used very frequently SharedUniformState getUniforms() const; /// Binds a uniform buffer to a given block name /// DOES NOT REQUIRE PROGRAM USE void setUniformBuffer(std::string const& bufferName, SharedUniformBuffer const& buffer); /// Binds a shader storage buffer to a given block name /// DOES NOT REQUIRE PROGRAM USE void setShaderStorageBuffer(std::string const& bufferName, SharedShaderStorageBuffer const& buffer); /// Binds an atomic counter buffer to a binding point /// DOES NOT REQUIRE PROGRAM USE void setAtomicCounterBuffer(int bindingPoint, SharedAtomicCounterBuffer const& buffer); /// Verifies registered offsets in the uniform buffer and emits errors if they don't match /// Return false if verification failed bool verifyUniformBuffer(std::string const& bufferName, SharedUniformBuffer const& buffer); /// Activates this shader program. /// Deactivation is done when the returned object runs out of scope. GLOW_NODISCARD UsedProgram use() { return {this}; } friend UsedProgram; public: // static construction /// Creates a shader program from a list of shaders /// Attaches shader and links the program /// Program can be used directly after this static SharedProgram create(std::vector<SharedShader> const& shader); static SharedProgram create(SharedShader const& shader) { return create(std::vector<SharedShader>({shader})); } /// Creates a program from either a single file or auto-discovered shader files /// E.g. createFromFile("mesh"); /// will use mesh.vsh as vertex shader and mesh.fsh as fragment shader if available /// See common/shader_endings.cc for a list of available endings /// Will also traverse "dots" if file not found to check for base versions /// E.g. createFromFile("mesh.opaque"); /// might find mesh.opaque.fsh and mesh.vsh static SharedProgram createFromFile(std::string const& fileOrBaseName); /// Creates a program from a list of explicitly named files /// Shader type is determined by common/shader_endings.cc static SharedProgram createFromFiles(std::vector<std::string> const& filenames); }; }
36.592982
122
0.698149
7ed08d18a4a54352dac118c13d60f2c6715f9bb7
1,092
cc
C++
leetcode/p6.cc
lhyqie/lhyqie.github.io
d986ac4afddf169a07d4f1de95bcc737368e212b
[ "MIT" ]
null
null
null
leetcode/p6.cc
lhyqie/lhyqie.github.io
d986ac4afddf169a07d4f1de95bcc737368e212b
[ "MIT" ]
null
null
null
leetcode/p6.cc
lhyqie/lhyqie.github.io
d986ac4afddf169a07d4f1de95bcc737368e212b
[ "MIT" ]
null
null
null
#include "common.h" class Solution { public: string longestPalindrome(string s) { int start = 0, max_len = 1; for(int i = 0; i < s.size(); i++){ int len1 = expandAroundCenter(s, i, i); int len2 = expandAroundCenter(s, i, i+1); int len = std::max(len1, len2); if(std::max(len1, len2) > max_len){ // when len is odd e.g. ...abcba... len = 5 center is i => start = i - (len-1)/2 = i - 2 // when len is even e.g. ...abba... len = 4 center is i => start = i - (len-1)/2 = i - 1 start = i - (len-1)/2; max_len = len; } // std::cout << "i=" << i << " len1=" << len1 << " len2=" << len2 << " start=" << start << "\n" ; } return s.substr(start, max_len); } private: int expandAroundCenter(const string& s, int left, int right){ while(left >= 0 && right< s.size() && s[left] == s[right]){ left --; right ++; } return right - left - 1; // right - left + 1 - 2 } }; int main() { std::cout << Solution().longestPalindrome("babbc"); return 0; }
30.333333
112
0.494505
7ed11ddecfb406867da6e2c1f16708dab04c588b
1,739
hpp
C++
include/pcl_ros_wrapper/registration/warp_point_2d.hpp
larics/pcl_ros_wrapper
cbb4fb2c74a463cee8d5c42dcd8cbabb407b617f
[ "BSD-3-Clause" ]
null
null
null
include/pcl_ros_wrapper/registration/warp_point_2d.hpp
larics/pcl_ros_wrapper
cbb4fb2c74a463cee8d5c42dcd8cbabb407b617f
[ "BSD-3-Clause" ]
null
null
null
include/pcl_ros_wrapper/registration/warp_point_2d.hpp
larics/pcl_ros_wrapper
cbb4fb2c74a463cee8d5c42dcd8cbabb407b617f
[ "BSD-3-Clause" ]
1
2021-03-31T12:42:13.000Z
2021-03-31T12:42:13.000Z
#ifndef WARP_POINT_2D #define WARP_POINT_2D #pragma once #include <pcl/registration/warp_point_rigid.h> #include <boost/shared_ptr.hpp> namespace pcl { namespace registration { /** \brief @b WarpPoint2D enables 3D (1D rotation around yaw + 2D translation) * transformations for points. * * \note The class is templated on the source and target point types as well as on the * output scalar of the transformation matrix (i.e., float or double). Default: float. * \author Radu B. Rusu * \ingroup registration */ template<typename PointSourceT, typename PointTargetT, typename Scalar = float> class WarpPoint2D : public WarpPointRigid<PointSourceT, PointTargetT, Scalar> { public: using Matrix4 = typename WarpPointRigid<PointSourceT, PointTargetT, Scalar>::Matrix4; using VectorX = typename WarpPointRigid<PointSourceT, PointTargetT, Scalar>::VectorX; using Ptr = boost::shared_ptr<WarpPoint2D<PointSourceT, PointTargetT, Scalar>>; using ConstPtr = boost::shared_ptr<const WarpPoint2D<PointSourceT, PointTargetT, Scalar>>; /** \brief Constructor. */ WarpPoint2D() : WarpPointRigid<PointSourceT, PointTargetT, Scalar>(2) {} /** \brief Empty destructor */ ~WarpPoint2D() {} /** \brief Set warp parameters. * \param[in] p warp parameters (tx ty rz) */ void setParam(const VectorX &p) override { assert(p.rows() == this->getDimension()); Matrix4 &trans = this->transform_matrix_; trans = Matrix4::Identity(); // Copy the rotation and translation components trans.block(0, 3, 4, 1) = Eigen::Matrix<Scalar, 4, 1>(p[0], p[1], 0, 1.0); } }; }// namespace registration }// namespace pcl #endif /* WARP_POINT_2D */
32.811321
89
0.693502
7ed9e9e405f5aad41a90800b91beedbb009328e9
769
hpp
C++
include/Version.hpp
marcosivni/dicomlib
dd268d07368ff4f1ffd1f94cdaa1e2dbf30bc5c7
[ "BSD-3-Clause" ]
null
null
null
include/Version.hpp
marcosivni/dicomlib
dd268d07368ff4f1ffd1f94cdaa1e2dbf30bc5c7
[ "BSD-3-Clause" ]
null
null
null
include/Version.hpp
marcosivni/dicomlib
dd268d07368ff4f1ffd1f94cdaa1e2dbf30bc5c7
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************ * DICOMLIB * Copyright 2003 Sunnybrook and Women's College Health Science Center * Implemented by Trevor Morgan (morgan@sten.sunnybrook.utoronto.ca) * * See LICENSE.txt for copyright and licensing info. *************************************************************************/ #ifndef VERSION_HPP_INCLUDE_GUARD_U62KI43SNTDB4 #define VERSION_HPP_INCLUDE_GUARD_U62KI43SNTDB4 namespace dicom { //!library meta-information, such as version. namespace library { extern const char* name; extern const char* version; extern const int major_version; extern const int minor_version; extern const int revision; }//namespace library } #endif //VERSION_HPP_INCLUDE_GUARD_U62KI43SNTDB4
26.517241
74
0.642393
7edaec75b0cf2648a7cee0b07f42f61f99fa1368
389
cpp
C++
cppcode/201710_12/reference.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
cppcode/201710_12/reference.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
cppcode/201710_12/reference.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main() { int a=1; int &b=a; int c=b; b=2; cout<<"a="<<a<<",b="<<b<<",c="<<c<<endl; int d[]={1,2,3,4,5}; int(&e)[5]=d; for(int i=0;i<sizeof(d)/sizeof(d[0]);i++) { e[i]=e[i]*10+e[i]; } for(int i=0;i<sizeof(d)/sizeof(d[0]);i++) { cout<<d[i]<<endl; } return 0; }
16.913043
45
0.411311
7edb7feacdeb2c8a27981b7a9ea1858e62205737
2,881
cpp
C++
algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/nvbio/nvbio-test/fastq_test.cpp
mfkiwl/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
[ "BSD-3-Clause" ]
2,111
2019-01-29T07:01:32.000Z
2022-03-29T06:48:14.000Z
algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/nvbio/nvbio-test/fastq_test.cpp
mfkiwl/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
[ "BSD-3-Clause" ]
131
2019-02-18T10:56:18.000Z
2021-09-27T12:07:00.000Z
algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/nvbio/nvbio-test/fastq_test.cpp
mfkiwl/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
[ "BSD-3-Clause" ]
421
2019-02-12T07:59:18.000Z
2022-03-27T05:22:01.000Z
/* * nvbio * Copyright (c) 2011-2014, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <nvbio/fastq/fastq.h> using namespace nvbio; namespace { struct Writer { Writer() : n(0) {} void push_back(const uint32 read_len, const char* name, const uint8* bp, const uint8* q) { #if 0 if ((n & 0x00FF) == 0) { char read[16*1024]; for (uint32 i = 0; i < read_len; ++i) read[i] = bp[i]; read[read_len] = '\0'; fprintf( stderr, " len: %u, read: %s\n", read_len, read ); } #endif n++; } uint32 n; }; } // anonymous namespace int fastq_test(const char* filename) { fprintf(stderr, "FASTQ test... started\n"); FASTQ_file fastq_file( filename ); if (fastq_file.valid() == false) { fprintf(stderr, "*** error *** : file \"%s\" not found\n", filename); return 1; } FASTQ_reader<FASTQ_file> fastq( fastq_file ); Writer writer; int n; while ((n = fastq.read( 100u, writer ))) { if (n < 0) { fprintf(stderr, "*** parsing error ***\n"); char error[1024]; fastq.error_string( error ); fprintf(stderr, " %s\n", error); return 1; } } fprintf(stderr, "FASTQ test... done: %u reads\n", writer.n); return 0; }
31.659341
92
0.645262
7edf5e50fc97e2e4a115438d0fe06804eb043f50
1,648
hpp
C++
graph_tree/reroot.hpp
hotman78/cpplib
c2f85c8741cdd0b731a5aa828b28b38c70c8d699
[ "CC0-1.0" ]
null
null
null
graph_tree/reroot.hpp
hotman78/cpplib
c2f85c8741cdd0b731a5aa828b28b38c70c8d699
[ "CC0-1.0" ]
null
null
null
graph_tree/reroot.hpp
hotman78/cpplib
c2f85c8741cdd0b731a5aa828b28b38c70c8d699
[ "CC0-1.0" ]
null
null
null
#pragma once #include<vector> /** * @brief 全方位木DP */ template<typename T,typename F,typename Fix> struct reroot{ std::vector<std::vector<long long>>g; std::vector<int>p_list; std::vector<T>p_table; std::vector<bool>p_checked; std::vector<map<int,T>>table; std::vector<T>ans; T e; F f; Fix fix; reroot(const std::vector<std::vector<long long>>& g,T e,F f=F(),Fix fix=Fix()):g(g),e(e),f(f),fix(fix){ int n=g.size(); p_list.resize(n,-1); p_checked.resize(n,0); table.resize(n); p_table.resize(n,e); ans.resize(n,e); dfs1(0,-1); for(int i=0;i<n;++i)ans[i]=dfs2(i,-1); } T dfs1(int n,int p){ p_list[n]=p; T tmp1=e,tmp2=e; std::vector<T>tmp(g[n].size()); rep(i,g[n].size()){ int t=g[n][i]; if(t==p)continue; table[n][t]=tmp1; tmp1=f(tmp1,tmp[i]=dfs1(t,n)); } for(int i=g[n].size()-1;i>=0;--i){ int t=g[n][i]; if(t==p)continue; table[n][t]=f(table[n][t],tmp2); tmp2=f(tmp[i],tmp2); } return fix(table[n][p]=tmp1,n,p); } T dfs2(int n,int p){ if(n==-1){ return e; } if(!p_checked[n]){ p_checked[n]=1; p_table[n]=dfs2(p_list[n],n); } if(p==-1){ return f(table[n][p_list[n]],p_table[n]); }else{ if(p_list[n]==-1)return fix(table[n][p],n,p); else return fix(f(table[n][p],p_table[n]),n,p); } } vector<T>query(){ return ans; } };
25.353846
107
0.462985
7ee4b87260e8806d0a41f06e5a6ee005bf9bf864
1,963
cpp
C++
apps/opencs/view/doc/operations.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/opencs/view/doc/operations.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/opencs/view/doc/operations.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#include "operations.hpp" #include <QVBoxLayout> #include <QHBoxLayout> #include "operation.hpp" CSVDoc::Operations::Operations() { /// \todo make widget height fixed (exactly the height required to display all operations) setFeatures (QDockWidget::NoDockWidgetFeatures); QWidget *widgetContainer = new QWidget (this); mLayout = new QVBoxLayout; widgetContainer->setLayout (mLayout); setWidget (widgetContainer); setVisible (false); setFixedHeight (widgetContainer->height()); setTitleBarWidget (new QWidget (this)); } void CSVDoc::Operations::setProgress (int current, int max, int type, int threads) { for (std::vector<Operation *>::iterator iter (mOperations.begin()); iter!=mOperations.end(); ++iter) if ((*iter)->getType()==type) { (*iter)->setProgress (current, max, threads); return; } int oldCount = mOperations.size(); int newCount = oldCount + 1; Operation *operation = new Operation (type, this); connect (operation, SIGNAL (abortOperation (int)), this, SIGNAL (abortOperation (int))); mLayout->addLayout (operation->getLayout()); mOperations.push_back (operation); operation->setProgress (current, max, threads); if ( oldCount > 0) setFixedHeight (height()/oldCount * newCount); setVisible (true); } void CSVDoc::Operations::quitOperation (int type) { for (std::vector<Operation *>::iterator iter (mOperations.begin()); iter!=mOperations.end(); ++iter) if ((*iter)->getType()==type) { int oldCount = mOperations.size(); int newCount = oldCount - 1; mLayout->removeItem ((*iter)->getLayout()); (*iter)->deleteLater(); mOperations.erase (iter); if (oldCount > 1) setFixedHeight (height() / oldCount * newCount); else setVisible (false); break; } }
28.042857
104
0.620479
7ee4c63995bffaf76d26ee7753c7496bf6dd7647
10,720
cpp
C++
evs/src/v2/model/ListSnapshotsRequest.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
evs/src/v2/model/ListSnapshotsRequest.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
null
null
null
evs/src/v2/model/ListSnapshotsRequest.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/evs/v2/model/ListSnapshotsRequest.h" namespace HuaweiCloud { namespace Sdk { namespace Evs { namespace V2 { namespace Model { ListSnapshotsRequest::ListSnapshotsRequest() { offset_ = 0; offsetIsSet_ = false; limit_ = 0; limitIsSet_ = false; name_ = ""; nameIsSet_ = false; status_ = ""; statusIsSet_ = false; volumeId_ = ""; volumeIdIsSet_ = false; availabilityZone_ = ""; availabilityZoneIsSet_ = false; id_ = ""; idIsSet_ = false; dedicatedStorageName_ = ""; dedicatedStorageNameIsSet_ = false; dedicatedStorageId_ = ""; dedicatedStorageIdIsSet_ = false; serviceType_ = ""; serviceTypeIsSet_ = false; enterpriseProjectId_ = ""; enterpriseProjectIdIsSet_ = false; } ListSnapshotsRequest::~ListSnapshotsRequest() = default; void ListSnapshotsRequest::validate() { } web::json::value ListSnapshotsRequest::toJson() const { web::json::value val = web::json::value::object(); if(offsetIsSet_) { val[utility::conversions::to_string_t("offset")] = ModelBase::toJson(offset_); } if(limitIsSet_) { val[utility::conversions::to_string_t("limit")] = ModelBase::toJson(limit_); } if(nameIsSet_) { val[utility::conversions::to_string_t("name")] = ModelBase::toJson(name_); } if(statusIsSet_) { val[utility::conversions::to_string_t("status")] = ModelBase::toJson(status_); } if(volumeIdIsSet_) { val[utility::conversions::to_string_t("volume_id")] = ModelBase::toJson(volumeId_); } if(availabilityZoneIsSet_) { val[utility::conversions::to_string_t("availability_zone")] = ModelBase::toJson(availabilityZone_); } if(idIsSet_) { val[utility::conversions::to_string_t("id")] = ModelBase::toJson(id_); } if(dedicatedStorageNameIsSet_) { val[utility::conversions::to_string_t("dedicated_storage_name")] = ModelBase::toJson(dedicatedStorageName_); } if(dedicatedStorageIdIsSet_) { val[utility::conversions::to_string_t("dedicated_storage_id")] = ModelBase::toJson(dedicatedStorageId_); } if(serviceTypeIsSet_) { val[utility::conversions::to_string_t("service_type")] = ModelBase::toJson(serviceType_); } if(enterpriseProjectIdIsSet_) { val[utility::conversions::to_string_t("enterprise_project_id")] = ModelBase::toJson(enterpriseProjectId_); } return val; } bool ListSnapshotsRequest::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("offset"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("offset")); if(!fieldValue.is_null()) { int32_t refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setOffset(refVal); } } if(val.has_field(utility::conversions::to_string_t("limit"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("limit")); if(!fieldValue.is_null()) { int32_t refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setLimit(refVal); } } if(val.has_field(utility::conversions::to_string_t("name"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("name")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setName(refVal); } } if(val.has_field(utility::conversions::to_string_t("status"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("status")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setStatus(refVal); } } if(val.has_field(utility::conversions::to_string_t("volume_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("volume_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setVolumeId(refVal); } } if(val.has_field(utility::conversions::to_string_t("availability_zone"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("availability_zone")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setAvailabilityZone(refVal); } } if(val.has_field(utility::conversions::to_string_t("id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setId(refVal); } } if(val.has_field(utility::conversions::to_string_t("dedicated_storage_name"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("dedicated_storage_name")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setDedicatedStorageName(refVal); } } if(val.has_field(utility::conversions::to_string_t("dedicated_storage_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("dedicated_storage_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setDedicatedStorageId(refVal); } } if(val.has_field(utility::conversions::to_string_t("service_type"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("service_type")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setServiceType(refVal); } } if(val.has_field(utility::conversions::to_string_t("enterprise_project_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("enterprise_project_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setEnterpriseProjectId(refVal); } } return ok; } int32_t ListSnapshotsRequest::getOffset() const { return offset_; } void ListSnapshotsRequest::setOffset(int32_t value) { offset_ = value; offsetIsSet_ = true; } bool ListSnapshotsRequest::offsetIsSet() const { return offsetIsSet_; } void ListSnapshotsRequest::unsetoffset() { offsetIsSet_ = false; } int32_t ListSnapshotsRequest::getLimit() const { return limit_; } void ListSnapshotsRequest::setLimit(int32_t value) { limit_ = value; limitIsSet_ = true; } bool ListSnapshotsRequest::limitIsSet() const { return limitIsSet_; } void ListSnapshotsRequest::unsetlimit() { limitIsSet_ = false; } std::string ListSnapshotsRequest::getName() const { return name_; } void ListSnapshotsRequest::setName(const std::string& value) { name_ = value; nameIsSet_ = true; } bool ListSnapshotsRequest::nameIsSet() const { return nameIsSet_; } void ListSnapshotsRequest::unsetname() { nameIsSet_ = false; } std::string ListSnapshotsRequest::getStatus() const { return status_; } void ListSnapshotsRequest::setStatus(const std::string& value) { status_ = value; statusIsSet_ = true; } bool ListSnapshotsRequest::statusIsSet() const { return statusIsSet_; } void ListSnapshotsRequest::unsetstatus() { statusIsSet_ = false; } std::string ListSnapshotsRequest::getVolumeId() const { return volumeId_; } void ListSnapshotsRequest::setVolumeId(const std::string& value) { volumeId_ = value; volumeIdIsSet_ = true; } bool ListSnapshotsRequest::volumeIdIsSet() const { return volumeIdIsSet_; } void ListSnapshotsRequest::unsetvolumeId() { volumeIdIsSet_ = false; } std::string ListSnapshotsRequest::getAvailabilityZone() const { return availabilityZone_; } void ListSnapshotsRequest::setAvailabilityZone(const std::string& value) { availabilityZone_ = value; availabilityZoneIsSet_ = true; } bool ListSnapshotsRequest::availabilityZoneIsSet() const { return availabilityZoneIsSet_; } void ListSnapshotsRequest::unsetavailabilityZone() { availabilityZoneIsSet_ = false; } std::string ListSnapshotsRequest::getId() const { return id_; } void ListSnapshotsRequest::setId(const std::string& value) { id_ = value; idIsSet_ = true; } bool ListSnapshotsRequest::idIsSet() const { return idIsSet_; } void ListSnapshotsRequest::unsetid() { idIsSet_ = false; } std::string ListSnapshotsRequest::getDedicatedStorageName() const { return dedicatedStorageName_; } void ListSnapshotsRequest::setDedicatedStorageName(const std::string& value) { dedicatedStorageName_ = value; dedicatedStorageNameIsSet_ = true; } bool ListSnapshotsRequest::dedicatedStorageNameIsSet() const { return dedicatedStorageNameIsSet_; } void ListSnapshotsRequest::unsetdedicatedStorageName() { dedicatedStorageNameIsSet_ = false; } std::string ListSnapshotsRequest::getDedicatedStorageId() const { return dedicatedStorageId_; } void ListSnapshotsRequest::setDedicatedStorageId(const std::string& value) { dedicatedStorageId_ = value; dedicatedStorageIdIsSet_ = true; } bool ListSnapshotsRequest::dedicatedStorageIdIsSet() const { return dedicatedStorageIdIsSet_; } void ListSnapshotsRequest::unsetdedicatedStorageId() { dedicatedStorageIdIsSet_ = false; } std::string ListSnapshotsRequest::getServiceType() const { return serviceType_; } void ListSnapshotsRequest::setServiceType(const std::string& value) { serviceType_ = value; serviceTypeIsSet_ = true; } bool ListSnapshotsRequest::serviceTypeIsSet() const { return serviceTypeIsSet_; } void ListSnapshotsRequest::unsetserviceType() { serviceTypeIsSet_ = false; } std::string ListSnapshotsRequest::getEnterpriseProjectId() const { return enterpriseProjectId_; } void ListSnapshotsRequest::setEnterpriseProjectId(const std::string& value) { enterpriseProjectId_ = value; enterpriseProjectIdIsSet_ = true; } bool ListSnapshotsRequest::enterpriseProjectIdIsSet() const { return enterpriseProjectIdIsSet_; } void ListSnapshotsRequest::unsetenterpriseProjectId() { enterpriseProjectIdIsSet_ = false; } } } } } }
24.814815
116
0.673134
7ee5dd311a7c3ec42cf4eae373c6b0f129fb3ffa
2,332
cpp
C++
School Olympiads/Kazakhstan IOI Team Selection Camp 2018/Day 4/c.cpp
SuperPuperMegaUltraEpicGoldenHacker/Competetive-Programming
ab1ca0d0d2187b561750d547e155e768951d29a0
[ "MIT" ]
null
null
null
School Olympiads/Kazakhstan IOI Team Selection Camp 2018/Day 4/c.cpp
SuperPuperMegaUltraEpicGoldenHacker/Competetive-Programming
ab1ca0d0d2187b561750d547e155e768951d29a0
[ "MIT" ]
null
null
null
School Olympiads/Kazakhstan IOI Team Selection Camp 2018/Day 4/c.cpp
SuperPuperMegaUltraEpicGoldenHacker/Competetive-Programming
ab1ca0d0d2187b561750d547e155e768951d29a0
[ "MIT" ]
null
null
null
# include <bits/stdc++.h> # define F first # define S second # define mp make_pair // everything go according to my plan # define pb push_back # define sz(a) (int)(a.size()) # define vec vector // shimkenttin kyzdary, dzyn, dzyn, dzyn... # define y1 Y_U_NO_y1 # define left Y_U_NO_left # define right Y_U_NO_right using namespace std; typedef pair <int, int> pii; typedef long long ll; typedef long double ld; const int Mod = (int)1e9 + 7; const int MX = 1073741822; const ll MXLL = 4e18; const int Sz = 1110111; // a pinch of soul inline void Read_rap () { ios_base :: sync_with_stdio(0); cin.tie(0); cout.tie(0); } inline void randomizer3000 () { unsigned int seed; asm ("rdtsc" : "=A"(seed)); srand (seed); } void files (string problem) { if (fopen ((problem + ".in").c_str(),"r")) { freopen ((problem + ".in").c_str(),"r",stdin); freopen ((problem + ".out").c_str(),"w",stdout); } } void localInput(const char in[] = "s") { if (fopen (in, "r")) freopen (in, "r", stdin); else cerr << "Warning: Input file not found" << endl; } ll n, k, a, b; ll x, y; ll binpow (ll a, ll b) { int res = 1; while (b) { if (b & 1) res = (res * a) % Mod; b >>= 1; a = (a * a) % Mod; } return res; } ll dp[Sz]; ll calc (int n) { if (n < k) return binpow (a + b, n); if (~dp[n]) return dp[n]; dp[n] = 0; for (int j = 0; j < k; j++) dp[n] = (dp[n] + (calc (n - j - 1) * b) % Mod * binpow (a, j)) % Mod; return dp[n]; } int main() { # ifdef Local //localInput(); # endif Read_rap(); cin >> n >> k >> a >> b; /* memset (dp, -1, sizeof dp); x = binpow (a + b, k-1); y = (binpow (a, k-1) * b) % Mod; ll res1 = binpow (a + b, n) - calc(n); */ for (int i = 0; i < k; i++) dp[i] = binpow (a + b, i); ll sum = 0; for (int i = 0; i < k; i++) sum = (sum + (dp[k - 1 - i] * b) % Mod * binpow (a, i)) % Mod; dp[k] = sum; for (int i = k + 1; i <= n; i++) { sum = (sum * a + b * dp[i - 1]) % Mod; sum = (sum - ((dp[i - k - 1] * b) % Mod * binpow (a, k))) % Mod; if (sum < 0) sum += Mod; dp[i] = sum; } ll res = binpow (a + b, n) - dp[n]; if (res < 0) res += Mod; cout << res; return 0; } // Coded by Z..
19.433333
73
0.496998
7ee62dc712cbf004e7453a3de916c97755ceec2b
2,417
cpp
C++
src/zone/call-task.cpp
localh0rzd/napajs
b3f5e67dd20caef5d96ea8c3e3d4c542fcb9a431
[ "MIT" ]
9,088
2017-08-08T22:28:16.000Z
2019-05-05T14:57:12.000Z
src/zone/call-task.cpp
localh0rzd/napajs
b3f5e67dd20caef5d96ea8c3e3d4c542fcb9a431
[ "MIT" ]
172
2017-08-09T21:32:15.000Z
2019-05-03T21:21:05.000Z
src/zone/call-task.cpp
localh0rzd/napajs
b3f5e67dd20caef5d96ea8c3e3d4c542fcb9a431
[ "MIT" ]
370
2017-08-09T04:58:14.000Z
2019-04-13T18:59:29.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. // See: https://groups.google.com/forum/#!topic/nodejs/onA0S01INtw #ifdef BUILDING_NODE_EXTENSION #include <node.h> #endif #include "call-task.h" #include <module/core-modules/napa/call-context-wrap.h> #include <napa/log.h> using namespace napa::zone; using namespace napa::v8_helpers; napa::zone::CallTask::CallTask(std::shared_ptr<CallContext> context) : _context(std::move(context)) { } void CallTask::Execute() { NAPA_DEBUG("CallTask", "Begin executing function (%s.%s).", _context->GetModule().c_str(), _context->GetFunction().c_str()); auto isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); auto context = isolate->GetCurrentContext(); // Get the module based main function from global scope. auto executeFunction = context->Global()->Get(MakeExternalV8String(isolate, "__napa_zone_call__")); JS_ENSURE(isolate, executeFunction->IsFunction(), "__napa_zone_call__ function must exist in global scope"); // Create task wrap. auto contextWrap = napa::module::CallContextWrap::NewInstance(_context); v8::Local<v8::Value> argv[] = { contextWrap }; // Execute the function. v8::TryCatch tryCatch(isolate); auto res = v8::Local<v8::Function>::Cast(executeFunction)->Call( isolate->GetCurrentContext(), context->Global(), 1, argv); // Terminating an isolate may occur from a different thread, i.e. from timeout service. // If the function call already finished successfully when the isolate is terminated it may lead // to one the following: // 1. Terminate was called before tryCatch.HasTerminated(), the user gets an error code. // 2. Terminate was called after tryCatch.HasTerminated(), the user gets a success code. // // In both cases the isolate is being restored since this happens before each task executes. if (tryCatch.HasTerminated()) { if (_terminationReason == TerminationReason::TIMEOUT) { (void)_context->Reject(NAPA_RESULT_TIMEOUT, "Terminated due to timeout"); } else { (void)_context->Reject(NAPA_RESULT_INTERNAL_ERROR, "Terminated with unknown reason"); } return; } NAPA_ASSERT(!tryCatch.HasCaught(), "__napa_zone_call__ should catch all user exceptions and reject task."); }
38.365079
128
0.695904
7ee9248ee9f8bd45268bfd3793b758401e95d653
1,892
cpp
C++
SimuVar/Is_Number.cpp
TheArquitect/SimuVar
b6f4965af938706f6de1497494362c4b5c87d01e
[ "BSD-2-Clause" ]
null
null
null
SimuVar/Is_Number.cpp
TheArquitect/SimuVar
b6f4965af938706f6de1497494362c4b5c87d01e
[ "BSD-2-Clause" ]
null
null
null
SimuVar/Is_Number.cpp
TheArquitect/SimuVar
b6f4965af938706f6de1497494362c4b5c87d01e
[ "BSD-2-Clause" ]
null
null
null
/** File : Is_Number.cpp Author : Menashe Rosemberg Created : 2019.02.19 Version: 20190219.1 Check if a string is a number Copyright (c) 2019 TheArquitect (Menashe Rosemberg) rosemberg@ymail.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #include "Is_Number.h" bool is_number(const std::string& TxT) { bool OnePoint = true; for (auto Letter = TxT.cbegin() + (TxT[0] == '-'? 1 : 0); Letter != TxT.cend(); ++Letter) if (*Letter =='.' && OnePoint) OnePoint = false; else if (!isdigit(*Letter)) return false; return true; }
44
94
0.708774
7eeb2627333c504966e2194063705b0f39a8d900
847
cpp
C++
RealTournament/source/Pickup.cpp
willcassella/RealTournament
70ed3c0d5cbb67938ec8f86eec7b4d98a26e25f3
[ "MIT" ]
null
null
null
RealTournament/source/Pickup.cpp
willcassella/RealTournament
70ed3c0d5cbb67938ec8f86eec7b4d98a26e25f3
[ "MIT" ]
null
null
null
RealTournament/source/Pickup.cpp
willcassella/RealTournament
70ed3c0d5cbb67938ec8f86eec7b4d98a26e25f3
[ "MIT" ]
null
null
null
// Pickup.cpp #include <Engine/World.h> #include "../include/RealTournament/Pickup.h" ////////////////////// /// Reflection /// BUILD_REFLECTION(real_tournament::Pickup); namespace real_tournament { /////////////////// /// Methods /// void Pickup::on_collision(Entity& entity, const CollisionData& /*data*/) { auto* player = Cast<Player>(entity); if (player && !spawn_pad.is_null()) { auto* spawnPad = this->get_world().get_object(spawn_pad); spawnPad->spawn_timer = spawnPad->spawn_timer_start; spawn_pad = nullptr; this->on_pickup(*player); } } void Pickup::on_initialize() { this->Base::on_initialize(); this->get_world().bind_event("update", *this, &Pickup::on_update); } void Pickup::on_update(float dt) { if (!spawn_pad.is_null()) { this->rotate(Vec3::Up, degrees(dt * 25)); } } }
19.697674
73
0.62928
7eed663feab7bd786df2df95d386ddc4d2c7e025
820
cpp
C++
src/primitive.cpp
WilliamLewww/cuda_pbrt
d1136793025b7aa8cc2daf6da6ec19314684580b
[ "MIT" ]
null
null
null
src/primitive.cpp
WilliamLewww/cuda_pbrt
d1136793025b7aa8cc2daf6da6ec19314684580b
[ "MIT" ]
null
null
null
src/primitive.cpp
WilliamLewww/cuda_pbrt
d1136793025b7aa8cc2daf6da6ec19314684580b
[ "MIT" ]
null
null
null
#include "primitive.h" Bounds3 Primitive::worldBounds() {} bool Primitive::checkRayIntersectionPredicate(Ray* ray) {} bool Primitive::checkRayIntersection(Ray* ray, SurfaceInteraction* surfaceInteraction) {} GeometricPrimitive::GeometricPrimitive(Shape* shape) { this->shape = shape; } GeometricPrimitive::~GeometricPrimitive() { } Bounds3 GeometricPrimitive::worldBounds() { return shape->worldBounds(); } bool GeometricPrimitive::checkRayIntersectionPredicate(Ray* ray) { return shape->checkRayIntersectionPredicate(ray); } bool GeometricPrimitive::checkRayIntersection(Ray* ray, SurfaceInteraction* surfaceInteraction) { float tHit; if (!shape->checkRayIntersection(ray, &tHit, surfaceInteraction)) { return false; } ray->tMax = tHit; surfaceInteraction->primitive = this; return true; }
25.625
97
0.767073
7ef3b326accd80455c869d530b44fecb228876a2
1,124
hpp
C++
src/Message.hpp
relaxtakenotes/xenos
24d19b683e85df54f56cd9a5b2c6416b86e1325d
[ "MIT" ]
4
2021-12-14T13:32:10.000Z
2022-03-08T23:14:58.000Z
src/Message.hpp
relaxtakenotes/xenos
24d19b683e85df54f56cd9a5b2c6416b86e1325d
[ "MIT" ]
1
2021-10-20T14:09:51.000Z
2021-10-20T14:09:51.000Z
src/Message.hpp
relaxtakenotes/xenos
24d19b683e85df54f56cd9a5b2c6416b86e1325d
[ "MIT" ]
null
null
null
#pragma once #include "stdafx.h" #include "Log.h" class Message { enum MsgType { Error, Warning, Info, Question, }; public: static void ShowError( HWND parent, const std::wstring& msg, const std::wstring& title = L"Error" ) { Show( msg, title, Error, parent ); } static void ShowWarning( HWND parent, const std::wstring& msg, const std::wstring& title = L"Warning" ) { Show( msg, title, Warning, parent ); } static void ShowInfo( HWND parent, const std::wstring& msg, const std::wstring& title = L"Info" ) { Show( msg, title, Info, parent ); } static bool ShowQuestion( HWND parent, const std::wstring& msg, const std::wstring& title = L"Question" ) { return Show( msg, title, Question, parent ) == IDYES; } private: static int Show( const std::wstring& msg, const std::wstring& title, MsgType type, HWND parent = NULL ) { UINT uType = MB_ICONERROR; return MessageBoxW( parent, msg.c_str(), title.c_str(), uType ); } };
22.938776
109
0.573843