blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
6dcbac83ca1a1496cdb8465cd74d00fe8415d9eb
9488dc8080b4c2534aa421744c66bb8f755ff41d
/C++/Projects/Game/Game/Source/Application.cpp
2e5d07e9d9e1452f834c2686eb15569127198466
[]
no_license
Kn1MS/SoftForAll
2e201f18e7de5a34d6fbf2ba163703831e367ff8
221dc13e66690db6a92eab721c5db9a1c7c91743
refs/heads/master
2021-01-20T10:04:37.943122
2017-05-04T16:06:29
2017-05-04T16:06:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,277
cpp
#include "../Include/Application.hpp" #include "../Include/Utility.hpp" #include "../Include/State.hpp" #include "../Include/StateIdentifiers.hpp" #include "../Include/TitleState.hpp" #include "../Include/GameState.hpp" #include "../Include/MenuState.hpp" #include "../Include/PauseState.hpp" #include "../Include/SettingsState.hpp" #include "../Include/GameOverState.hpp" #include "../Include/DialogState.hpp" #include "../Include/LoadingState.hpp" const sf::Time Application::TimePerFrame = sf::seconds(1.f/60.f); Application::Application() : mWindow(sf::VideoMode(1280, 720), "Timle", sf::Style::Close) , mTextures() , mFonts() , mPlayer() , mStateStack(State::Context(mWindow, mTextures, mFonts, mPlayer)) , mStatisticsText() , mStatisticsUpdateTime() , mStatisticsNumFrames(0) { mWindow.setKeyRepeatEnabled(false); mWindow.setVerticalSyncEnabled(true); mFonts.load(Fonts::Main, "Media/Other/Noto Serif.ttf"); mTextures.load(Textures::TitleScreen, "Media/Textures/Menu/back.png"); mTextures.load(Textures::ButtonNormal, "Media/Textures/Menu/ButtonNormal.png"); mTextures.load(Textures::ButtonSelected, "Media/Textures/Menu/ButtonSelected.png"); mTextures.load(Textures::ButtonPressed, "Media/Textures/Menu/ButtonPressed.png"); mTextures.load(Textures::DialogBox, "Media/Textures/Interface/DialogBox.png"); mStatisticsText.setFont(mFonts.get(Fonts::Main)); mStatisticsText.setPosition(5.f, 5.f); mStatisticsText.setCharacterSize(10u); registerStates(); mStateStack.pushState(States::Title); } void Application::run() { sf::Clock clock; sf::Time timeSinceLastUpdate = sf::Time::Zero; while (mWindow.isOpen()) { sf::Time dt = clock.restart(); timeSinceLastUpdate += dt; while (timeSinceLastUpdate > TimePerFrame) { timeSinceLastUpdate -= TimePerFrame; processInput(); update(TimePerFrame); // Check inside this loop, because stack might be empty before update() call if (mStateStack.isEmpty()) mWindow.close(); } updateStatistics(dt); render(); } } void Application::processInput() { sf::Event event; while (mWindow.pollEvent(event)) { mStateStack.handleEvent(event); if (event.type == sf::Event::Closed) mWindow.close(); } } void Application::update(sf::Time dt) { mStateStack.update(dt); } void Application::render() { mWindow.clear(sf::Color(85, 170, 255)); mStateStack.draw(); mWindow.setView(mWindow.getDefaultView()); mWindow.draw(mStatisticsText); mWindow.display(); } void Application::updateStatistics(sf::Time dt) { mStatisticsUpdateTime += dt; mStatisticsNumFrames += 1; if (mStatisticsUpdateTime >= sf::seconds(1.0f)) { mStatisticsText.setString("FPS: " + toString(mStatisticsNumFrames)); mStatisticsUpdateTime -= sf::seconds(1.0f); mStatisticsNumFrames = 0; } } void Application::registerStates() { mStateStack.registerState<TitleState>(States::Title); mStateStack.registerState<MenuState>(States::Menu); mStateStack.registerState<GameState>(States::Game); mStateStack.registerState<LoadingState>(States::Loading); mStateStack.registerState<PauseState>(States::Pause); mStateStack.registerState<SettingsState>(States::Settings); mStateStack.registerState<GameOverState>(States::GameOver); mStateStack.registerState<DialogState>(States::Dialog); }
[ "vasar007@yandex.ru" ]
vasar007@yandex.ru
3eda9429386b1e9301aa70bd2b1f7c3b2a48f2ff
1c09e11802c249d7ea6557f1484d9edef45ec086
/swihlflashtool/libFlsTool/src/Fls2Parser.h
71668d6b0bc0b22edf4f5e2aefcf76a214322348
[]
no_license
pradeepcredenceid/tabasco_hardware_sierra
2f0c73989046ca36349685471625e98cb89a48fb
4e4c46cac62e902c2a75b127737dced1bbefd97d
refs/heads/master
2021-08-24T08:40:38.109212
2017-09-06T19:27:17
2017-09-06T19:27:17
110,303,638
2
1
null
null
null
null
UTF-8
C++
false
false
2,231
h
/* ------------------------------------------------------------------------- Copyright (C) 2013-2014 Intel Mobile Communications GmbH Sec Class: Intel Confidential (IC) ---------------------------------------------------------------------- Revision Information: $File name: /msw_tools/FlashTool/libFlsTool/src/Fls2Parser.h $ $CC-Version: .../dhkristx_140314_v0/1 $ $Date: 2014-04-22 9:13:29 UTC $ ---------------------------------------------------------------------- by CCCT (0.12h) ---------------------------------------------------------------------- */ #ifndef FLS2PARSER_H_ #define FLS2PARSER_H_ #include <stdint.h> #ifdef __cplusplus #include "Logger.h" #include "FlsMetaFile.h" #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> using namespace ipa::fls; /* Intel Platform Abstraction - Fls */ namespace ipa { namespace fls { #define PRG_MAGIC_NUMBER 0x693729F1 #define FLS2_LOAD_MAGIC 0x01FEDABE typedef enum { PRG_FILE_TYPE = 1, FLS_FILE_TYPE, EEP_FILE_TYPE, DFFS_FILE_TYPE, DISK_FILE_TYPE, NUM_FILE_TYPES // This should be the last } prg_file_type; string generateFileName(string filename, int UID, string type, string extra = ""); uint32_t fls2_get_size_of(const char* structure); /** * The Intel Fls2 Parser Class **/ class Fls2Parser { private: FlsMetaFile& m_ref; size_t m_size; vector<uint8_t> meta_data; Logger info; Logger debug; int verbosity; public: Fls2Parser(FlsMetaFile& ref, string file, int verbose); void load(const char* file); static void save(FlsMetaFile& ref, string file, int verbose); void set_verbose(int verbose); /** * Generate the SecPack * * @return Reference to the sec_pack buffer */ vector<uint8_t>& generate_sec_pack(); private: /** * Parsing the Fls2 file */ void fls2_parse(std::ifstream& fls); DownloadFile* get_download_file(size_t uid); }; } /* namespace fls */ } /* namespace ipa */ #endif /* __cplusplus */ #endif /* FLS3PARSER_H_ */
[ "gary.bisson@boundarydevices.com" ]
gary.bisson@boundarydevices.com
e5eb854713b4dfa560fda9afe38ad0abbd8a8dd4
dd2b4a363027b7d8225a885b562fe8aa117132b5
/lib/RegularMasking.cpp
2e30ebd51b936f57c245c84f5442828fa85f6d5a
[]
no_license
ylmzkaan/HemorrhageDetection
8293e994add50fc8649b632a22fe6aa8436f2dd3
e4f48f49e506af62d66743a6dd58c3dd0cee994a
refs/heads/master
2022-03-19T22:01:48.346663
2019-09-17T19:23:17
2019-09-17T19:23:17
198,085,594
0
0
null
null
null
null
UTF-8
C++
false
false
1,866
cpp
#include "../includes/Masking/MaskingMethods/RegularMasking.h" namespace sitk = itk::simple; /* This masking algorithm based on region growing with lower and upper threshold specified in parameters with regionGrowingLowerThreshold and regionGrowingUpperThreshold. If regionGrowingSeedType is "center" the seed is at x=230 y=340 z=number_of_slices/2. */ RegularMasking::RegularMasking(sitk::Image &image, const std::string &regionGrowingSeedType, const int &regionGrowingLowerThreshold, const int &regionGrowingUpperThreshold) : MaskingStrategy(image), regionGrowingSeedType(regionGrowingSeedType), regionGrowingLowerThreshold(regionGrowingLowerThreshold), regionGrowingUpperThreshold(regionGrowingUpperThreshold) {} sitk::Image RegularMasking::getBrainParenchyma() { std::cout << "Applying region growing to extract brain parenchyma." << std::endl; image = medianFilter.Execute(image); // Setup Region Growing filter unsigned int idxCenterSlice = (unsigned int) image.GetDepth() / 2; if (regionGrowingSeedType == "center") { regionGrower.SetSeed(std::vector<unsigned int> {230,340,idxCenterSlice}); } regionGrower.SetLower(regionGrowingLowerThreshold); regionGrower.SetUpper(regionGrowingUpperThreshold); regionGrower.SetReplaceValue(1); regionGrower.SetConnectivity(sitk::ConnectedThresholdImageFilter::ConnectivityType::FaceConnectivity); sitk::Image brainParenchymaMask = regionGrower.Execute(image); sitk::Image brainParenchyma = maskFilter.Execute(image, brainParenchymaMask, 0, 1); //brainParenchyma = thresholdFilter.Execute(image, 60, 80, 0); #ifndef NDEBUG sitk::Show(brainParenchyma, "Brain Parenchyma"); #endif std::cout << "Brain parenchyma is extracted." << std::endl; return brainParenchyma; }
[ "kaan-yilmaz@outlook.com.tr" ]
kaan-yilmaz@outlook.com.tr
24d65d3ff12d714cec01933845fc38df3cd03255
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE36_Absolute_Path_Traversal/s01/CWE36_Absolute_Path_Traversal__char_console_open_34.cpp
bd68c13dafc19ebedbd61a2929b023c3a00d712a
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
4,152
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE36_Absolute_Path_Traversal__char_console_open_34.cpp Label Definition File: CWE36_Absolute_Path_Traversal.label.xml Template File: sources-sink-34.tmpl.cpp */ /* * @description * CWE: 36 Absolute Path Traversal * BadSource: console Read input from the console * GoodSource: Full path and file name * Sinks: open * BadSink : Open the file named in data using open() * Flow Variant: 34 Data flow: use of a union containing two methods of accessing the same data (within the same function) * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #ifdef _WIN32 #define OPEN _open #define CLOSE _close #else #include <unistd.h> #define OPEN open #define CLOSE close #endif namespace CWE36_Absolute_Path_Traversal__char_console_open_34 { typedef union { char * unionFirst; char * unionSecond; } unionType; #ifndef OMITBAD void bad() { char * data; unionType myUnion; char dataBuffer[FILENAME_MAX] = ""; data = dataBuffer; { /* Read input from the console */ size_t dataLen = strlen(data); /* if there is room in data, read into it from the console */ if (FILENAME_MAX-dataLen > 1) { /* POTENTIAL FLAW: Read data from the console */ if (fgets(data+dataLen, (int)(FILENAME_MAX-dataLen), stdin) != NULL) { /* The next few lines remove the carriage return from the string that is * inserted by fgets() */ dataLen = strlen(data); if (dataLen > 0 && data[dataLen-1] == '\n') { data[dataLen-1] = '\0'; } } else { printLine("fgets() failed"); /* Restore NUL terminator if fgets fails */ data[dataLen] = '\0'; } } } myUnion.unionFirst = data; { char * data = myUnion.unionSecond; { int fileDesc; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE); if (fileDesc != -1) { CLOSE(fileDesc); } } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2B() { char * data; unionType myUnion; char dataBuffer[FILENAME_MAX] = ""; data = dataBuffer; #ifdef _WIN32 /* FIX: Use a fixed, full path and file name */ strcat(data, "c:\\temp\\file.txt"); #else /* FIX: Use a fixed, full path and file name */ strcat(data, "/tmp/file.txt"); #endif myUnion.unionFirst = data; { char * data = myUnion.unionSecond; { int fileDesc; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE); if (fileDesc != -1) { CLOSE(fileDesc); } } } } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE36_Absolute_Path_Traversal__char_console_open_34; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
5b66ecdaed88e9eea83125f0cebb79a6a05f919d
394a279fc8b82f3e7e980698023f84bdab30beb9
/src/qt/bitcoingui.cpp
6e34daa2b341680bbdf108d6cf18880dbeca2873
[ "MIT" ]
permissive
hocf/h1
d9dd886908776f6f6cdd7116a464ce9fbbc54d66
36ed792a0507f415e98cd2c9d3b1b6e3562571bf
refs/heads/master
2020-07-21T02:42:37.129061
2016-11-14T21:16:27
2016-11-14T21:16:27
73,740,920
0
1
null
null
null
null
UTF-8
C++
false
false
28,592
cpp
/* * Qt4 bitcoin GUI. * * W.J. van der Laan 2011-2012 * The HuobiCoin Developers 2011-2012 */ #include "bitcoingui.h" #include "transactiontablemodel.h" #include "optionsdialog.h" #include "aboutdialog.h" #include "clientmodel.h" #include "walletmodel.h" #include "walletframe.h" #include "optionsmodel.h" #include "transactiondescdialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "notificator.h" #include "guiutil.h" #include "rpcconsole.h" #include "ui_interface.h" #include "wallet.h" #include "init.h" #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #include <QApplication> #include <QMenuBar> #include <QMenu> #include <QIcon> #include <QVBoxLayout> #include <QToolBar> #include <QStatusBar> #include <QLabel> #include <QMessageBox> #include <QProgressBar> #include <QStackedWidget> #include <QDateTime> #include <QMovie> #include <QTimer> #include <QDragEnterEvent> #if QT_VERSION < 0x050000 #include <QUrl> #endif #include <QMimeData> #include <QStyle> #include <QListWidget> #include <iostream> const QString BitcoinGUI::DEFAULT_WALLET = "~Default"; BitcoinGUI::BitcoinGUI(bool fIsTestnet, QWidget *parent) : QMainWindow(parent), clientModel(0), encryptWalletAction(0), changePassphraseAction(0), aboutQtAction(0), trayIcon(0), notificator(0), rpcConsole(0), prevBlocks(0) { GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this); #ifndef Q_OS_MAC if (!fIsTestnet) { setWindowTitle(tr("HuobiCoin") + " - " + tr("Wallet")); QApplication::setWindowIcon(QIcon(":icons/bitcoin")); setWindowIcon(QIcon(":icons/bitcoin")); } else { setWindowTitle(tr("HuobiCoin") + " - " + tr("Wallet") + " " + tr("[testnet]")); QApplication::setWindowIcon(QIcon(":icons/bitcoin_testnet")); setWindowIcon(QIcon(":icons/bitcoin_testnet")); } #else setUnifiedTitleAndToolBarOnMac(true); QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); if (!fIsTestnet) MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin")); else MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); #endif // Create wallet frame and make it the central widget walletFrame = new WalletFrame(this); setCentralWidget(walletFrame); // Accept D&D of URIs setAcceptDrops(true); // Create actions for the toolbar, menu bar and tray/dock icon // Needs walletFrame to be initialized createActions(fIsTestnet); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create system tray icon and notification createTrayIcon(fIsTestnet); // Create status bar statusBar(); // Status bar notification icons QFrame *frameBlocks = new QFrame(); frameBlocks->setContentsMargins(0,0,0,0); frameBlocks->setMinimumWidth(56); frameBlocks->setMaximumWidth(56); QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks); frameBlocksLayout->setContentsMargins(3,0,3,0); frameBlocksLayout->setSpacing(3); labelEncryptionIcon = new QLabel(); labelConnectionsIcon = new QLabel(); labelBlocksIcon = new QLabel(); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelEncryptionIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelConnectionsIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(false); progressBar = new QProgressBar(); progressBar->setAlignment(Qt::AlignCenter); progressBar->setVisible(false); // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) // See https://qt-project.org/doc/qt-4.8/gallery.html QString curStyle = QApplication::style()->metaObject()->className(); if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }"); } statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(frameBlocks); syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this); rpcConsole = new RPCConsole(this); connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show())); // Install event filter to be able to catch status tip events (QEvent::StatusTip) this->installEventFilter(this); } BitcoinGUI::~BitcoinGUI() { GUIUtil::saveWindowGeometry("nWindow", this); if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu) trayIcon->hide(); #ifdef Q_OS_MAC delete appMenuBar; MacDockIconHandler::instance()->setMainWindow(NULL); #endif } void BitcoinGUI::createActions(bool fIsTestnet) { QActionGroup *tabGroup = new QActionGroup(this); overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this); overviewAction->setStatusTip(tr("Show general overview of wallet")); overviewAction->setToolTip(overviewAction->statusTip()); overviewAction->setCheckable(true); overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1)); tabGroup->addAction(overviewAction); sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this); sendCoinsAction->setStatusTip(tr("Send coins to a HuobiCoin address")); sendCoinsAction->setToolTip(sendCoinsAction->statusTip()); sendCoinsAction->setCheckable(true); sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2)); tabGroup->addAction(sendCoinsAction); receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this); receiveCoinsAction->setStatusTip(tr("Show the list of addresses for receiving payments")); receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip()); receiveCoinsAction->setCheckable(true); receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3)); tabGroup->addAction(receiveCoinsAction); historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this); historyAction->setStatusTip(tr("Browse transaction history")); historyAction->setToolTip(historyAction->statusTip()); historyAction->setCheckable(true); historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4)); tabGroup->addAction(historyAction); addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Addresses"), this); addressBookAction->setStatusTip(tr("Edit the list of stored addresses and labels")); addressBookAction->setToolTip(addressBookAction->statusTip()); addressBookAction->setCheckable(true); addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5)); tabGroup->addAction(addressBookAction); connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage())); connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage())); connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage())); quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this); quitAction->setStatusTip(tr("Quit application")); quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q)); quitAction->setMenuRole(QAction::QuitRole); if (!fIsTestnet) aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About HuobiCoin"), this); else aboutAction = new QAction(QIcon(":/icons/bitcoin_testnet"), tr("&About HuobiCoin"), this); aboutAction->setStatusTip(tr("Show information about HuobiCoin")); aboutAction->setMenuRole(QAction::AboutRole); aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this); aboutQtAction->setStatusTip(tr("Show information about Qt")); aboutQtAction->setMenuRole(QAction::AboutQtRole); optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this); optionsAction->setStatusTip(tr("Modify configuration options for HuobiCoin")); optionsAction->setMenuRole(QAction::PreferencesRole); if (!fIsTestnet) toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this); else toggleHideAction = new QAction(QIcon(":/icons/bitcoin_testnet"), tr("&Show / Hide"), this); toggleHideAction->setStatusTip(tr("Show or hide the main Window")); encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this); encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet")); encryptWalletAction->setCheckable(true); backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this); backupWalletAction->setStatusTip(tr("Backup wallet to another location")); changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this); changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption")); signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this); signMessageAction->setStatusTip(tr("Sign messages with your HuobiCoin addresses to prove you own them")); verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this); verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified HuobiCoin addresses")); openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this); openRPCConsoleAction->setStatusTip(tr("Open debugging and diagnostic console")); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked())); connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked())); connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden())); connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool))); connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet())); connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab())); } void BitcoinGUI::createMenuBar() { #ifdef Q_OS_MAC // Create a decoupled menu bar on Mac which stays even if the window is closed appMenuBar = new QMenuBar(); #else // Get the main window's menu bar on other platforms appMenuBar = menuBar(); #endif // Configure the menus QMenu *file = appMenuBar->addMenu(tr("&File")); file->addAction(backupWalletAction); file->addAction(signMessageAction); file->addAction(verifyMessageAction); file->addSeparator(); file->addAction(quitAction); QMenu *settings = appMenuBar->addMenu(tr("&Settings")); settings->addAction(encryptWalletAction); settings->addAction(changePassphraseAction); settings->addSeparator(); settings->addAction(optionsAction); QMenu *help = appMenuBar->addMenu(tr("&Help")); help->addAction(openRPCConsoleAction); help->addSeparator(); help->addAction(aboutAction); help->addAction(aboutQtAction); } void BitcoinGUI::createToolBars() { QToolBar *toolbar = addToolBar(tr("Tabs toolbar")); toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); toolbar->addAction(overviewAction); toolbar->addAction(sendCoinsAction); toolbar->addAction(receiveCoinsAction); toolbar->addAction(historyAction); toolbar->addAction(addressBookAction); } void BitcoinGUI::setClientModel(ClientModel *clientModel) { this->clientModel = clientModel; if(clientModel) { // Create system tray menu (or setup the dock menu) that late to prevent users from calling actions, // while the client has not yet fully loaded createTrayIconMenu(); // Keep up to date with client setNumConnections(clientModel->getNumConnections()); connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers()); connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int))); // Receive and report messages from network/worker thread connect(clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int))); rpcConsole->setClientModel(clientModel); walletFrame->setClientModel(clientModel); } } bool BitcoinGUI::addWallet(const QString& name, WalletModel *walletModel) { return walletFrame->addWallet(name, walletModel); } bool BitcoinGUI::setCurrentWallet(const QString& name) { return walletFrame->setCurrentWallet(name); } void BitcoinGUI::removeAllWallets() { walletFrame->removeAllWallets(); } void BitcoinGUI::createTrayIcon(bool fIsTestnet) { #ifndef Q_OS_MAC trayIcon = new QSystemTrayIcon(this); if (!fIsTestnet) { trayIcon->setToolTip(tr("HuobiCoin client")); trayIcon->setIcon(QIcon(":/icons/toolbar")); } else { trayIcon->setToolTip(tr("HuobiCoin client") + " " + tr("[testnet]")); trayIcon->setIcon(QIcon(":/icons/toolbar_testnet")); } trayIcon->show(); #endif notificator = new Notificator(QApplication::applicationName(), trayIcon); } void BitcoinGUI::createTrayIconMenu() { QMenu *trayIconMenu; #ifndef Q_OS_MAC // return if trayIcon is unset (only on non-Mac OSes) if (!trayIcon) return; trayIconMenu = new QMenu(this); trayIcon->setContextMenu(trayIconMenu); connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason))); #else // Note: On Mac, the dock icon is used to provide the tray's functionality. MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance(); dockIconHandler->setMainWindow((QMainWindow *)this); trayIconMenu = dockIconHandler->dockMenu(); #endif // Configuration of the tray icon (or dock icon) icon menu trayIconMenu->addAction(toggleHideAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(sendCoinsAction); trayIconMenu->addAction(receiveCoinsAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(signMessageAction); trayIconMenu->addAction(verifyMessageAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(optionsAction); trayIconMenu->addAction(openRPCConsoleAction); #ifndef Q_OS_MAC // This is built-in on Mac trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); #endif } #ifndef Q_OS_MAC void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason) { if(reason == QSystemTrayIcon::Trigger) { // Click on system tray icon triggers show/hide of the main window toggleHideAction->trigger(); } } #endif void BitcoinGUI::optionsClicked() { if(!clientModel || !clientModel->getOptionsModel()) return; OptionsDialog dlg; dlg.setModel(clientModel->getOptionsModel()); dlg.exec(); } void BitcoinGUI::aboutClicked() { AboutDialog dlg; dlg.setModel(clientModel); dlg.exec(); } void BitcoinGUI::gotoOverviewPage() { if (walletFrame) walletFrame->gotoOverviewPage(); } void BitcoinGUI::gotoHistoryPage() { if (walletFrame) walletFrame->gotoHistoryPage(); } void BitcoinGUI::gotoAddressBookPage() { if (walletFrame) walletFrame->gotoAddressBookPage(); } void BitcoinGUI::gotoReceiveCoinsPage() { if (walletFrame) walletFrame->gotoReceiveCoinsPage(); } void BitcoinGUI::gotoSendCoinsPage(QString addr) { if (walletFrame) walletFrame->gotoSendCoinsPage(addr); } void BitcoinGUI::gotoSignMessageTab(QString addr) { if (walletFrame) walletFrame->gotoSignMessageTab(addr); } void BitcoinGUI::gotoVerifyMessageTab(QString addr) { if (walletFrame) walletFrame->gotoVerifyMessageTab(addr); } void BitcoinGUI::setNumConnections(int count) { QString icon; switch(count) { case 0: icon = ":/icons/connect_0"; break; case 1: case 2: case 3: icon = ":/icons/connect_1"; break; case 4: case 5: case 6: icon = ":/icons/connect_2"; break; case 7: case 8: case 9: icon = ":/icons/connect_3"; break; default: icon = ":/icons/connect_4"; break; } labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelConnectionsIcon->setToolTip(tr("%n active connection(s) to HuobiCoin network", "", count)); } void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks) { // Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text) statusBar()->clearMessage(); // Acquire current block source enum BlockSource blockSource = clientModel->getBlockSource(); switch (blockSource) { case BLOCK_SOURCE_NETWORK: progressBarLabel->setText(tr("Synchronizing with network...")); break; case BLOCK_SOURCE_DISK: progressBarLabel->setText(tr("Importing blocks from disk...")); break; case BLOCK_SOURCE_REINDEX: progressBarLabel->setText(tr("Reindexing blocks on disk...")); break; case BLOCK_SOURCE_NONE: // Case: not Importing, not Reindexing and no network connection progressBarLabel->setText(tr("No block source available...")); break; } QString tooltip; QDateTime lastBlockDate = clientModel->getLastBlockDate(); QDateTime currentDate = QDateTime::currentDateTime(); int secs = lastBlockDate.secsTo(currentDate); if(count < nTotalBlocks) { tooltip = tr("Processed %1 of %2 (estimated) blocks of transaction history.").arg(count).arg(nTotalBlocks); } else { tooltip = tr("Processed %1 blocks of transaction history.").arg(count); } // Set icon state: spinning if catching up, tick otherwise if(secs < 90*60 && count >= nTotalBlocks) { tooltip = tr("Up to date") + QString(".<br>") + tooltip; labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); walletFrame->showOutOfSyncWarning(false); progressBarLabel->setVisible(false); progressBar->setVisible(false); } else { // Represent time from last generated block in human readable text QString timeBehindText; if(secs < 48*60*60) { timeBehindText = tr("%n hour(s)","",secs/(60*60)); } else if(secs < 14*24*60*60) { timeBehindText = tr("%n day(s)","",secs/(24*60*60)); } else { timeBehindText = tr("%n week(s)","",secs/(7*24*60*60)); } progressBarLabel->setVisible(true); progressBar->setFormat(tr("%1 behind").arg(timeBehindText)); progressBar->setMaximum(1000000000); progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5); progressBar->setVisible(true); tooltip = tr("Catching up...") + QString("<br>") + tooltip; labelBlocksIcon->setMovie(syncIconMovie); if(count != prevBlocks) syncIconMovie->jumpToNextFrame(); prevBlocks = count; walletFrame->showOutOfSyncWarning(true); tooltip += QString("<br>"); tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText); tooltip += QString("<br>"); tooltip += tr("Transactions after this will not yet be visible."); } // Don't word-wrap this (fixed-width) tooltip tooltip = QString("<nobr>") + tooltip + QString("</nobr>"); labelBlocksIcon->setToolTip(tooltip); progressBarLabel->setToolTip(tooltip); progressBar->setToolTip(tooltip); } void BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret) { QString strTitle = tr("HuobiCoin"); // default title // Default to information icon int nMBoxIcon = QMessageBox::Information; int nNotifyIcon = Notificator::Information; // Override title based on style QString msgType; switch (style) { case CClientUIInterface::MSG_ERROR: msgType = tr("Error"); break; case CClientUIInterface::MSG_WARNING: msgType = tr("Warning"); break; case CClientUIInterface::MSG_INFORMATION: msgType = tr("Information"); break; default: msgType = title; // Use supplied title } if (!msgType.isEmpty()) strTitle += " - " + msgType; // Check for error/warning icon if (style & CClientUIInterface::ICON_ERROR) { nMBoxIcon = QMessageBox::Critical; nNotifyIcon = Notificator::Critical; } else if (style & CClientUIInterface::ICON_WARNING) { nMBoxIcon = QMessageBox::Warning; nNotifyIcon = Notificator::Warning; } // Display message if (style & CClientUIInterface::MODAL) { // Check for buttons, use OK as default, if none was supplied QMessageBox::StandardButton buttons; if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK))) buttons = QMessageBox::Ok; QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons); int r = mBox.exec(); if (ret != NULL) *ret = r == QMessageBox::Ok; } else notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message); } void BitcoinGUI::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); #ifndef Q_OS_MAC // Ignored on Mac if(e->type() == QEvent::WindowStateChange) { if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray()) { QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e); if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized()) { QTimer::singleShot(0, this, SLOT(hide())); e->ignore(); } } } #endif } void BitcoinGUI::closeEvent(QCloseEvent *event) { if(clientModel) { #ifndef Q_OS_MAC // Ignored on Mac if(!clientModel->getOptionsModel()->getMinimizeToTray() && !clientModel->getOptionsModel()->getMinimizeOnClose()) { QApplication::quit(); } #endif } QMainWindow::closeEvent(event); } void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee) { QString strMessage = tr("This transaction is over the size limit. You can still send it for a fee of %1, " "which goes to the nodes that process your transaction and helps to support the network. " "Do you want to pay the fee?").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired)); QMessageBox::StandardButton retval = QMessageBox::question( this, tr("Confirm transaction fee"), strMessage, QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes); *payFee = (retval == QMessageBox::Yes); } void BitcoinGUI::incomingTransaction(const QString& date, int unit, qint64 amount, const QString& type, const QString& address) { // On new transaction, make an info balloon message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"), tr("Date: %1\n" "Amount: %2\n" "Type: %3\n" "Address: %4\n") .arg(date) .arg(BitcoinUnits::formatWithUnit(unit, amount, true)) .arg(type) .arg(address), CClientUIInterface::MSG_INFORMATION); } void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event) { // Accept only URIs if(event->mimeData()->hasUrls()) event->acceptProposedAction(); } void BitcoinGUI::dropEvent(QDropEvent *event) { if(event->mimeData()->hasUrls()) { int nValidUrisFound = 0; QList<QUrl> uris = event->mimeData()->urls(); foreach(const QUrl &uri, uris) { if (walletFrame->handleURI(uri.toString())) nValidUrisFound++; } // if valid URIs were found if (nValidUrisFound) walletFrame->gotoSendCoinsPage(); else message(tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid HuobiCoin address or malformed URI parameters."), CClientUIInterface::ICON_WARNING); } event->acceptProposedAction(); } bool BitcoinGUI::eventFilter(QObject *object, QEvent *event) { // Catch status tip events if (event->type() == QEvent::StatusTip) { // Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff if (progressBarLabel->isVisible() || progressBar->isVisible()) return true; } return QMainWindow::eventFilter(object, event); } void BitcoinGUI::handleURI(QString strURI) { // URI has to be valid if (!walletFrame->handleURI(strURI)) message(tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid HuobiCoin address or malformed URI parameters."), CClientUIInterface::ICON_WARNING); } void BitcoinGUI::setEncryptionStatus(int status) { switch(status) { case WalletModel::Unencrypted: labelEncryptionIcon->hide(); encryptWalletAction->setChecked(false); changePassphraseAction->setEnabled(false); encryptWalletAction->setEnabled(true); break; case WalletModel::Unlocked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; case WalletModel::Locked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; } } void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden) { // activateWindow() (sometimes) helps with keyboard focus on Windows if (isHidden()) { show(); activateWindow(); } else if (isMinimized()) { showNormal(); activateWindow(); } else if (GUIUtil::isObscured(this)) { raise(); activateWindow(); } else if(fToggleHidden) hide(); } void BitcoinGUI::toggleHidden() { showNormalIfMinimized(true); } void BitcoinGUI::detectShutdown() { if (ShutdownRequested()) QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); }
[ "empowrcoin@gmail.com" ]
empowrcoin@gmail.com
0a8a158833a74fc9f61ea335c95fe64b889fbf9d
594fc4eadeff6b0fabe9c2923b8b996d2b13dea1
/nudg++/trunk/Src/Examples2D/MaxwellNonCon2D/BuildPNonCon2D.cpp
4df880bcd3e2bf749dd4a4030fb5414bb0027b2d
[ "MIT", "LGPL-3.0-only", "LGPL-2.1-or-later" ]
permissive
AlbaraaKhayat/nodal-dg
506345d6a2e12c289c2965c1160118c3ea448ba3
28e43f41f0d55ff22ec543695d772a5f0ddae52d
refs/heads/master
2022-12-23T17:40:30.554978
2020-10-01T06:24:17
2020-10-01T06:24:17
268,416,765
0
0
MIT
2020-06-01T03:32:24
2020-06-01T03:32:24
null
UTF-8
C++
false
false
8,029
cpp
// BuildPNonCon2D.cpp // function pinfo = BuildPNonCon2D(Norder, pK, pVX, pVY, pEToV, pBCType) // 2007/08/04 //--------------------------------------------------------- #include "NDGLib_headers.h" //#include "NDG2D.h" #include "MaxwellNonCon2D.h" //######################################################### // TODO: migrate back to class NDG2D //######################################################### //--------------------------------------------------------- void MaxwellNonCon2D::BuildPNonCon2D ( int Norder, // [in] single integer int pK, // [in] DVec& pVX, // [in] DVec& pVY, // [in] IMat& pEToV, // [in] IMat& pBCType, // [in] PInfoV& pinfo // [out] ) //--------------------------------------------------------- { // load Norder as a list of {N} values IVec NList(1); NList(1) = Norder; BuildPNonCon2D(NList,pK,pVX,pVY,pEToV,pBCType,pinfo); } //--------------------------------------------------------- void MaxwellNonCon2D::BuildPNonCon2D ( IVec& Norder, // [in] integer array int pK, // [in] DVec& pVX, // [in] DVec& pVY, // [in] IMat& pEToV, // [in] IMat& pBCType, // [in] PInfoV& pinfo // [out] ) //--------------------------------------------------------- { // function pinfo = BuildPNonCon2D(Norder, pK, pVX, pVY, pEToV, pBCType) // // Purpose: construct info necessary for DGTD on P-nonconforming meshes // Globals2D; // Find maximum requested polynomial order this->Nmax = Norder.max_val(); // store original boundary conditions saveBCType = pBCType; // allow for one PInfo object for each order N pinfo.resize(Nmax+1, NULL); // Mesh details Nfaces = 3; NODETOL = 1e-12; VX = pVX; VY = pVY; DVec x1,y1,foo,rids1,rids2,sids3, gz,gw, rM,rP,gzr; IVec tids,ids,ids1,ids2,ids3,idsM,idsP; IVec KR,ksN, va,vb,vc, fN1,fN2,fmask; IMat kmap(pK,2), EToV_N, idsPM; DMat interpM,interpP,mmM; DMat_Diag Dgw; int N1=0,N2=0,k=0,offset=0,f1=0,f2=0,k1=0,k2=0; int k1orig=0,k2orig=0,pi1Nfp=0; // Perform a mini StartUp2D for the elements of each order int sk = 1; for (N=1; N<=Nmax; ++N) { // load N'th order polynomial nodes Np = (N+1)*(N+2)/2; Nfp = N+1; Nodes2D(N, x1,y1); xytors(x1,y1, r,s); // Find list of N'th order nodes on each face of the reference element tids = find(abs(s+1.0), '<', NODETOL); rids1=r(tids); sort(rids1, foo, ids, eAscend); ids1=tids(ids); tids = find(abs(r+s ), '<', NODETOL); rids2=r(tids); sort(rids2, foo, ids, eDescend); ids2=tids(ids); tids = find(abs(r+1.0), '<', NODETOL); sids3=s(tids); sort(sids3, foo, ids, eDescend); ids3=tids(ids); // Fmask = [ids1,ids2,ids3]; Fmask.resize(Nfp,3); // set shape (M,N) before concat() Fmask = concat(ids1,ids2,ids3); // load vector into shaped matrix // Build reference element matrices V = Vandermonde2D(N,r,s); invV = inv(V); MassMatrix = trans(invV)*invV; ::Dmatrices2D(N,r,s,V, Dr,Ds); Lift2D(); // store information for N'th order elements pinfo[N] = new PInfo(Nmax); PInfo& pinfo_N = *(pinfo[N]); pinfo_N.Np=Np; pinfo_N.Nfp=Nfp; pinfo_N.Fmask=Fmask; pinfo_N.r=r; pinfo_N.s=s; pinfo_N.Dr=Dr; pinfo_N.Ds=Ds; pinfo_N.LIFT=LIFT; pinfo_N.V=V; // Find elements of polynomial order N ksN = find(Norder, '=', N); K = ksN.length(); pinfo_N.K = K; pinfo_N.ks = ksN; if (K>0) { // Use the subset of elements of order N EToV_N = pEToV(ksN,All); BCType = saveBCType(ksN,All); KR=Range(1,K); kmap(ksN,1) = KR.data(); kmap(ksN,2) = N; // Build coordinates of all the nodes va = EToV_N(All,1); vb = EToV_N(All,2); vc = EToV_N(All,3); x = 0.5 * (-(r+s)*VX(va) + (1.0+r)*VX(vb) + (1.0+s)*VX(vc)); y = 0.5 * (-(r+s)*VY(va) + (1.0+r)*VY(vb) + (1.0+s)*VY(vc)); // Calculate geometric factors ::GeometricFactors2D(x,y,Dr,Ds, rx,sx,ry,sy,J); Normals2D(); Fscale = sJ.dd(J(Fmask,All)); // Calculate element connections on this mesh tiConnect2D(EToV_N, EToE,EToF); BuildMaps2D(); BuildBCMaps2D(); pinfo_N.mapW = mapW; //--------------------------------------------------- // Compute triangulation of N'th order nodes on mesh // // triN = delaunay(r, s); alltri = []; // for (k=1; k<=K; ++k) { alltri = [alltri; triN+(k-1)*Np]; } // pinfo_N.tri = alltri; //--------------------------------------------------- IMat triN, alltri; Triangulation2D(N, triN); for (k=1; k<=K; ++k) { // append copies of reference triangulation, // with ids shifted by (k-1)*Np alltri.append_rows( triN + (k-1)*Np ); } pinfo_N.tri = alltri; //--------------------------------------------------- // Store geometric information in pinfo struct pinfo_N.rx = rx; pinfo_N.sx = sx; pinfo_N.ry = ry; pinfo_N.sy = sy; pinfo_N.nx = nx; pinfo_N.ny = ny; pinfo_N.sJ = sJ; pinfo_N.J = J; pinfo_N.x = x; pinfo_N.y = y; pinfo_N.Fscale = Fscale; // (current) total number of DG nodes max_pinf_id = sk+K*Np-1; // Store location of the N'th order nodes in a global vector // pinfo_N.ids = reshape(sk:sk+K*Np-1, Np, K); pinfo_N.ids.load(Np,K, Range(sk,max_pinf_id)); sk += K*Np; } } // For each possible order for (N1=1; N1<=Nmax; ++N1) { // generate face L2projection matrices (from order N2 to order N1 face space) for (N2=1; N2<=Nmax; ++N2) { // Set up sufficient Gauss quadrature to exactly perform surface integrals JacobiGQ(0, 0, std::max(N1,N2), gz, gw); const PInfo &piN1 = *(pinfo[N1]), &piN2 = *(pinfo[N2]); fN1=piN1.Fmask(All,1); fN2=piN2.Fmask(All,1); // All edges have same distribution (note special Fmask) rM = piN1.r(fN1); rP = piN2.r(fN2); // gzr = gz(end:-1:1); gzr = gz(Range(gz.size(),1)); Dgw.diag(gw); // Build N2 to N1 projection matrices for '+' trace data interpM = Vandermonde1D(N1, gz )/Vandermonde1D(N1, rM); interpP = Vandermonde1D(N2, gzr)/Vandermonde1D(N2, rP); // Face mass matrix used in projection mmM = trans(interpM) * Dgw * interpM; piN1.interpP[N2] = mmM | ( trans(interpM) * Dgw * interpP); } } // Generate neighbor information for all faces tiConnect2D(pEToV, EToE, EToF); // For each possible polynomial order for (N1=1; N1<=Nmax; ++N1) { const PInfo &piN1 = *(pinfo[N1]); // Create a set of indexing arrays, one for each possible neighbor order for (N2=1; N2<=Nmax; ++N2) { (piN1.fmapM[N2]).resize(0); // used as vector of ids (piN1.vmapP[N2]).resize(0,0); // used as (Nfp,K) matrix } // Loop through all elements of order N1 for (k1=1; k1<=piN1.K; ++k1) { // Find element in original mesh k1orig = piN1.ks(k1); // Check all it's faces for (f1=1; f1<=Nfaces; ++f1) { // Find neighboring element (i.e. it's order and location in N2 mesh) k2orig = EToE(k1orig,f1); f2 = EToF(k1orig,f1); k2 = kmap(k2orig,1); N2 = kmap(k2orig,2); pi1Nfp = piN1.Nfp; // Compute location of face nodes of '-' trace offset = (k1-1)*pi1Nfp*Nfaces + (f1-1)*pi1Nfp; idsM = Range(offset+1, offset+pi1Nfp); // Find location of volume nodes on '+' trace of (k1orig,f1) fmask = pinfo[N2]->Fmask(All,f2); idsPM = pinfo[N2]->ids(fmask, k2); // extract as IMat idsP = idsPM; // convert to Ivec // Store node locations in cell arrays // piN1.fmapM[N2] = [pinfo(N1).fmapM{N2}, idsM]; // piN1.vmapP[N2] = [pinfo(N1).vmapP{N2}, idsP]; piN1.fmapM[N2].append(idsM); // used as vector of ids piN1.vmapP[N2].append_col(idsP); // used as (Nfp,K) matrix } } } umMSG(1, "BuildPNonCon2D() complete.\n"); }
[ "timwar@Tims-MacBook-Pro-2.local" ]
timwar@Tims-MacBook-Pro-2.local
a73081e889de423abc5bc4a5dbb1532f46458323
b3805d47d5386a052c1abfb8adad8a246e9776a9
/ch5/example/C++ features.cpp
afd9869a2e48a2692f585b733095a04d802a7c00
[]
no_license
xzshen071/zishu
31388470577159038794e444093e7ac34c74250b
1f797c6d3a8645cd05aa54b6c5a062c17c7374da
refs/heads/master
2021-06-22T22:50:19.669848
2019-09-08T09:14:16
2019-09-08T09:14:16
154,518,744
8
0
null
null
null
null
GB18030
C++
false
false
762
cpp
//C++特定的头文件 #include<iostream>//提供输入输出流 #include<algorithm>//提供常用的算法,如min //C++中可以使用流简化输入输出操作。标准输入输出流在头文件iostream中定义,存在于名称空间std中(可有多个名称空间)。如果使用using namespace std,可直接使用。 using namespace std; const int maxn=100+10; //数组大小可以使用const声明的常数 int A[maxn]; int main(){ long long a,b; while(cin >> a >> b){ cout<<min(a,b)<<"\n"; } //若注释掉using namespace std,上面报错,下面这段程序与上面效果相同。 /* while(std::cin >> a >> b){ std::cout<<std::min(a,b)<<"\n"; } */ return 0; } //C++相对与C多了bool类型
[ "noreply@github.com" ]
noreply@github.com
990f82d3ef56fa11150e174a40245d8cf5a31dff
de3ab58815ad42d6f065a045da994cc7142cbbb3
/adjlist3.cpp
2631f8018c043fea4ddfcd0d48a0bfb6a7f6609b
[]
no_license
xil12008/powerlawP2P
1553277af9ec3be2d3055e30dd2012dcc565051e
f48142a7bf925c62eef01176b2a36730e40d2114
refs/heads/master
2021-01-10T01:19:48.482782
2016-01-25T05:19:08
2016-01-25T05:19:08
47,791,377
0
0
null
null
null
null
UTF-8
C++
false
false
17,192
cpp
// A C Program to demonstrate adjacency list representation of graphs #include <stdio.h> #include <stdlib.h> #include <time.h> #include <vector> #include <math.h> /* pow */ #include <map> using namespace std; #define TRIAL_FIND_DEGREE 20 //#define ADD_THEN_REMOVE // A structure to represent an adjacency list node struct AdjListNode { int dest; struct AdjListNode* next; }; // A structure to represent an adjacency list struct AdjList { struct AdjListNode *head; // pointer to head node of list }; // A structure to represent a graph. A graph is an array of adjacency lists. // Size of array will be V (number of vertices in graph) struct Graph { int V; int cap; int* degree; struct AdjList* array; }; // A utility function to create a new adjacency list node struct AdjListNode* newAdjListNode(int dest) { struct AdjListNode* newNode = (struct AdjListNode*) malloc(sizeof(struct AdjListNode)); newNode->dest = dest; newNode->next = NULL; return newNode; } // A utility function that creates a graph of V vertices struct Graph* createGraph(int V) { struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph)); graph->V = V; graph->cap = 0; // Create an array of adjacency lists. Size of array will be V graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList)); graph->degree = (int*) malloc(V * sizeof(int)); // Initialize each adjacency list as empty by making head as NULL int i; for (i = 0; i < V; ++i) graph->array[i].head = NULL; graph->degree[i] = 0; return graph; } // Adds an edge to an undirected graph void addEdge(struct Graph* graph, int src, int dest) { if (src >= graph->cap || dest >= graph->cap) { fprintf(stderr, "Sorry, wrong node id src=%d dest=%d.\n", src, dest); return; } //if (graph->degree[src] == 0 || graph->degree[dest] == 0) //{ // fprintf(stderr, "Sorry, node does NOT exist. node id src=%d dest=%d.\n", src, dest); // return; //} // Add an edge from src to dest. A new node is added to the adjacency // list of src. The node is added at the begining struct AdjListNode* newNode = newAdjListNode(dest); newNode->next = graph->array[src].head; graph->array[src].head = newNode; ++graph->degree[src]; // Since graph is undirected, add an edge from dest to src also newNode = newAdjListNode(src); newNode->next = graph->array[dest].head; graph->array[dest].head = newNode; ++graph->degree[dest]; } // A utility function to print the adjacenncy list representation of graph void printGraph(struct Graph* graph) { int v; printf(" cap=%d", graph->cap); for (v = 0; v < graph->cap; ++v) { struct AdjListNode* pCrawl = graph->array[v].head; printf("\n Adjacency list of vertex %d (degree %d)\n head ", v, graph->degree[v]); while (pCrawl) { printf("-> %d", pCrawl->dest); pCrawl = pCrawl->next; } printf("\n"); } } //print one node void printNode(struct Graph* graph, int v) { struct AdjListNode* pCrawl = graph->array[v].head; printf("\n Adjacency list of vertex %d (degree %d)\n head ", v, graph->degree[v]); while (pCrawl) { printf("-> %d", pCrawl->dest); pCrawl = pCrawl->next; } } // return the id of newly joining node int newNode(Graph* graph) { if ( graph->cap >= graph->V) { fprintf(stderr, "Sorry, insufficient memory space when adding node.\n"); return -1; } return graph->cap++; //the assigned node id increases by 1 } // One edge from a --> b ?? // only in single direction graph, you could replace a and b bool isConnected(Graph* graph, int a, int b) { if (a == -1 || b == -1) return false; if (a == b) return true; // NOTE: treat as connected even if same node struct AdjListNode* pCrawl = graph->array[a].head; while (pCrawl) { if (pCrawl->dest == b) { //printf("conflict:%d->%d\n", a, b); return true; } pCrawl = pCrawl->next; } return false; } // find a random node ID with desired degree // @TODO complete randomness int findNode(Graph* graph, int deg, int forbid = -1) { int rnum; for (int i = 0; i < TRIAL_FIND_DEGREE; ++i) { rnum = rand() % graph->cap; // not connected with forbid, in case return the same node twice. if (graph->degree[rnum] == deg && ! isConnected(graph, rnum, forbid) ) { return rnum; } } //if it did not find the node with desired deg, then vector<int> vec; for (int i = 0; i < graph->cap; ++i) { if (graph->degree[i] == deg) { vec.push_back(i); } } if (vec.size() > 0) { int tmp_count = 30 * vec.size(); while (--tmp_count > 0) { int ret = rand() % vec.size(); if( ! isConnected(graph, vec[ret], forbid) && ! graph->degree[vec[ret]] == 0) return vec[ret]; } } printf("WARNING: No node has degree %d (current graph size = %d)\n", deg, graph->cap); return -1; } //randomly generate degree by distribution ai int joinDegree(int k, int m, vector<double>* ai) { double rsum = (double) rand() / (RAND_MAX); //printf("rsum=%f\t", rsum); for (int i = 0; i < m-k; ++i) { rsum -= (double) (*ai)[i] / k; //printf("rsum - %f =%f\t", (double) (*ai)[i] / k, rsum); if (rsum < 0) { //printf("return %d\n", i + k); return i + k; } } fprintf(stderr, "ERROR generate degree!\n"); return m - 1; } // add k neighbors when a new node join the network void joinNode(Graph* graph, int k, int m, vector<double>* ai) { int id = newNode(graph); // node to be added int mydegree; int i = k; int neighbor; int rn; while (i > 0) { mydegree = joinDegree(k, m, ai); // passing parameter id to findNode() because // findNode() should not return a neighbor of node id. neighbor = findNode(graph, mydegree, id); if (neighbor != -1) { addEdge(graph, id, neighbor); } else { //@TODO in this case, some improvements could be made by //choosing a node closer to the desired degree "mydegree". while (1) // prevent connecting to a non-exist node { rn = rand() % graph->cap; if (graph->degree[rn] >= k && graph->degree[rn] < m && ! isConnected(graph, rn, id) ) { break; } } addEdge(graph, id, rn); } --i; } } vector<double>* generate_ai(int k, int m, double gamma) { vector<double>* v = new vector<double>(); //calculate f[i], a[i] double sum = 0; for(int i = k; i < m; ++i) { sum += 1.0 * (m - i) / pow(i, gamma); } double ai = 1; double hold = 0; for(int i =k; i < m; ++i) { double fi = 1.0 * (m - 2 * k) / pow( i, gamma) / sum; hold += fi; ai = ai - fi; v->push_back(ai); printf("f%d=%f a%d=%f\n", i , fi, i, ai); } printf("f%d=%f\n", m, 1 - hold); printf("["); for( int i = k; i < m; ++i) { printf(" %f, ", 1.0 * (m - 2 * k) / pow( i, gamma) / sum ); } printf("%f]\n", 1 - hold); //check if correct printf("%f == %f\n", 1.0 - hold, ai); return v; } void initGraph(Graph* graph, int k) { // create the initial graph for (int i = 0; i < 2*k + 1; ++i) newNode(graph); for (int i = 0; i < 2*k + 1; ++i) { for(int j = i; j < 2*k + 1; ++j) { if (i != j) { addEdge(graph, i, j); } } } } void statics_neighbor_degree(Graph* graph, int k, int m, int b) { map<int, int> nd; //neighbor's degree for( int i = k; i <= m; ++i) { nd[i] = 0; } int count = 0; for ( int i = 0; i < graph->cap; ++i) { int d = graph->degree[i]; if ( d == b ) { struct AdjListNode* pCrawl = graph->array[i].head; while( pCrawl ) { //printf("i=%d(%d) neighbor=%d nd=%d\n", i, b, pCrawl->dest, graph->degree[pCrawl->dest]); ++nd[graph->degree[pCrawl->dest]]; pCrawl = pCrawl->next; } count++; } } printf("nd[%d] = [", b); double checksum = 0; for (int i = k; i < m ; ++i) { printf("%f,\t", (double)(1.0 * nd[i] / count)); checksum += (double)(1.0 * nd[i] / count); } printf("%f]\n", (double)(1.0 * nd[m] / count)); //printf("checksum=%f\n", checksum); } void statics(Graph *graph, int k, int m) { map<int, int> v; for( int i = k; i <= m; ++i) { v[i] = 0; } int count = 0; double checksum = 0; for ( int i = 0; i < graph->cap; ++i) { int d = graph->degree[i]; if (d >= k && d <= m ) { v[ graph->degree[i] ] += 1; count++; } else if ( d != 0) { printf("Statics exception: node %d has degree %d.\n", i, d); } } printf("total %d nodes\n", count); for( int i = k; i <= m; ++i) { //printf("d%i fraction=%f\n", i, (double) 1.0 * v[i] / count ); checksum += (double) 1.0 * v[i] / count; } printf("["); for( int i = k; i < m; ++i) { printf(" %f, ", (double) 1.0 * v[i] / count ); } printf(" %f ", (double) 1.0 * v[m] / count ); printf("]\n"); printf("checksum = %f\n", checksum); } int findK(Graph* graph, int k, int id) { int tmp = id; int a; int count = 10; while (graph->degree[tmp] > k && --count > -1) { tmp = (graph->array[tmp].head)->dest; if (tmp == id) { return -1; } } if (count > -1) return tmp; else return -2; } // NOTE: it's just one direction void removeEdge(Graph* graph, int src, int dst) { struct AdjListNode* pCrawl = graph->array[src].head; struct AdjListNode* prev = graph->array[src].head; while (pCrawl) { //printf("%d dst%d\n", pCrawl->dest, dst); if (pCrawl->dest == dst) { if (pCrawl == graph->array[src].head) { graph->array[src].head = pCrawl->next; } else prev->next = pCrawl->next; graph->degree[src]--; return; } prev = pCrawl; pCrawl = pCrawl->next; } fprintf(stderr, "ERROR: remove edge failed src=%d dst=%d\n", src, dst); } void removeAllEdges(Graph* graph, int v) { struct AdjListNode* pCrawl = graph->array[v].head; while (pCrawl) { removeEdge(graph, pCrawl->dest, v); pCrawl = pCrawl->next; } graph->array[v].head = NULL; graph->degree[v] = 0; } //randomly generate degree by distribution ai int deleteDegree(int k, int m, int b) { double rsum = (double) rand() / (RAND_MAX); for (int i = 0; i < b-k; ++i) { rsum -= (double) 1.0 / (b - k); if (rsum < 0) { return i + k; } } fprintf(stderr, "ERROR generate degree while removing node!\n"); return - 1; } void deleteBroadcast(Graph* graph, int id, int k, int m, int b) { if (b <= k) { fprintf(stderr, "ERROR: deleteBroadcast\n"); return; } int degree = deleteDegree(k, m, b); //printf("degree=%d b=%d\n", degree, b); int node = findNode(graph, degree, id); if (node != -1) { addEdge(graph, node, id); //printf("addEdge (%d, %d)\n", node, id); } else { int rn = -1; while (1) // prevent connecting to a non-exist node { rn = rand() % graph->cap; if (graph->degree[rn] >= k && graph->degree[rn] < b) { break; } } addEdge(graph, rn, id); //printf("addEdge (random=%d, %d)\n", rn, id); } } int randomNeighbor(Graph* graph, int id) { struct AdjListNode* pCrawl = graph->array[id].head; int njump = rand() % graph->degree[id]; for (int i = 0;i < njump - 1; ++i) { pCrawl = pCrawl->next; } return pCrawl->dest; } void deleteNode(int id, Graph* graph, int k, int m, int ithnode, vector<double>* ai) { int b = graph->degree[id]; //printf("R= %d b=%d\n", id, b); struct AdjListNode* pCrawl = graph->array[id].head; int mydegree, helper; for (int i = 0; i < k; ++i) { mydegree = joinDegree(k, m, ai) + 1; // +1 because q(i+1) = a(i) helper = findNode(graph, mydegree, pCrawl->dest); if (helper == -1) { //@TODO in this case, some improvements could be made by //choosing a node closer to the desired degree "mydegree". // @TODO and should not let pCrawl->dest be removed if its' degree = k printf("No node has degree %d. So skip one shuffle.%dth node\n" , mydegree, ithnode); } else{ int neighbor = randomNeighbor(graph, helper); while (isConnected(graph, neighbor, pCrawl->dest) || neighbor == pCrawl->dest) { /* printf("Stuck finding neighbor here\n"); if (isConnected(graph, neighbor, pCrawl->dest)) printf("%d connected with %d", neighbor, pCrawl->dest); else if (neighbor == pCrawl->dest) printf("neighbor %d is pCrawl->dest %d", neighbor, pCrawl->dest); printNode(graph, helper); */ neighbor = randomNeighbor(graph, helper); } //printf("%d--X--%d--+--%d\n", helper, neighbor, pCrawl->dest); removeEdge(graph, helper, neighbor); removeEdge(graph, neighbor, helper); addEdge(graph, neighbor, pCrawl->dest); } pCrawl = pCrawl->next; } int degree_accum = k; while (pCrawl) { //printf("push degree=%d\t", degree_accum); helper = findNode(graph, degree_accum, id); if (helper == -1) { // @TODO should not let pCrawl->dest be removed if its' degree = k printf("No node has degree %d. So skip one push.%dth node\n" , mydegree, ithnode); } else{ addEdge(graph, helper, pCrawl->dest); //printf("%d push %d( => degree%d)\n", pCrawl->dest, helper, graph->degree[helper]); } pCrawl = pCrawl->next; ++degree_accum; } removeAllEdges(graph, id); } void testJoinDegree(int k, int m, vector<double>* ai){ int tmp = 0; int hold = 0; while(tmp++<100) { int degree = joinDegree(k, m, ai); if (degree == k) hold++; printf("%d\n", degree); } printf("hold==%d", hold); } // Driver program to test above functions int main() { srand(time(NULL)); int V = 40000; int k = 2; int m = 10; double gamma = 2.5; struct Graph* graph = createGraph(V); initGraph(graph, k); //printGraph(graph); #ifdef ADD_THEN_REMOVE printf("============start adding=============\n"); vector<double> *ai = generate_ai(k, m, gamma); // nodes join for (int i = 2*k + 1; i< V; ++i) { joinNode(graph, k, m, ai); } //printGraph(graph); statics(graph, k, m); /*for ( int b = k; b <= m; ++b) { statics_neighbor_degree(graph, k, m, b); } //return 0; */ printf("=========now, remove==============\n"); //node quiting for (int i = 0; i < 10000; ++i) { int rid; while (1){ rid = rand() % graph->cap; if (graph->degree[rid] >= 2*k) break; } deleteNode(rid, graph, k, m, i, ai); //removeAllEdges(graph, rid); } //printGraph(graph); statics(graph, k, m); int inputn = 0; fflush(stdout); while (inputn != -1) { printf("Type Node ID:"); fflush(stdout); scanf("%d", &inputn); printNode(graph, inputn); printf("\n"); fflush(stdout); } #else int segment = 100; vector<double> *ai = generate_ai(k, m, gamma); // nodes join for (int i = 2*k + 1; i < V/4; ++i) { joinNode(graph, k, m, ai); } statics(graph, k, m); printf("Pattern 1\n"); for (int i = V/4; i < V; ++i) { if ( rand()%2 ) joinNode(graph, k, m, ai); else { int rid; while (1){ rid = rand() % graph->cap; if (graph->degree[rid] >= 2*k) break; } deleteNode(rid, graph, k, m, i, ai); //removeAllEdges(graph, rid); } } statics(graph, k, m); #endif return 0; }
[ "luxy622@gmail.com" ]
luxy622@gmail.com
08ea0504f0b72ae28c8f23175855f017ddf6bcb8
04b1803adb6653ecb7cb827c4f4aa616afacf629
/chrome/browser/chromeos/extensions/file_system_provider/file_system_provider_api.h
e5aab5e2b1945df33bef34ca69d7b48dd9c96ca8
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
5,043
h
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_EXTENSIONS_FILE_SYSTEM_PROVIDER_FILE_SYSTEM_PROVIDER_API_H_ #define CHROME_BROWSER_CHROMEOS_EXTENSIONS_FILE_SYSTEM_PROVIDER_FILE_SYSTEM_PROVIDER_API_H_ #include "chrome/browser/chromeos/extensions/file_system_provider/provider_function.h" #include "chrome/browser/extensions/chrome_extension_function.h" namespace extensions { class FileSystemProviderMountFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystemProvider.mount", FILESYSTEMPROVIDER_MOUNT) protected: ~FileSystemProviderMountFunction() override {} ResponseAction Run() override; }; class FileSystemProviderUnmountFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystemProvider.unmount", FILESYSTEMPROVIDER_UNMOUNT) protected: ~FileSystemProviderUnmountFunction() override {} ResponseAction Run() override; }; class FileSystemProviderGetAllFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystemProvider.getAll", FILESYSTEMPROVIDER_GETALL) protected: ~FileSystemProviderGetAllFunction() override {} ResponseAction Run() override; }; class FileSystemProviderGetFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystemProvider.get", FILESYSTEMPROVIDER_GET) protected: ~FileSystemProviderGetFunction() override {} ResponseAction Run() override; }; class FileSystemProviderNotifyFunction : public ChromeAsyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystemProvider.notify", FILESYSTEMPROVIDER_NOTIFY) protected: ~FileSystemProviderNotifyFunction() override {} bool RunAsync() override; private: // Called when notifying is completed. void OnNotifyCompleted(base::File::Error result); }; class FileSystemProviderInternalUnmountRequestedSuccessFunction : public FileSystemProviderInternalFunction { public: DECLARE_EXTENSION_FUNCTION( "fileSystemProviderInternal.unmountRequestedSuccess", FILESYSTEMPROVIDERINTERNAL_UNMOUNTREQUESTEDSUCCESS) protected: ~FileSystemProviderInternalUnmountRequestedSuccessFunction() override {} ResponseAction Run() override; }; class FileSystemProviderInternalGetMetadataRequestedSuccessFunction : public FileSystemProviderInternalFunction { public: DECLARE_EXTENSION_FUNCTION( "fileSystemProviderInternal.getMetadataRequestedSuccess", FILESYSTEMPROVIDERINTERNAL_GETMETADATAREQUESTEDSUCCESS) protected: ~FileSystemProviderInternalGetMetadataRequestedSuccessFunction() override {} ResponseAction Run() override; }; class FileSystemProviderInternalGetActionsRequestedSuccessFunction : public FileSystemProviderInternalFunction { public: DECLARE_EXTENSION_FUNCTION( "fileSystemProviderInternal.getActionsRequestedSuccess", FILESYSTEMPROVIDERINTERNAL_GETACTIONSREQUESTEDSUCCESS) protected: ~FileSystemProviderInternalGetActionsRequestedSuccessFunction() override {} ResponseAction Run() override; }; class FileSystemProviderInternalReadDirectoryRequestedSuccessFunction : public FileSystemProviderInternalFunction { public: DECLARE_EXTENSION_FUNCTION( "fileSystemProviderInternal.readDirectoryRequestedSuccess", FILESYSTEMPROVIDERINTERNAL_READDIRECTORYREQUESTEDSUCCESS) protected: ~FileSystemProviderInternalReadDirectoryRequestedSuccessFunction() override {} ResponseAction Run() override; }; class FileSystemProviderInternalReadFileRequestedSuccessFunction : public FileSystemProviderInternalFunction { public: DECLARE_EXTENSION_FUNCTION( "fileSystemProviderInternal.readFileRequestedSuccess", FILESYSTEMPROVIDERINTERNAL_READFILEREQUESTEDSUCCESS) protected: ~FileSystemProviderInternalReadFileRequestedSuccessFunction() override {} ResponseAction Run() override; }; class FileSystemProviderInternalOperationRequestedSuccessFunction : public FileSystemProviderInternalFunction { public: DECLARE_EXTENSION_FUNCTION( "fileSystemProviderInternal.operationRequestedSuccess", FILESYSTEMPROVIDERINTERNAL_OPERATIONREQUESTEDSUCCESS) protected: ~FileSystemProviderInternalOperationRequestedSuccessFunction() override {} ResponseAction Run() override; }; class FileSystemProviderInternalOperationRequestedErrorFunction : public FileSystemProviderInternalFunction { public: DECLARE_EXTENSION_FUNCTION( "fileSystemProviderInternal.operationRequestedError", FILESYSTEMPROVIDERINTERNAL_OPERATIONREQUESTEDERROR) protected: ~FileSystemProviderInternalOperationRequestedErrorFunction() override {} ResponseAction Run() override; }; } // namespace extensions #endif // CHROME_BROWSER_CHROMEOS_EXTENSIONS_FILE_SYSTEM_PROVIDER_FILE_SYSTEM_PROVIDER_API_H_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
0897cf0b8d24827d6aae8c397ca322837f9f8280
e1eaebb04214484f8ea8ddc2a8e3993f058ee5cd
/cpp08/ex00/main.cpp
fa1c8421f5d6d0c1e212bb584e04b3e12659adf1
[]
no_license
bember-usr/cpp_module
728dee26093170287409a40b002b81dac9420b9d
68d2511eb7c69b8f78079bcfd13f5746de7a35d6
refs/heads/master
2023-06-09T08:36:34.776423
2021-06-26T12:34:42
2021-06-26T12:34:42
380,497,670
0
0
null
null
null
null
UTF-8
C++
false
false
1,023
cpp
#include "easyfind.hpp" int main(void) { std::vector<int> a; a.push_back(1); a.push_back(3); a.push_back(45); a.push_back(34); a.push_back(78); a.push_back(6); std::vector<int>::iterator var; std::cout << "\033[32mValid test: find '3'\033[0m" << std::endl; try { var = easyfind(a, 3); std::cout << "Detected element is " << *var << ", pos : " << var - a.begin() << std::endl; } catch(const std::exception& e) { std::cerr << e.what() << '\n'; } std::cout << "\033[32mValid test: find '78'\033[0m" << std::endl; try { var = easyfind(a, 78); std::cout << "Detected element is " << *var << ", pos : " << var - a.begin() << std::endl; } catch(const std::exception& e) { std::cerr << e.what() << '\n'; } std::cout << "\033[31mNot Valid test: find '-1'\033[0m" << std::endl; try { var = easyfind(a, -1); std::cout << "Detected element is" << *var << ", pos : " << var - a.begin() << std::endl; } catch(const std::exception& e) { std::cerr << e.what() << '\n'; } return (0); }
[ "diana.latyrova@gmail.com" ]
diana.latyrova@gmail.com
399bec12bf0db5415681abb8f85012c217dbcb08
2277375bd4a554d23da334dddd091a36138f5cae
/ThirdParty/Havok/Source/Geometry/Internal/Algorithms/RayCast/hkcdRayCastTriangle.inl
e117998ec08a54b3beba56b7fc1aed3192f29843
[]
no_license
kevinmore/Project-Nebula
9a0553ccf8bdc1b4bb5e2588fc94516d9e3532bc
f6d284d4879ae1ea1bd30c5775ef8733cfafa71d
refs/heads/master
2022-10-22T03:55:42.596618
2020-06-19T09:07:07
2020-06-19T09:07:07
25,372,691
6
5
null
null
null
null
UTF-8
C++
false
false
13,761
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #include <Common/Base/Math/Vector/hkVector4Util.h> // // Intersects a line segment with a triangle. Returns 1 if the segment intersects the triangle, // and 0 otherwise. inline hkBool32 HK_CALL hkcdSegmentTriangleIntersect( const hkcdRay& ray, hkVector4Parameter vA, hkVector4Parameter vB, hkVector4Parameter vC, hkSimdRealParameter tolerance, hkVector4& normalOut, hkSimdReal& fractionInOut) { hkVector4Comparison cmpPQ; hkVector4 vN; { hkVector4 vAB; vAB.setSub(vB, vA); hkVector4 vAC; vAC.setSub(vC, vA); hkVector4 vAP; vAP.setSub(ray.m_origin, vA); vN.setCross(vAB, vAC); const hkSimdReal distAP = vN.dot<3>(vAP); // dist_a const hkSimdReal projLen = vN.dot<3>(ray.getDirection()); // dist_a - dist_b const hkSimdReal distAQ = distAP + projLen; // dist_b const hkSimdReal distance = -(distAP / projLen); // distance // cmpPQ = (dist_a * dist_b >= 0.0f) && ( (dist_a != 0.0f) || (dist_b == 0.0f) ) cmpPQ.setOr(distAP.notEqualZero(), distAQ.equalZero()); cmpPQ.setAnd((distAP * distAQ).greaterEqualZero(), cmpPQ); // cmpPQ = (distance < fractionInOut) && ( (dist_a * dist_b < 0.0f) || ( (dist_a == 0.0f) && (dist_b != 0.0f) ) ) cmpPQ.setAndNot(distance.less(fractionInOut), cmpPQ); // Early exit if ( !cmpPQ.anyIsSet() ) { return false; } // Set proper sign for the normal fractionInOut = distance; normalOut.setFlipSign(vN, distAP); } hkVector4 vDots; { // Compute intersection point hkVector4 vI; vI.setAddMul(ray.m_origin, ray.getDirection(), fractionInOut); // Test whether the intersection point is inside the triangle hkVector4 vIA; vIA.setSub(vA, vI); hkVector4 vIB; vIB.setSub(vB, vI); hkVector4 vIC; vIC.setSub(vC, vI); hkVector4 nIAB; nIAB.setCross(vIA, vIB); hkVector4 nIBC; nIBC.setCross(vIB, vIC); hkVector4 nICA; nICA.setCross(vIC, vIA); hkVector4Util::dot3_1vs4(vN, nIAB, nIBC, nICA, vN, vDots); } // Decide whether we have an intersection or not { // Normalize normal const hkSimdReal squaredNormalLen = vDots.getComponent<3>(); normalOut.mul(squaredNormalLen.sqrtInverse()); hkVector4 edgeTol; edgeTol.setAll(-squaredNormalLen * tolerance); hkVector4Comparison cmp0; cmp0.setAnd(vDots.greaterEqual(edgeTol), cmpPQ); return cmp0.allAreSet<hkVector4ComparisonMask::MASK_XYZ>(); } } // // Helper function for segment bundle intersect. Returns (B - I) * (n x (A - I)) inline static void hkcdHelperEdgeDots( hkVector4Parameter vA, hkVector4Parameter vB, const hkFourTransposedPoints& vI, hkVector4Parameter vN, hkVector4& vDotsOut ) { hkFourTransposedPoints vAI, vBI; vAI.setSub(vI, vA); // (I - A) vAI.setCross(vN, vAI); // n x (I - A) vBI.setSub(vI, vB); // (I - B) vBI.dot3(vAI, vDotsOut); // (I - B) * (n x (I - A)) = (B - I) * (n x (A - I)) = n * ((A - I) x (B - I)) } // // Intersects a ray bundle with the triangle. inline hkVector4Comparison HK_CALL hkcdSegmentBundleTriangleIntersect( const hkcdRayBundle& rayBundle, hkVector4Parameter vA, hkVector4Parameter vB, hkVector4Parameter vC, hkSimdRealParameter tolerance, hkFourTransposedPoints& normalsOut, hkVector4& fractionsInOut ) { const hkFourTransposedPoints& vStart = rayBundle.m_start; hkFourTransposedPoints vDir; rayBundle.getDirection(vDir); hkVector4Comparison cmpPQ; hkVector4 vN, distAP; hkVector4 distance; { hkVector4 vAB; vAB.setSub(vB, vA); hkVector4 vAC; vAC.setSub(vC, vA); vN.setCross(vAB, vAC); hkFourTransposedPoints vAP; vAP.setSub(vStart, vA); vAP.dot3(vN, distAP); // dist_a hkVector4 projLen; vDir.dot3(vN, projLen); // dist_b - dist_a hkVector4 distAQ; distAQ.setAdd(distAP, projLen); // dist_b distance.setDiv(distAP, projLen); distance.setNeg<4>(distance); // distance // cmpPQ = (dist_a * dist_b >= 0.0f) && ( (dist_a != 0.0f) || (dist_b == 0.0f) ) cmpPQ.setOr(distAP.notEqualZero(), distAQ.equalZero()); distAQ.mul(distAP); cmpPQ.setAnd(distAQ.greaterEqualZero(), cmpPQ); // cmpPQ = (distance < fractionInOut) && ( (dist_a * dist_b < 0.0f) || ( (dist_a == 0.0f) && (dist_b != 0.0f) ) ) cmpPQ.setAndNot(distance.less(fractionsInOut), cmpPQ); cmpPQ.setAnd(cmpPQ, rayBundle.m_activeRays); // Early exit if ( !cmpPQ.anyIsSet() ) { return cmpPQ; } } // Get normal length and compute a tolerance const hkSimdReal normalLengthSquared = vN.lengthSquared<3>(); hkVector4 edgeTol; edgeTol.setAll(-normalLengthSquared * tolerance); // Decide whether we have a valid intersection { // Compute intersection point hkFourTransposedPoints vI; vI.setAddMulT(vStart, vDir, distance); // Test for point I inside edge AB { hkVector4 vDotsAB; hkcdHelperEdgeDots(vA, vB, vI, vN, vDotsAB); cmpPQ.setAnd(cmpPQ, vDotsAB.greaterEqual(edgeTol)); } // Test for point I inside edge BC { hkVector4 vDotsBC; hkcdHelperEdgeDots(vB, vC, vI, vN, vDotsBC); cmpPQ.setAnd(cmpPQ, vDotsBC.greaterEqual(edgeTol)); } // Test for point I inside edge CA { hkVector4 vDotsCA; hkcdHelperEdgeDots(vC, vA, vI, vN, vDotsCA); cmpPQ.setAnd(cmpPQ, vDotsCA.greaterEqual(edgeTol)); } } // Output fractions fractionsInOut.setSelect(cmpPQ, distance, fractionsInOut); // Output normals { vN.normalize<3>(); hkFourTransposedPoints allNormals; allNormals.setAll(vN); // Set proper signs allNormals.flipSigns(distAP); // Select only colliding normals in the output normalsOut.setSelect(cmpPQ, allNormals, normalsOut); } return cmpPQ; } // // Returns true and the fraction if the ray intersect the triangle between 0 and fractionInOut. #if defined(HK_PLATFORM_XBOX360) | defined(HK_PLATFORM_PS3) HK_FORCE_INLINE hkBool32 HK_CALL hkcdSegmentTriangleIntersect( const hkcdRay& ray, hkVector4Parameter a, hkVector4Parameter b, hkVector4Parameter c, hkVector4& nonUnitNormalOut, hkSimdReal& fractionInOut ) { { hkVector4 v01; v01.setSub(b, a); hkVector4 v12; v12.setSub(c, b); hkVector4 v20; v20.setSub(a, c); hkVector4 orig0; orig0.setSub( ray.m_origin, a ); hkVector4 orig1; orig1.setSub( ray.m_origin, b ); hkVector4 orig2; orig2.setSub( ray.m_origin, c ); hkVector4 end0; end0.setAddMul( orig0, ray.getDirection(), fractionInOut ); hkVector4 n; n.setCross( v01, v20 ); hkVector4 c0; c0.setCross( orig0, ray.getDirection() ); hkVector4 c1; c1.setCross( orig1, ray.getDirection() ); hkVector4 c2; c2.setCross( orig2, ray.getDirection() ); hkSimdReal d = n.dot<3>( orig0 ); hkSimdReal e = n.dot<3>( end0 ); hkSimdReal d0 = c0.dot<3>( v01 ); hkSimdReal d1 = c1.dot<3>( v12 ); hkSimdReal d2 = c2.dot<3>( v20 ); hkSimdReal fraction = d / (d-e); // optimistically do the fraction here hkIntVector d_equal_e; d_equal_e .setXor( (const hkIntVector&)d, (const hkIntVector&)e ); hkIntVector d0_equal_d1; d0_equal_d1.setXor( (const hkIntVector&)d0, (const hkIntVector&)d1 ); hkIntVector d1_equal_d2; d1_equal_d2.setXor( (const hkIntVector&)d1, (const hkIntVector&)d2 ); hkIntVector d_equal; d_equal.setOr( d0_equal_d1, d1_equal_d2); hkIntVector d_nequal_e; d_nequal_e.setXor( d_equal_e, (hkIntVector&)hkVector4::getConstant(HK_QUADREAL_MINUS1)); hkIntVector check; check.setOr( d_equal, d_nequal_e); if ( check.isNegativeAssumingAllValuesEqual() ) { return 0; } // now we are sure to have a hit fractionInOut = fraction * fractionInOut; nonUnitNormalOut = n; return 1; } } #else HK_FORCE_INLINE hkBool32 HK_CALL hkcdSegmentTriangleIntersect( const hkcdRay& ray, hkVector4Parameter vA, hkVector4Parameter vB, hkVector4Parameter vC, hkVector4& nonUnitNormalOut, hkSimdReal& fractionInOut ) { { hkVector4 vAB; vAB.setSub(vB, vA); // v01 hkVector4 vCA; vCA.setSub(vA, vC); // v20 hkVector4 vN; vN.setCross(vAB, vCA); hkVector4 vAP; vAP.setSub(ray.m_origin, vA); hkVector4 end0; end0.setAddMul(vAP, ray.getDirection(), fractionInOut); hkSimdReal d = vN.dot<3>( vAP ); hkSimdReal e = vN.dot<3>( end0 ); if ( (d*e).isSignBitClear() ) { return 0; } hkSimdReal fraction = d / (d-e); // calculate the fraction here so that the compiler can get rid of d and e hkVector4 vBP; vBP.setSub(ray.m_origin, vB); hkVector4 vCP; vCP.setSub(ray.m_origin, vC); hkVector4 vBC; vBC.setSub(vC, vB); // v12 hkVector4 c0; c0.setCross(vAP, ray.getDirection()); hkVector4 c1; c1.setCross(vBP, ray.getDirection()); hkVector4 c2; c2.setCross(vCP, ray.getDirection()); hkSimdReal d0 = c0.dot<3>(vAB); hkSimdReal d1 = c1.dot<3>(vBC); hkSimdReal d2 = c2.dot<3>(vCA); if ( (d0*d1).isSignBitSet() | (d1*d2).isSignBitSet() ) { return 0; } // now we are sure to have a hit fractionInOut = fraction * fractionInOut; nonUnitNormalOut = vN; return 1; } } #endif HK_FORCE_INLINE void hkcdSortVerticesDeterministically( hkVector4Parameter va, hkVector4Parameter vb, hkVector4Comparison* cmpOut ) { extern hkChar hkcdSortVerticesDeterministicallyTable[]; hkVector4Comparison equal = va.equal( vb ); hkVector4Comparison greater = va.greater( vb ); hkVector4Comparison::Mask me = equal.getMask(); hkVector4Comparison::Mask mg = greater.getMask(); cmpOut->set( hkVector4ComparisonMask::Mask(hkcdSortVerticesDeterministicallyTable[me<<4 | mg]) ); } HK_FORCE_INLINE hkBool32 HK_CALL hkcdSegmentTriangleIntersectImprovedAccuracy( const hkcdRay& ray, hkVector4Parameter vA, hkVector4Parameter vB, hkVector4Parameter vC, hkVector4& nonUnitNormalOut, hkSimdReal& fractionInOut) { { hkVector4 vAB; vAB.setSub(vB, vA); // v01 hkVector4 vCA; vCA.setSub(vA, vC); // v20 hkVector4 vN; vN.setCross(vAB, vCA); hkVector4 vAP; vAP.setSub(ray.m_origin, vA); hkVector4 end0; end0.setAddMul(vAP, ray.getDirection(), fractionInOut); hkSimdReal d = vN.dot<3>( vAP ); hkSimdReal e = vN.dot<3>( end0 ); if ( (d*e).isSignBitClear() ) { return 0; } hkSimdReal fraction = d / (d-e); // calculate the fraction here so that the compiler can get rid of d and e // sort edges //edge0; hkVector4Comparison e0c; hkcdSortVerticesDeterministically( vA, vB, &e0c ); hkVector4 e0A; e0A.setSelect( e0c, vA, vB ); hkVector4Comparison e1c; hkcdSortVerticesDeterministically( vB, vC, &e1c ); hkVector4 e1A; e1A.setSelect( e1c, vB, vC ); hkVector4Comparison e2c; hkcdSortVerticesDeterministically( vC, vA, &e2c ); hkVector4 e2A; e2A.setSelect( e2c, vC, vA ); hkVector4 vBC; vBC.setSub(vC, vB); // v12 hkVector4 v0P; v0P.setSub( ray.m_origin, e0A ); hkVector4 v1P; v1P.setSub( ray.m_origin, e1A ); hkVector4 v2P; v2P.setSub( ray.m_origin, e2A ); hkVector4 c0; c0.setCross( v0P, ray.getDirection() ); hkVector4 c1; c1.setCross( v1P, ray.getDirection() ); hkVector4 c2; c2.setCross( v2P, ray.getDirection() ); hkSimdReal d0 = c0.dot<3>(vAB); hkSimdReal d1 = c1.dot<3>(vBC); hkSimdReal d2 = c2.dot<3>(vCA); if ( (d0*d1).isSignBitSet() | (d1*d2).isSignBitSet() ) { return 0; } // now we are sure to have a hit fractionInOut = fraction * fractionInOut; nonUnitNormalOut = vN; return 1; } } // HK_FORCE_INLINE hkInt32 hkcdRayTriangleIntersect( const hkcdRay& ray, const hkVector4& a, const hkVector4& b, const hkVector4& c, hkSimdReal* HK_RESTRICT fractionOut, hkVector4* HK_RESTRICT normalOut, hkcdRayQueryFlags::Enum flags ) { hkVector4 org; org.setSub(ray.m_origin, a); hkVector4 ab; ab.setSub(b,a); hkVector4 ac; ac.setSub(c,a); hkVector4 n; n.setCross(ab,ac); hkSimdReal den = n.dot<3>(ray.getDirection()); if((den * den) < hkSimdReal_Eps) return 0; if((flags & hkcdRayQueryFlags::DISABLE_BACK_FACING_TRIANGLE_HITS) && den.isSignBitClear()) return 0; if((flags & hkcdRayQueryFlags::DISABLE_FRONT_FACING_TRIANGLE_HITS) && den.isSignBitSet()) return 0; hkSimdReal num = n.dot<3>(org); hkSimdReal fraction = - num / den; if((den * num).isSignBitSet() && fraction < ray.getFraction()) { hkVector4 impact; impact.setAddMul(org, ray.getDirection(), fraction); hkVector4 epsilon; epsilon.setAll(-2.e-4f); epsilon.mul(n.lengthSquared<3>()); // use faster length hkVector4 ab0; ab0.setSub(ab, impact); hkVector4 ac0; ac0.setSub(ac, impact); hkVector4 c0; c0.setCross(ab0, ac0); hkVector4 c1; c1.setCross(ab, impact); hkVector4 c2; c2.setCross(impact, ac); hkVector4 dots; hkVector4Util::dot3_3vs3(c0,n, c1,n, c2,n, dots); if(dots.greaterEqual(epsilon).allAreSet<hkVector4ComparisonMask::MASK_XYZ>()) { if(fractionOut) { *fractionOut = fraction; } if(normalOut) { normalOut->setFlipSign( n, den.signBitClear() ); } return hkcdRayCastResult::createOutsideHit(); } } return hkcdRayCastResult::createMiss(); } /* * Havok SDK - Base file, BUILD(#20130912) * * Confidential Information of Havok. (C) Copyright 1999-2013 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available from salesteam@havok.com. * */
[ "dingfengyu@gmail.com" ]
dingfengyu@gmail.com
4d35962742155b1329d46fe1370267179d954814
9b0b324ebc3f3ee27188eb65211fbf1f57c736d6
/2013/Decode Ways.cpp
5a3f76acdef98a3a4330d184813e3e7b5c99c07e
[]
no_license
zoyanhui/leetcode
4c830daff3d79b0029dcb2cb6eb801b7f9b57ab3
49ec4861cb7b685dd8174075e95126419895ead5
refs/heads/master
2021-01-22T07:10:43.230766
2020-09-19T04:18:10
2020-09-19T04:18:10
42,497,657
2
0
null
null
null
null
UTF-8
C++
false
false
1,131
cpp
class Solution { public: int numDecodings(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int len = s.length(); if(len < 1 || s[0] < '1' || s[0] > '9') return 0; vector<int> ret(len+1, 0); ret[0] = ret[1] = 1; for(int i=1; i < len; i++) { bool two = check(s, i-1, i), one = check(s, i, i); if(!two && !one) ret[i+1] = 0; if(two) ret[i+1] += ret[i-1]; if(one) { ret[i+1] += ret[i]; } } return ret[len]; } private: bool check(const string s, int begin, int end) { if(end - begin > 1 || begin > end) return false; string tstr(s,begin, end-begin+1); if(end == begin) { if(tstr < "1" || tstr >"9") return false; else return true; } else { if(tstr >= "10" && tstr <= "26") return true; else return false; } } };
[ "zhouyanhui@appchina.com" ]
zhouyanhui@appchina.com
ca4d53fc90491ff647e647ee3a7ee0bc04b7786e
459186ed42db477a7b7c7be15e67133cbae6000c
/src/platform/3ds/main.cpp
4346fa02130398ab72c62621f174de9c286c6987
[ "BSD-2-Clause-Views", "BSD-2-Clause" ]
permissive
JeanSairien/OpenLara
65e234e95d3f0f062d3d01e1f696d5bf1215f525
18386a1d353823c9f046fc09076a631a32e6f4ff
refs/heads/master
2020-06-07T12:38:39.637913
2019-05-30T02:04:08
2019-05-30T02:04:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,964
cpp
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include "game.h" // multi-threading void* osMutexInit() { Handle *mutex = new Handle(); svcCreateMutex(mutex, false); return mutex; } void osMutexFree(void *obj) { svcCloseHandle(*(Handle*)obj); delete (Handle*)obj; } void osMutexLock(void *obj) { svcWaitSynchronization(*(Handle*)obj, U64_MAX); } void osMutexUnlock(void *obj) { svcReleaseMutex(*(Handle*)obj); } // timing u64 osStartTime = 0; int osGetTimeMS() { return int(osGetTime() - osStartTime); } // input bool osJoyReady(int index) { return index == 0; } void osJoyVibrate(int index, float L, float R) { // } void inputInit() { hidInit(); } void inputUpdate() { const static u64 keys[jkMAX] = { 0, KEY_B, KEY_A, KEY_Y, KEY_X, KEY_L, KEY_R, KEY_SELECT, KEY_START, 0, 0, KEY_ZL, KEY_ZR, KEY_DLEFT, KEY_DRIGHT, KEY_DUP, KEY_DDOWN, }; hidScanInput(); u64 mask = hidKeysDown() | hidKeysHeld(); for (int i = 1; i < jkMAX; i++) { Input::setJoyDown(0, JoyKey(jkNone + i), (mask & keys[i]) != 0); } circlePosition circlePos; hidCircleRead(&circlePos); vec2 stickL = vec2(float(circlePos.dx), float(-circlePos.dy)) / 160.0f; if (fabsf(stickL.x) < 0.3f && fabsf(stickL.y) < 0.3f) stickL = vec2(0.0f); Input::setJoyPos(0, jkL, stickL); } void inputFree() { hidExit(); } // sound #define SND_FRAMES (4704/2) ndspWaveBuf sndWaveBuf[2]; Sound::Frame *sndBuffer; Thread sndThread; int sndBufIndex; bool sndReady; void sndFill(void *arg) { LOG("thread start\n"); memset(sndWaveBuf, 0, sizeof(sndWaveBuf)); sndWaveBuf[0].data_vaddr = sndBuffer + 0; sndWaveBuf[0].nsamples = SND_FRAMES; sndWaveBuf[1].data_vaddr = sndBuffer + SND_FRAMES; sndWaveBuf[1].nsamples = SND_FRAMES; Sound::fill(sndBuffer, SND_FRAMES * 2); sndBufIndex = 0; ndspChnWaveBufAdd(0, sndWaveBuf + 0); ndspChnWaveBufAdd(0, sndWaveBuf + 1); while (sndReady) { ndspWaveBuf &buf = sndWaveBuf[sndBufIndex]; if (buf.status == NDSP_WBUF_DONE) { Sound::fill((Sound::Frame*)buf.data_pcm16, buf.nsamples); DSP_FlushDataCache(buf.data_pcm16, buf.nsamples); ndspChnWaveBufAdd(0, &buf); sndBufIndex = !sndBufIndex; } svcSleepThread(1000000ULL); } } void sndInit() { sndBuffer = (Sound::Frame*)linearAlloc(SND_FRAMES * sizeof(Sound::Frame) * 2); ndspInit(); ndspSetOutputMode (NDSP_OUTPUT_STEREO); ndspChnSetFormat (0, NDSP_FORMAT_STEREO_PCM16); ndspChnSetInterp (0, NDSP_INTERP_LINEAR); ndspChnSetRate (0, 44100); float mix[12]; memset(mix, 0, sizeof(mix)); mix[0] = 1.0; mix[1] = 1.0; ndspChnSetMix(0, mix); sndReady = true; s32 priority = 0; svcGetThreadPriority(&priority, CUR_THREAD_HANDLE); sndThread = threadCreate(sndFill, NULL, 64 * 1024, priority - 1, -1, false); } void sndFree() { sndReady = false; threadJoin(sndThread, U64_MAX); threadFree(sndThread); ndspExit(); linearFree((uint32*)sndBuffer); } int main() { { bool isNew3DS; APT_CheckNew3DS(&isNew3DS); if (isNew3DS) { osSetSpeedupEnable(true); } } strcpy(cacheDir, "sdmc:/3ds/OpenLara/"); strcpy(saveDir, "sdmc:/3ds/OpenLara/"); strcpy(contentDir, "sdmc:/3ds/OpenLara/"); if(chdir(contentDir) != 0) { gfxExit(); return 0; } sndInit(); inputInit(); osStartTime = Core::getTime(); Game::init("PSXDATA/LEVEL1.PSX"); while (aptMainLoop() && !Core::isQuit) { inputUpdate(); if (Input::joy[0].down[jkStart]) Core::quit(); Game::update(); Game::render(); GAPI::present(); } inputFree(); sndFree(); Game::deinit(); return 0; }
[ "xproger@list.ru" ]
xproger@list.ru
b7a9966827680f08c7df3279645464482b15b26c
bd6153487eacbd00c7ff57319300c261f71a4840
/JuceLibraryCode/modules/juce_core/unit_tests/juce_UnitTest.h
772e094a7f2e41c3a8af3cd058cf185c49c7733d
[]
no_license
gbevin/linnstrument-control
cc6fe7a5eedcb36d2b7628ef72e6185d2fc7edcf
ab04ac190bfddfbfdb8fd732171db2e78e27314a
refs/heads/master
2020-05-29T14:41:23.675122
2016-06-12T13:04:33
2016-06-12T13:04:33
60,967,218
27
1
null
null
null
null
UTF-8
C++
false
false
11,208
h
/* ============================================================================== This file is part of the juce_core module of the JUCE library. Copyright (c) 2015 - ROLI Ltd. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ------------------------------------------------------------------------------ NOTE! This permissive ISC license applies ONLY to files within the juce_core module! All other JUCE modules are covered by a dual GPL/commercial license, so if you are using any other modules, be sure to check that you also comply with their license. For more details, visit www.juce.com ============================================================================== */ #ifndef JUCE_UNITTEST_H_INCLUDED #define JUCE_UNITTEST_H_INCLUDED class UnitTestRunner; //============================================================================== /** This is a base class for classes that perform a unit test. To write a test using this class, your code should look something like this: @code class MyTest : public UnitTest { public: MyTest() : UnitTest ("Foobar testing") {} void runTest() override { beginTest ("Part 1"); expect (myFoobar.doesSomething()); expect (myFoobar.doesSomethingElse()); beginTest ("Part 2"); expect (myOtherFoobar.doesSomething()); expect (myOtherFoobar.doesSomethingElse()); ...etc.. } }; // Creating a static instance will automatically add the instance to the array // returned by UnitTest::getAllTests(), so the test will be included when you call // UnitTestRunner::runAllTests() static MyTest test; @endcode To run a test, use the UnitTestRunner class. @see UnitTestRunner */ class JUCE_API UnitTest { public: //============================================================================== /** Creates a test with the given name. */ explicit UnitTest (const String& name); /** Destructor. */ virtual ~UnitTest(); /** Returns the name of the test. */ const String& getName() const noexcept { return name; } /** Runs the test, using the specified UnitTestRunner. You shouldn't need to call this method directly - use UnitTestRunner::runTests() instead. */ void performTest (UnitTestRunner* runner); /** Returns the set of all UnitTest objects that currently exist. */ static Array<UnitTest*>& getAllTests(); //============================================================================== /** You can optionally implement this method to set up your test. This method will be called before runTest(). */ virtual void initialise(); /** You can optionally implement this method to clear up after your test has been run. This method will be called after runTest() has returned. */ virtual void shutdown(); /** Implement this method in your subclass to actually run your tests. The content of your implementation should call beginTest() and expect() to perform the tests. */ virtual void runTest() = 0; //============================================================================== /** Tells the system that a new subsection of tests is beginning. This should be called from your runTest() method, and may be called as many times as you like, to demarcate different sets of tests. */ void beginTest (const String& testName); //============================================================================== /** Checks that the result of a test is true, and logs this result. In your runTest() method, you should call this method for each condition that you want to check, e.g. @code void runTest() { beginTest ("basic tests"); expect (x + y == 2); expect (getThing() == someThing); ...etc... } @endcode If testResult is true, a pass is logged; if it's false, a failure is logged. If the failure message is specified, it will be written to the log if the test fails. */ void expect (bool testResult, const String& failureMessage = String::empty); /** Compares two values, and if they don't match, prints out a message containing the expected and actual result values. */ template <class ValueType> void expectEquals (ValueType actual, ValueType expected, String failureMessage = String::empty) { const bool result = (actual == expected); if (! result) { if (failureMessage.isNotEmpty()) failureMessage << " -- "; failureMessage << "Expected value: " << expected << ", Actual value: " << actual; } expect (result, failureMessage); } //============================================================================== /** Writes a message to the test log. This can only be called from within your runTest() method. */ void logMessage (const String& message); /** Returns a shared RNG that all unit tests should use. If a test needs random numbers, it's important that when an error is found, the exact circumstances can be re-created in order to re-test the problem, by repeating the test with the same random seed value. To make this possible, the UnitTestRunner class creates a master seed value for the run, writes this number to the log, and then this method returns a Random object based on that seed. All tests should only use this method to create any Random objects that they need. Note that this method will return an identical object each time it's called for a given run, so if you need several different Random objects, the best way to do that is to call Random::combineSeed() on the result to permute it with a constant value. */ Random getRandom() const; private: //============================================================================== const String name; UnitTestRunner* runner; JUCE_DECLARE_NON_COPYABLE (UnitTest) }; //============================================================================== /** Runs a set of unit tests. You can instantiate one of these objects and use it to invoke tests on a set of UnitTest objects. By using a subclass of UnitTestRunner, you can intercept logging messages and perform custom behaviour when each test completes. @see UnitTest */ class JUCE_API UnitTestRunner { public: //============================================================================== /** */ UnitTestRunner(); /** Destructor. */ virtual ~UnitTestRunner(); /** Runs a set of tests. The tests are performed in order, and the results are logged. To run all the registered UnitTest objects that exist, use runAllTests(). If you want to run the tests with a predetermined seed, you can pass that into the randomSeed argument, or pass 0 to have a randomly-generated seed chosen. */ void runTests (const Array<UnitTest*>& tests, int64 randomSeed = 0); /** Runs all the UnitTest objects that currently exist. This calls runTests() for all the objects listed in UnitTest::getAllTests(). If you want to run the tests with a predetermined seed, you can pass that into the randomSeed argument, or pass 0 to have a randomly-generated seed chosen. */ void runAllTests (int64 randomSeed = 0); /** Sets a flag to indicate whether an assertion should be triggered if a test fails. This is true by default. */ void setAssertOnFailure (bool shouldAssert) noexcept; /** Sets a flag to indicate whether successful tests should be logged. By default, this is set to false, so that only failures will be displayed in the log. */ void setPassesAreLogged (bool shouldDisplayPasses) noexcept; //============================================================================== /** Contains the results of a test. One of these objects is instantiated each time UnitTest::beginTest() is called, and it contains details of the number of subsequent UnitTest::expect() calls that are made. */ struct TestResult { /** The main name of this test (i.e. the name of the UnitTest object being run). */ String unitTestName; /** The name of the current subcategory (i.e. the name that was set when UnitTest::beginTest() was called). */ String subcategoryName; /** The number of UnitTest::expect() calls that succeeded. */ int passes; /** The number of UnitTest::expect() calls that failed. */ int failures; /** A list of messages describing the failed tests. */ StringArray messages; }; /** Returns the number of TestResult objects that have been performed. @see getResult */ int getNumResults() const noexcept; /** Returns one of the TestResult objects that describes a test that has been run. @see getNumResults */ const TestResult* getResult (int index) const noexcept; protected: /** Called when the list of results changes. You can override this to perform some sort of behaviour when results are added. */ virtual void resultsUpdated(); /** Logs a message about the current test progress. By default this just writes the message to the Logger class, but you could override this to do something else with the data. */ virtual void logMessage (const String& message); /** This can be overridden to let the runner know that it should abort the tests as soon as possible, e.g. because the thread needs to stop. */ virtual bool shouldAbortTests(); private: //============================================================================== friend class UnitTest; UnitTest* currentTest; String currentSubCategory; OwnedArray <TestResult, CriticalSection> results; bool assertOnFailure, logPasses; Random randomForTest; void beginNewTest (UnitTest* test, const String& subCategory); void endTest(); void addPass(); void addFail (const String& failureMessage); JUCE_DECLARE_NON_COPYABLE (UnitTestRunner) }; #endif // JUCE_UNITTEST_H_INCLUDED
[ "gbevin@uwyn.com" ]
gbevin@uwyn.com
098bb755c508ba736bca53a28ba055d2f7c1c211
d9b4adb8bdd3a19859b050c1735d06a380bb9929
/poj-cpp/3671/14921265_AC_32MS_704K.cc
fbaf680d63126ac1c8b37d249bc775696dcd0d64
[]
no_license
conwnet/way-of-algorithm
eea4901ab62a6bc189e5c60209dc1e8610f76806
201df876cf55a7eae7e55789f2fa43d2f2545628
refs/heads/master
2021-07-31T19:17:48.871429
2021-07-24T17:42:30
2021-07-24T17:42:30
75,063,660
20
2
null
null
null
null
UTF-8
C++
false
false
638
cc
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; int cow[30010], N, dp[30010][2]; int main() { scanf("%d", &N); for(int i=1; i<=N; i++) scanf("%d", &cow[i]); for(int i=1; i<=N; i++) { if(cow[i]==1) { dp[i][0] = dp[i-1][0]; dp[i][1] = min(dp[i][0], dp[i-1][1])+1; } else { dp[i][0] = dp[i-1][0]+1; dp[i][1] = min(dp[i-1][0], dp[i-1][1]); } } printf("%d\n", min(dp[N][0], dp[N][1])); return 0; }
[ "netcon@live.com" ]
netcon@live.com
cc819c64009fbf92fd0cd9b870b643aaa5c7b4fe
be2c1b107c8a544e990ba4a4a29be51ceeeb1cef
/MAE 172 Quadcopter/src/Flight.cpp
788c1deef74ef946fab698074ff56c18f931c588
[]
no_license
Nub/MAE-172-Quadcopter
a924636c245edc47856a04e34883a3ea776cadfa
0e2dd4e98ff6e8f795c43925c2e0a633d3fd1796
refs/heads/master
2021-01-13T02:51:56.010387
2016-03-13T20:06:30
2016-03-13T20:06:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,811
cpp
// // Flight.cpp // Library C++ code // ---------------------------------- // Developed with embedXcode+ // http://embedXcode.weebly.com // // Project MAE 172 Quadcopter // // Created by Sage Thayer, 1/22/16 5:17 PM // Sage Thayer // // Copyright (c) Sage Thayer, 2016 // Licence <#license#> // // See Flight.h and ReadMe.txt for references // // Library header #include "Flight.h" // Code //Constructor QuadCopter::QuadCopter(float* Dt) { Yaw.setDifferentialTime(Dt); Pitch.setDifferentialTime(Dt); Roll.setDifferentialTime(Dt); Altitude.setDifferentialTime(Dt); //Set the controller feedbacks (actual position) Yaw.setFeedback(&attitude[2]); Pitch.setFeedback(&attitude[1]); Roll.setFeedback(&attitude[0]); Altitude.setFeedback(&position[2]); //Standard gains yawGains[0] = 1.0; yawGains[1] = 5; yawGains[2] = 10; //P, D, DD pitchGains[0] = 1.0; pitchGains[1] = 5; pitchGains[2] = 10; //P, D, DD rollGains[0] = 1.0; rollGains[1] = 5; rollGains[2] = 10; //P, D, DD altitudeGains[0] = 1; altitudeGains[1] = 10; altitudeGains[2] = 0; // P, D, I: PD controller for altitude //Standard Mixer Percent yawPercent = .2; pitchPercent = .4; rollPercent = .4; Yaw.setGains(yawGains); Pitch.setGains(pitchGains); Roll.setGains(rollGains); Altitude.setGains(altitudeGains); } QuadCopter::QuadCopter(float* Dt, T* ESCSignal[4]) { Yaw.setDifferentialTime(Dt); Pitch.setDifferentialTime(Dt); Roll.setDifferentialTime(Dt); Altitude.setDifferentialTime(Dt); ESCSignal[0] = &escSignal[0]; ESCSignal[1] = &escSignal[1]; ESCSignal[2] = &escSignal[2]; ESCSignal[3] = &escSignal[3]; //Set the controller feedbacks (actual position) Yaw.setFeedback(&attitude[2]); Pitch.setFeedback(&attitude[1]); Roll.setFeedback(&attitude[0]); Altitude.setFeedback(&position[2]); //Standard gains yawGains[0] = 1.0; yawGains[1] = 5; yawGains[2] = 10; //P, D, DD pitchGains[0] = 1.0; pitchGains[1] = 5; pitchGains[2] = 10; //P, D, DD rollGains[0] = 1.0; rollGains[1] = 5; rollGains[2] = 10; //P, D, DD altitudeGains[0] = 1; altitudeGains[1] = 10; altitudeGains[2] = 0; // P, D, I: PD controller for altitude yawGains = yawGains/10; pitchGains = yawGains/10; rollGains = yawGains/10; altitudeGains = altitudeGains/10; yawPercent = .05; pitchPercent = .475; rollPercent = .475; //set gains in controller objects Yaw.setGains(yawGains); Pitch.setGains(pitchGains); Roll.setGains(rollGains); Altitude.setGains(altitudeGains); } void QuadCopter::mixMotors() { //positve roll is a dip right in the quads frame //positve pitch is a moment upwards in the quads frame //positve yaw is a spin to the right //stabilization or control of each axis escSignal[0] = -(yawPercent)*Yaw.getControlSignal()/2 + (rollPercent)*Roll.getControlSignal()/2 + (pitchPercent)*Pitch.getControlSignal()/2; //motor 1 escSignal[1] = (yawPercent)*Yaw.getControlSignal()/2 + (rollPercent)*Roll.getControlSignal()/2 - (pitchPercent)*Pitch.getControlSignal()/2; //motor 2 escSignal[2] = (yawPercent)*Yaw.getControlSignal()/2 - (rollPercent)*Roll.getControlSignal()/2 + (pitchPercent)*Pitch.getControlSignal()/2; //motor 3 escSignal[3] = -(yawPercent)*Yaw.getControlSignal()/2 - (rollPercent)*Roll.getControlSignal()/2 - (pitchPercent)*Pitch.getControlSignal()/2; //motor 4 //append altitude control escSignal[0] += Altitude.getControlSignal(); //motor 1 escSignal[1] += Altitude.getControlSignal(); //motor 2 escSignal[2] += Altitude.getControlSignal(); //motor 3 escSignal[3] += Altitude.getControlSignal(); //motor 4 } // method to hold the quad level and at a set height void QuadCopter::steadyLevelFlight() { //Set the controller desired position Yaw.setDesiredOuptut(0); Pitch.setDesiredOuptut(0); Roll.setDesiredOuptut(0); // 1 m Altitude.setDesiredOuptut(100); Yaw.update(); Pitch.update(); Roll.update(); Altitude.update(); this->mixMotors(); } // Lets land bool QuadCopter::land() { //Stay level Yaw.setDesiredOuptut(0); Pitch.setDesiredOuptut(0); Roll.setDesiredOuptut(0); //update attitude controllers Yaw.update(); Pitch.update(); Roll.update(); Altitude.update(); // Set new height to be zero desiredAltitude = 0; this->mixMotors(); if (position[2] - desiredAltitude <= landThreshold) { return true; } else { return false; } }
[ "stthayer@uci.edu" ]
stthayer@uci.edu
0564866adcfb9a7691224ec3c1c90724cce0a416
eda2b66cd014e529bcaa4440d79b5109422ceb99
/Battleship/Temp/il2cppOutput/il2cppOutput/GeneratedGenericVirtualInvokers.h
8cb96326d494879f8d79cc810646f749d7134160
[]
no_license
jrbyam/CS372Battleship
a8b9cf491e5fdea6d466a7f5693feed70a348dfb
cb186e0a5777fc4d8879923f8cec4b5d83dac19e
refs/heads/master
2021-01-10T09:24:55.403518
2016-03-11T22:29:00
2016-03-11T22:29:00
51,184,324
0
0
null
null
null
null
UTF-8
C++
false
false
519
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #pragma once template <typename T1, typename T2> struct GenericVirtActionInvoker2 { typedef void (*Action)(void*, T1, T2, const MethodInfo*); static inline void Invoke (const MethodInfo* method, void* obj, T1 p1, T2 p2) { VirtualInvokeData data = il2cpp::vm::Runtime::GetGenericVirtualInvokeData (method, obj); ((Action)data.methodInfo->method)(data.target, p1, p2, data.methodInfo); } };
[ "jrbyam@Brock.local" ]
jrbyam@Brock.local
505e7284e813fe17ee871307c61cc81c84bf46a4
65c92f6c171a0565fe5275ecc48033907090d69d
/Client/Plugins/TimeTable/Implementation/EdtSceneProxyWidget.cpp
5c3a51e66bca8dfc62e842862f9a03c0af3b6b34
[]
no_license
freakyzoidberg/horus-edu
653ac573887d83a803ddff1881924ab82b46f5f6
2757766a6cb8c1f1a1b0a8e209700e6e3ccea6bc
refs/heads/master
2020-05-20T03:08:15.276939
2010-01-07T14:34:51
2010-01-07T14:34:51
32,684,226
0
0
null
null
null
null
UTF-8
C++
false
false
7,244
cpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Horus is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * Horus is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with Horus. If not, see <http://www.gnu.org/licenses/>. * * * * The orginal content of this material was realized as part of * * 'Epitech Innovative Project' www.epitech.eu * * * * You are required to preserve the names of the original authors * * of this content in every copy of this material * * * * Authors : * * - BERTHOLON Romain * * - GRANDEMANGE Adrien * * - LACAVE Pierre * * - LEON-BONNET Valentin * * - NANOUCHE Abderrahmane * * - THORAVAL Gildas * * - VIDAL Jeremy * * * * You are also invited but not required to send a mail to the original * * authors of this content in case of modification of this material * * * * Contact: contact@horus-edu.net * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include "EdtSceneProxyWidget.h" #include <QGraphicsItem> EdtSceneProxyWidget::EdtSceneProxyWidget(PluginManager *pluginManager, TreeData *treedata, qint8 width, qint8 height) : _pluginManager(pluginManager) { _scene = new EDTScene(pluginManager, treedata); _scene->setBackgroundBrush(QPixmap(":/background.png")); _scene->setSceneRect(0,0, width,height); this->setAlignment(Qt::AlignLeft | Qt::AlignTop); for (int i = 1; i <= 7; i++) !this->reDesignEvent(i); this->setScene(_scene); } EdtSceneProxyWidget::EdtSceneProxyWidget(PluginManager *pluginManager, qint8 width, qint8 height) : _pluginManager(pluginManager) { _scene = new EDTScene(pluginManager); _scene->setBackgroundBrush(QPixmap(":/background.png")); _scene->setSceneRect(0,0, width,height); this->setAlignment(Qt::AlignLeft | Qt::AlignTop); for (int i = 1; i <= 7; i++) this->reDesignEvent(i); this->setScene(_scene); } EdtSceneProxyWidget::~EdtSceneProxyWidget() { if (_scene) delete _scene; } bool EdtSceneProxyWidget::reDesignEvent(int day) { this->repaint();; QList<QGraphicsItem *> listItem = _scene->items(QRectF(_scene->getWPosforDay(day),50,10,800) ); QList<QGraphicsItemGroup*> listGroup; bool add; for (int i = 0; i < listItem.size(); i++) { if (listItem.at(i)->group() != 0) { add = true; for (int j = 0; j < listGroup.size(); j++) if (listGroup.at(j) == listItem.at(i)->group()) add = false; if (add) listGroup.append(listItem.at(i)->group()); } } for (int i = 0; i < listGroup.size(); i++) { if ((i < (listGroup.size() - 1)) && (listGroup.at(i)->collidingItems().size() < listGroup.at(i+1)->collidingItems().size())) { listGroup.swap(i,i+1); i = 0; } } if (listGroup.size() <= 0) return true; qDebug() << "There is " << listGroup.size() << " group Item"; for (int j = 0; j < listGroup.size(); j++) { listGroup = getCollidingItemGroup(listGroup.at(j)); if (listGroup.size() > 1) { int decalage; qDebug() << "Il ya " << listGroup.size() << " Collisions"; decalage = (100)/ listGroup.size(); for (int i = 0; i < listGroup.size(); i++) { listGroup.at(i)->setPos(listGroup.at(i)->x() + (i * decalage) - 2, listGroup.at(i)->y()); listGroup.at(i)->scale(1/(static_cast<qreal>(listGroup.size()) + 0.15),1); } } } return false; /* QList<QGraphicsItem *> collisionlistItem = group->collidingItems(); QList<QGraphicsItemGroup*> collisionlistGroup; bool add; for (int i = 0; i < collisionlistItem.size(); i++) { if (collisionlistItem.at(i)->group() != 0) { add = true; for (int j = 0; j < collisionlistGroup.size(); j++) if (collisionlistGroup.at(j) == collisionlistItem.at(i)->group()) add = false; if (add) collisionlistGroup.append(collisionlistItem.at(i)->group()); } } int decalage; if (collisionlistGroup.size() > 1) { decalage = (CWIDTH)/ collisionlistGroup.size(); for (int i = 0; i < collisionlistGroup.size(); i++) { collisionlistGroup.at(i)->setPos(collisionlistGroup.at(i)->x() + (i * decalage),collisionlistGroup.at(i)->y()); collisionlistGroup.at(i)->scale(1/static_cast<qreal>(collisionlistGroup.size()),1); } } */ } QList<QGraphicsItemGroup*> EdtSceneProxyWidget::getCollidingItemGroup(QGraphicsItemGroup *group) { QList<QGraphicsItem *> collisionlistItem = group->collidingItems(Qt::IntersectsItemBoundingRect); QList<QGraphicsItemGroup*> collisionlistGroup; bool add; for (int i = 0; i < collisionlistItem.size(); i++) { if (collisionlistItem.at(i)->group() != 0) { add = true; for (int j = 0; j < collisionlistGroup.size(); j++) if (collisionlistGroup.at(j) == collisionlistItem.at(i)->group()) add = false; if (add) { // if (collisionlistItem.at(i)->group() != group) collisionlistGroup.append(collisionlistItem.at(i)->group()); } } } return collisionlistGroup; } int EdtSceneProxyWidget::getMaxColafterRedesign(QList<QGraphicsItemGroup*> listg) { if (listg.size() <= 0) return 1; return 1; }
[ "freakyzoidberg@users.noreply.github.com" ]
freakyzoidberg@users.noreply.github.com
83696e0a33dfc8c6970c4816dea3b107b4978bec
0436bf0c8276500a3ff59093bc6d3561268134c6
/apps/rtigo9_omm/src/main.cpp
c0e12f9268662cadb7a45874308bd35b72d5805f
[]
no_license
NVIDIA/OptiX_Apps
7e21234c3e3c0e5237d011fc567da7f3f90e2c51
2ff552ce4b2cf0e998531899bb8b39d27e064d06
refs/heads/master
2023-08-20T02:47:58.294963
2023-08-08T10:29:36
2023-08-08T10:29:36
239,562,369
223
42
null
2023-09-04T09:31:07
2020-02-10T16:47:28
C++
UTF-8
C++
false
false
4,537
cpp
/* * Copyright (c) 2013-2020, 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 NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "shaders/config.h" #include "inc/Application.h" #include <IL/il.h> #include <algorithm> #include <iostream> static Application* g_app = nullptr; static void callbackError(int error, const char* description) { std::cerr << "ERROR: "<< error << ": " << description << '\n'; } static int runApp(const Options& options) { int width = std::max(1, options.getWidth()); int height = std::max(1, options.getHeight()); GLFWwindow* window = glfwCreateWindow(width, height, "rtigo9_omm - Copyright (c) 2022 NVIDIA Corporation", NULL, NULL); if (!window) { callbackError(APP_ERROR_CREATE_WINDOW, "glfwCreateWindow() failed."); return APP_ERROR_CREATE_WINDOW; } glfwMakeContextCurrent(window); if (glewInit() != GL_NO_ERROR) { callbackError(APP_ERROR_GLEW_INIT, "GLEW failed to initialize."); return APP_ERROR_GLEW_INIT; } ilInit(); // Initialize DevIL once. g_app = new Application(window, options); if (!g_app->isValid()) { std::cerr << "ERROR: Application() failed to initialize successfully.\n"; ilShutDown(); return APP_ERROR_APP_INIT; } const int mode = std::max(0, options.getMode()); if (mode == 0) // Interactive, default. { // Main loop bool finish = false; while (!finish && !glfwWindowShouldClose(window)) { glfwPollEvents(); // Render continuously. Battery drainer! glfwGetFramebufferSize(window, &width, &height); g_app->reshape(width, height); g_app->guiNewFrame(); //g_app->guiReferenceManual(); // HACK The ImGUI "Programming Manual" as example code. g_app->guiWindow(); // This application's GUI window rendering commands. g_app->guiEventHandler(); // SPACE to toggle the GUI windows and all mouse tracking via GuiState. finish = g_app->render(); // OptiX rendering, returns true when benchmark is enabled and the samples per pixel have been rendered. g_app->display(); // OpenGL display always required to lay the background for the GUI. g_app->guiRender(); // Render all ImGUI elements at last. glfwSwapBuffers(window); //glfwWaitEvents(); // Render only when an event is happening. Needs some glfwPostEmptyEvent() to prevent GUI lagging one frame behind when ending an action. } } else if (mode == 1) // Batched benchmark single shot. // FIXME When not using anything OpenGL, the whole window and OpenGL setup could be removed. { g_app->benchmark(); } delete g_app; ilShutDown(); return APP_EXIT_SUCCESS; } int main(int argc, char *argv[]) { glfwSetErrorCallback(callbackError); if (!glfwInit()) { callbackError(APP_ERROR_GLFW_INIT, "GLFW failed to initialize."); return APP_ERROR_GLFW_INIT; } int result = APP_ERROR_UNKNOWN; Options options; if (options.parseCommandLine(argc, argv)) { result = runApp(options); } glfwTerminate(); return result; }
[ "droettger@nvidia.com" ]
droettger@nvidia.com
9a0c8ebb2b9d1482c2fe189f4074a17ce39cbf93
583e18a04387fba52dfcd0f94861c472fb889279
/source/logging/record.cpp
d36f9ffc90e6ec8d8f0064e1bdd07fee6f530bd8
[ "MIT" ]
permissive
alexlaguta/CppLogging
d64e371c95992fec1398563a453f2e598cb7ad57
d4c69d7ee0de115db6eb8de9e4aa61a8d7863e02
refs/heads/master
2022-08-07T03:18:45.005232
2020-05-18T10:49:15
2020-05-18T10:49:15
264,909,944
0
0
null
2020-05-18T10:48:30
2020-05-18T10:48:29
null
UTF-8
C++
false
false
29,515
cpp
/*! \file record.cpp \brief Logging record implementation \author Ivan Shynkarenka \date 08.07.2016 \copyright MIT License */ #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // clang: warning: 'function': was declared deprecated #elif defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // GCC: warning: 'function': was declared deprecated #elif defined(_MSC_VER) #pragma warning(push) #pragma warning(disable: 4996) // C4996: 'function': was declared deprecated #endif #include "logging/record.h" #include <map> namespace { bool IsDigit(char ch) { return (ch >= '0') && (ch <= '9'); } bool IsStartName(char ch) { return ((ch >= 'A') && (ch <= 'Z')) || ((ch >= 'a') && (ch <= 'z')) || (ch == '_'); } bool IsMiddleName(char ch) { return IsStartName(ch) || IsDigit(ch); } struct Argument { CppLogging::ArgumentType type; size_t offset; size_t size; bool GetUnsigned(const std::vector<uint8_t>& buffer, size_t& result) const { switch (type) { case CppLogging::ArgumentType::ARG_INT8: { int8_t value; std::memcpy(&value, buffer.data() + offset, sizeof(int8_t)); result = (size_t)value; return true; } case CppLogging::ArgumentType::ARG_UINT8: { uint8_t value; std::memcpy(&value, buffer.data() + offset, sizeof(uint8_t)); result = (size_t)value; return true; } case CppLogging::ArgumentType::ARG_INT16: { int16_t value; std::memcpy(&value, buffer.data() + offset, sizeof(int16_t)); result = (size_t)value; return true; } case CppLogging::ArgumentType::ARG_UINT16: { uint16_t value; std::memcpy(&value, buffer.data() + offset, sizeof(uint16_t)); result = (size_t)value; return true; } case CppLogging::ArgumentType::ARG_INT32: { int32_t value; std::memcpy(&value, buffer.data() + offset, sizeof(int32_t)); result = (size_t)value; return true; } case CppLogging::ArgumentType::ARG_UINT32: { uint32_t value; std::memcpy(&value, buffer.data() + offset, sizeof(uint32_t)); result = (size_t)value; return true; } case CppLogging::ArgumentType::ARG_INT64: { int64_t value; std::memcpy(&value, buffer.data() + offset, sizeof(int64_t)); result = (size_t)value; return true; } case CppLogging::ArgumentType::ARG_UINT64: { uint64_t value; std::memcpy(&value, buffer.data() + offset, sizeof(uint64_t)); result = (size_t)value; return true; } default: { assert(false && "Unsupported argument type!"); return false; } } } }; struct Arguments { std::vector<Argument> arguments; std::map<std::string, Argument> named_arguments; }; Argument ParseArgument(const std::vector<uint8_t>& buffer, size_t index) { // Parse the argument type CppLogging::ArgumentType type; std::memcpy(&type, buffer.data() + index, sizeof(uint8_t)); index += sizeof(uint8_t); // Parse the argument value switch (type) { case CppLogging::ArgumentType::ARG_BOOL: return Argument{ type, index, sizeof(uint8_t) }; case CppLogging::ArgumentType::ARG_CHAR: return Argument{ type, index, sizeof(uint8_t) }; case CppLogging::ArgumentType::ARG_WCHAR: return Argument{ type, index, sizeof(uint32_t) }; case CppLogging::ArgumentType::ARG_INT8: return Argument{ type, index, sizeof(int8_t) }; case CppLogging::ArgumentType::ARG_UINT8: return Argument{ type, index, sizeof(uint8_t) }; case CppLogging::ArgumentType::ARG_INT16: return Argument{ type, index, sizeof(int16_t) }; case CppLogging::ArgumentType::ARG_UINT16: return Argument{ type, index, sizeof(uint16_t) }; case CppLogging::ArgumentType::ARG_INT32: return Argument{ type, index, sizeof(int32_t) }; case CppLogging::ArgumentType::ARG_UINT32: return Argument{ type, index, sizeof(uint32_t) }; case CppLogging::ArgumentType::ARG_INT64: return Argument{ type, index, sizeof(int64_t) }; case CppLogging::ArgumentType::ARG_UINT64: return Argument{ type, index, sizeof(uint64_t) }; case CppLogging::ArgumentType::ARG_FLOAT: return Argument{ type, index, sizeof(float) }; case CppLogging::ArgumentType::ARG_DOUBLE: return Argument{ type, index, sizeof(double) }; case CppLogging::ArgumentType::ARG_STRING: { uint32_t size; std::memcpy(&size, buffer.data() + index, sizeof(uint32_t)); return Argument{ type, index, sizeof(uint32_t) + size }; } case CppLogging::ArgumentType::ARG_POINTER: return Argument{ type, index, sizeof(uint64_t) }; case CppLogging::ArgumentType::ARG_CUSTOM: { uint32_t size; std::memcpy(&size, buffer.data() + index, sizeof(uint32_t)); return Argument{ type, index, size }; } case CppLogging::ArgumentType::ARG_LIST: { uint32_t size; std::memcpy(&size, buffer.data() + index, sizeof(uint32_t)); return Argument{ type, index, size }; } default: { assert(false && "Unsupported argument type!"); return Argument{ CppLogging::ArgumentType::ARG_UNKNOWN, 0, 0 }; } } } Arguments ParseArguments(const std::vector<uint8_t>& buffer, size_t offset, size_t size) { Arguments result; size_t index = offset; while (index < (offset + size)) { // Parse the argument type CppLogging::ArgumentType type; std::memcpy(&type, buffer.data() + index, sizeof(uint8_t)); if (type == CppLogging::ArgumentType::ARG_NAMEDARG) { index += sizeof(uint8_t); uint32_t length; std::memcpy(&length, buffer.data() + index, sizeof(uint32_t)); index += sizeof(uint32_t); std::string name; name.resize(length); std::memcpy(name.data(), buffer.data() + index, length); index += length; Argument argument = ParseArgument(buffer, index); index += sizeof(uint8_t) + argument.size; result.named_arguments[name] = argument; } else { Argument argument = ParseArgument(buffer, index); index += sizeof(uint8_t) + argument.size; result.arguments.emplace_back(argument); } } return result; } bool ParseUnsigned(std::string_view::iterator& it, const std::string_view::iterator& end, size_t& result) { result = 0; size_t max_int = std::numeric_limits<int>::max(); size_t big_int = max_int / 10; char current = *it; while (IsDigit(current)) { // Check for overflow. if (result > big_int) { result = max_int + 1; break; } result = 10 * result + (current - '0'); if (++it == end) { assert(false && "Invalid format message! Unmatched '}' in the format string."); return false; } current = *it; } if (result > max_int) { assert(false && "Invalid format message! Number is too big."); return false; } return true; } bool ParseName(std::string_view::iterator& it, const std::string_view::iterator& end, std::string& result) { result = ""; char current = *it; if (IsStartName(current)) { result.push_back(current); while (it != end) { if (++it == end) { assert(false && "Invalid format message! Unmatched '}' in the format string."); return false; } current = *it; if (IsMiddleName(current)) result.push_back(current); else break; } } return true; } bool WriteFormatArgument(fmt::writer& writer, const fmt::writer::format_specs& specs, const Argument& argument, const std::vector<uint8_t> buffer) { switch (argument.type) { case CppLogging::ArgumentType::ARG_BOOL: { uint8_t value; std::memcpy(&value, buffer.data() + argument.offset, sizeof(uint8_t)); writer.write_int(value != 0, specs); return true; } case CppLogging::ArgumentType::ARG_CHAR: { uint8_t value; std::memcpy(&value, buffer.data() + argument.offset, sizeof(uint8_t)); writer.write((char)value); return true; } case CppLogging::ArgumentType::ARG_WCHAR: { uint32_t value; std::memcpy(&value, buffer.data() + argument.offset, sizeof(uint32_t)); writer.write((char)value); return true; } case CppLogging::ArgumentType::ARG_INT8: { int8_t value; std::memcpy(&value, buffer.data() + argument.offset, sizeof(int8_t)); writer.write_int(value, specs); return true; } case CppLogging::ArgumentType::ARG_UINT8: { uint8_t value; std::memcpy(&value, buffer.data() + argument.offset, sizeof(uint8_t)); writer.write_int(value, specs); return true; } case CppLogging::ArgumentType::ARG_INT16: { int16_t value; std::memcpy(&value, buffer.data() + argument.offset, sizeof(int16_t)); writer.write_int(value, specs); return true; } case CppLogging::ArgumentType::ARG_UINT16: { uint16_t value; std::memcpy(&value, buffer.data() + argument.offset, sizeof(uint16_t)); writer.write_int(value, specs); return true; } case CppLogging::ArgumentType::ARG_INT32: { int32_t value; std::memcpy(&value, buffer.data() + argument.offset, sizeof(int32_t)); writer.write_int(value, specs); return true; } case CppLogging::ArgumentType::ARG_UINT32: { uint32_t value; std::memcpy(&value, buffer.data() + argument.offset, sizeof(uint32_t)); writer.write_int(value, specs); return true; } case CppLogging::ArgumentType::ARG_INT64: { int64_t value; std::memcpy(&value, buffer.data() + argument.offset, sizeof(int64_t)); writer.write_int(value, specs); return true; } case CppLogging::ArgumentType::ARG_UINT64: { uint64_t value; std::memcpy(&value, buffer.data() + argument.offset, sizeof(uint64_t)); writer.write_int(value, specs); return true; } case CppLogging::ArgumentType::ARG_FLOAT: { float value; std::memcpy(&value, buffer.data() + argument.offset, sizeof(float)); writer.write(value, specs); return true; } case CppLogging::ArgumentType::ARG_DOUBLE: { double value; std::memcpy(&value, buffer.data() + argument.offset, sizeof(double)); writer.write(value, specs); return true; } case CppLogging::ArgumentType::ARG_STRING: { uint32_t length; std::memcpy(&length, buffer.data() + argument.offset, sizeof(uint32_t)); writer.write(fmt::string_view((const char*)buffer.data() + argument.offset + sizeof(uint32_t), length), specs); return true; } case CppLogging::ArgumentType::ARG_POINTER: { uint64_t value; std::memcpy(&value, buffer.data() + argument.offset, sizeof(uint64_t)); writer.write_pointer((uintptr_t)value, &specs); return true; } case CppLogging::ArgumentType::ARG_CUSTOM: { size_t index = argument.offset; // Parse the custom data type size uint32_t custom_size; std::memcpy(&custom_size, buffer.data() + index, sizeof(uint32_t)); index += sizeof(uint32_t); custom_size -= sizeof(uint32_t); // Parse the pattern length uint32_t custom_pattern_length; std::memcpy(&custom_pattern_length, buffer.data() + index, sizeof(uint32_t)); index += sizeof(uint32_t); custom_size -= sizeof(uint32_t); // Parse the pattern value std::string custom_pattern; custom_pattern.resize(custom_pattern_length); std::memcpy(custom_pattern.data(), buffer.data() + index, custom_pattern_length); index += custom_pattern_length; custom_size -= custom_pattern_length; std::string custom = CppLogging::Record::RestoreFormat(custom_pattern, buffer, index, custom_size); writer.write(custom); return true; } case CppLogging::ArgumentType::ARG_LIST: { size_t index = argument.offset; // Parse the list size uint32_t list_size; std::memcpy(&list_size, buffer.data() + index, sizeof(uint32_t)); index += sizeof(uint32_t); list_size -= sizeof(uint32_t); // Write arguments from the list while (index < (argument.offset + sizeof(uint32_t) + list_size)) { Argument arg = ParseArgument(buffer, index); if (!WriteFormatArgument(writer, specs, arg, buffer)) return false; index += sizeof(uint8_t) + arg.size; } return true; } default: { assert(false && "Unsupported argument type!"); return false; } } } } // namespace namespace CppLogging { std::string Record::RestoreFormat(std::string_view pattern, const std::vector<uint8_t> buffer, size_t offset, size_t size) { std::string result; // Parse arguments and check arguments count before formatting auto args = ParseArguments(buffer, offset, size); if (args.arguments.empty() && args.named_arguments.empty()) return std::string(pattern); size_t argument_current_index = 0; // Parse the format message pattern for (auto it = pattern.begin(); it < pattern.end(); ++it) { char current = *it; if (current == '{') { if (++it == pattern.end()) { assert(false && "Invalid format message! Unmatched '}' in the format string."); return std::string(pattern); } char next = *it; // Match '{{' pattern if (next == '{') { result.push_back('{'); continue; } // Match '}}' pattern if (next == '}') { if (++it != pattern.end()) { if (*it == '}') { result.push_back('}'); continue; } } --it; } current = next; // Argument settings size_t argument_index = argument_current_index++; std::string argument_name; bool argument_width = false; size_t argument_width_index = 0; std::string argument_width_name; bool argument_precision = false; size_t argument_precision_index = 0; std::string argument_precision_name; fmt::align_t align_type = fmt::align_t::none; bool align_alt = false; char align_fill = ' '; fmt::sign_t sign = fmt::sign_t::none; size_t width = 0; int precision = -1; char type = 0; // Parse argument index if (IsDigit(current)) { if (!ParseUnsigned(it, pattern.end(), argument_index)) return std::string(pattern); } else if (IsStartName(current)) { if (!ParseName(it, pattern.end(), argument_name)) return std::string(pattern); } current = *it; // Parse argument settings if ((current == ':') && (it != pattern.end())) { // Parse align settings int align_index = 0; if ((it + 1) != pattern.end()) { ++align_index; ++it; } do { auto align_ch = *(it + align_index); switch (align_ch) { case '<': align_type = fmt::align_t::left; break; case '>': align_type = fmt::align_t::right; break; case '=': align_type = fmt::align_t::numeric; break; case '^': align_type = fmt::align_t::center; break; default: break; } if (align_type != fmt::align_t::none) { if (align_index > 0) { auto ch = *it; if (ch == '{') { assert(false && "Invalid format message! Invalid fill character '{' in the format string."); return std::string(pattern); } it += 2; align_fill = ch; } else ++it; break; } } while (align_index-- > 0); // Parse sign if (it != pattern.end()) { current = *it; switch (current) { case '+': sign = fmt::sign_t::plus; ++it; break; case '-': sign = fmt::sign_t::minus; ++it; break; case ' ': sign = fmt::sign_t::space; ++it; break; default: break; } } // Parse hash if (it != pattern.end()) { current = *it; if (current == '#') { align_alt = true; ++it; } } // Parse zero flag if (it != pattern.end()) { current = *it; if (current == '0') { align_type = fmt::align_t::numeric; align_fill = '0'; ++it; } } // Parse width if (it != pattern.end()) { current = *it; if (IsDigit(current)) { if (!ParseUnsigned(it, pattern.end(), width)) return std::string(pattern); } else if (current == '{') { if (++it == pattern.end()) { assert(false && "Invalid format message! Invalid format width specifier."); return std::string(pattern); } current = *it; if (IsDigit(current)) { if (!ParseUnsigned(it, pattern.end(), argument_width_index)) return std::string(pattern); argument_width = true; } else if (IsStartName(current)) { if (!ParseName(it, pattern.end(), argument_width_name)) return std::string(pattern); argument_width = true; } if ((it == pattern.end()) || (*it++ != '}')) { assert(false && "Invalid format message! Invalid format width specifier."); return std::string(pattern); } if (!argument_width) { argument_width_index = argument_current_index++; argument_width = true; } // Parse width argument if (!argument_width_name.empty()) { auto it_width = args.named_arguments.find(argument_width_name); if ((it_width == args.named_arguments.end()) || !it_width->second.GetUnsigned(buffer, width)) { assert(false && "Invalid format message! Cannot find argument width specifier by name."); return std::string(pattern); } } else { if ((argument_width_index > args.arguments.size()) || !args.arguments[argument_width_index].GetUnsigned(buffer, width)) { assert(false && "Invalid format message! Cannot find or parse argument width specifier."); return std::string(pattern); } } } } // Parse precision if (it != pattern.end()) { current = *it; if (current == '.') { if (++it == pattern.end()) { assert(false && "Invalid format message! Invalid format precision specifier."); return std::string(pattern); } current = *it; if (IsDigit(current)) { size_t prec; if (!ParseUnsigned(it, pattern.end(), prec)) return std::string(pattern); precision = (int)prec; } else if (current == '{') { if (++it == pattern.end()) { assert(false && "Invalid format message! Invalid format precision specifier."); return std::string(pattern); } current = *it; if (IsDigit(current)) { if (!ParseUnsigned(it, pattern.end(), argument_precision_index)) return std::string(pattern); argument_precision = true; } else if (IsStartName(current)) { if (!ParseName(it, pattern.end(), argument_precision_name)) return std::string(pattern); argument_precision = true; } if ((it == pattern.end()) || (*it++ != '}')) { assert(false && "Invalid format message! Invalid format precision specifier."); return std::string(pattern); } if (!argument_precision) { argument_precision_index = argument_current_index++; argument_precision = true; } // Parse precision argument size_t prec = 0; if (!argument_precision_name.empty()) { auto it_prec = args.named_arguments.find(argument_precision_name); if ((it_prec == args.named_arguments.end()) || !it_prec->second.GetUnsigned(buffer, prec)) { assert(false && "Invalid format message! Cannot find argument precision specifier by name."); return std::string(pattern); } } else { if ((argument_precision_index > args.arguments.size()) || !args.arguments[argument_precision_index].GetUnsigned(buffer, prec)) { assert(false && "Invalid format message! Cannot find or parse argument precision specifier."); return std::string(pattern); } } precision = (int)prec; } } } } // Parse type if ((it != pattern.end()) && (*it != '}')) { current = *it; type = current; ++it; } // Parse the end of argument if ((it == pattern.end()) || (*it != '}')) { assert(false && "Invalid format message! Unmatched '}' in the format string."); return std::string(pattern); } fmt::format_specs specs; specs.align = align_type; specs.alt = align_alt; specs.fill[0] = align_fill; specs.sign = sign; specs.width = (unsigned)width; specs.precision = precision; specs.type = type; fmt::internal::container_buffer<std::string> container(result); fmt::writer writer(container); // Get the format argument Argument argument; if (!argument_name.empty()) { auto it_arg = args.named_arguments.find(argument_name); if (it_arg == args.named_arguments.end()) { assert(false && "Invalid format message! Cannot find argument by name."); return std::string(pattern); } argument = args.named_arguments[argument_name]; } else { if (argument_index > args.arguments.size()) { assert(false && "Invalid format message! Cannot find argument by index."); return std::string(pattern); } argument = args.arguments[argument_index]; } // Write format argument if (!WriteFormatArgument(writer, specs, argument, buffer)) return std::string(pattern); } else result.push_back(current); } return result; } } // namespace CppLogging #if defined(__clang__) #pragma clang diagnostic pop #elif defined(__GNUC__) #pragma GCC diagnostic pop #elif defined(_MSC_VER) #pragma warning(pop) #endif
[ "chronoxor@gmail.com" ]
chronoxor@gmail.com
deb1be3909a15cae37ae6dbfc7e3de806f28e347
68f5893a42c15072fbe15ee4d40a872457019252
/include/yield/stage/seda_stage_scheduler.hpp
ce65f3088c99a953ff3cb0f8f16aefe0f04d30d4
[]
no_license
respu/yield
6e7ead66e7c1738ec8f34d11377603346e51e850
bd0ee589b0b227a5c42f293a11031f452317abcd
refs/heads/master
2021-01-18T10:52:23.634492
2013-08-19T21:36:25
2013-08-19T21:36:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,064
hpp
// yield/stage/seda_stage_scheduler.hpp // Copyright (c) 2013 Minor Gordon // All rights reserved // This source file is part of the Yield project. // 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 Yield project nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL Minor Gordon BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef _YIELD_STAGE_SEDA_STAGE_SCHEDULER_HPP_ #define _YIELD_STAGE_SEDA_STAGE_SCHEDULER_HPP_ #include "yield/stage/stage_scheduler.hpp" #include "yield/thread/thread.hpp" namespace yield { namespace stage { class SedaStageScheduler : public StageScheduler { public: ~SedaStageScheduler(); // StageScheduler void schedule(Stage&, ConcurrencyLevel); private: class SedaStage; private: vector< ::yield::thread::Thread*> threads; }; } } #endif
[ "github@minorgordon.net" ]
github@minorgordon.net
db24c069f43b82e7e5ef5ceced5f0c29b69b2b89
9ff7ecb1cd346cd2523b5c556405c75cebb4e66f
/10.regular-expression-matching.cpp
52507a47e8dff09dc1f2902db93cdf4028a2a461
[]
no_license
kingsmad/leetcode_2017
c8785ce3fb56e0eab0c7b5013b0bc52570bdd418
f5cc0d09c3b77faa804739ea43ba4a090397c718
refs/heads/master
2021-03-22T01:29:51.127263
2018-08-08T22:43:25
2018-08-08T22:43:25
97,318,569
0
0
null
null
null
null
UTF-8
C++
false
false
1,109
cpp
#include <assert.h> #include <cstring> #include <iostream> #include <string> #include <vector> using namespace std; const int maxn = 1e3 + 10; int dp[maxn][maxn], f[maxn]; class Solution { public: bool isMatch(string s, string p) { int n = s.size(), m = p.size(); memset(dp, -1, sizeof(dp)); return calc(n, m, s, p); } int calc(int x, int y, const string& s, const string& p) { if (x == 0 && y == 0) return 1; if (dp[x][y] != -1) return dp[x][y]; if (x > 0 && y > 0 && (p.at(y-1) == '.' || p.at(y-1) == s.at(x-1))) return dp[x][y] = calc(x-1, y-1, s, p); if (y > 0 && p.at(y-1) == '*') { if (p.at(y-2) == '.') { for (int z=x; z>=0; --z) if (calc(z, y-2, s, p)) return dp[x][y] = 1; return dp[x][y] = 0; } else { char c = p.at(y-2); int l = x; while(l>0 && s.at(l-1) == c) --l; for (int z=x; z>=l; --z) if (calc(z, y-2, s, p)) return dp[x][y] = 1; return dp[x][y] = 0; } } return dp[x][y] = 0; } }; #ifdef ROACH_ONLINE_JUDGE int main(int argc, char** argv) { } #endif
[ "grinchcoder@gmail.com" ]
grinchcoder@gmail.com
1c25ba958adf248a99fe57ca239e2dd230ebb7f0
e3d9d8ea5b1450b912dfdc33f6891c900995f552
/src/YSL_Struct.h
e6f42d6dce5bf40409cab27aece83b2f09113699
[ "MIT" ]
permissive
junha1/junhasl
d4ac379dd31341573768c0bb5526ad272b245ff4
3950364ac3213677c74c4506c2d59341d35f0c97
refs/heads/master
2021-07-16T16:31:32.494717
2020-10-06T06:07:16
2020-10-06T06:07:16
216,875,841
3
0
null
null
null
null
UTF-8
C++
false
false
3,878
h
#pragma once #include "YSL_SerializationConfiguration.h" #include "../YTL.h" #include "YSL_Common.h" #include "YSL_Types.h" namespace ysl { // This is supposed to be working properly in C++ but Visual fucking studio has serious bug. #define YSL_PACK_FV(...) static constexpr auto ysl_mps = make_tuple(__VA_ARGS__);\ static constexpr bool ysl_struct_trival = true; #define YSL_PACK(...) static constexpr auto ysl_mps() {return make_tuple(__VA_ARGS__);}\ static constexpr bool ysl_struct_trival = true; template <class T, typename... Args> static tuple<Args& ...> ysl_pack(T* t, const tuple<Args T::* ...>& mpt) { static constexpr int n = sizeof...(Args); if constexpr (n == 0) { return tuple{}; } else { static constexpr auto range = YTL::GenAtoB<0, n - 1>::ints(); return YTL::PM_Ints(range, [&](auto... S) { return std::tie(t->*get<S.value>(mpt)...); }); } } // const template <class T, typename... Args> static tuple<const Args& ...> ysl_pack(const T* t, const tuple<Args T::* ...>& mpt) { static constexpr int n = sizeof...(Args); if constexpr (n == 0) { return tuple{}; } else { static constexpr auto range = YTL::GenAtoB<0, n - 1>::ints(); return YTL::PM_Ints(range, [&](auto... S) { return std::tie(t->*get<S.value>(mpt)...); }); } } struct ysl_struct_base { // redeclare to true if your struct has only 1 member and you want to use it as itself (not in a tuple) using tuple_unpack_for_single_member = std::bool_constant<false>; void ysl_loads_notify() {} }; struct ysl_struct : public ysl_struct_base { virtual ysl_struct* ysl_factory() const = 0; virtual yobject ysl_dumps() const = 0; virtual void ysl_loads(const yobject& p) = 0; virtual void ysl_loads_notify() = 0; }; template <class T> auto ysl_struct_tuple(T* t) // returning reference is tricky. always by value. { using B = typename T::ysl_parent; if constexpr (std::is_same_v<B, void> || std::is_same_v<B, ysl_struct_base>) { if constexpr (T::tuple_unpack_for_single_member::value == false) return ysl_pack<T>(t, T::ysl_mps()); // <T> needed when mps is empty else { static_assert(std::tuple_size_v<decltype(T::ysl_mps())> == 1); return ref(t->*get<0>(T::ysl_mps())); // no tuple } } else { static_assert(T::tuple_unpack_for_single_member::value == false); if constexpr (std::tuple_size<decltype(T::ysl_mps())>::value == 0) return ysl_struct_tuple<B>(t); else return make_tuple(ysl_struct_tuple<B>(t), ysl_pack<T>(t, T::ysl_mps())); } } template <class T> decltype(auto) ysl_struct_tuple(const T* t) { using B = typename T::ysl_parent; if constexpr (std::is_same_v<B, void> || std::is_same_v<B, ysl_struct_base>) { if constexpr (T::tuple_unpack_for_single_member::value == false) return ysl_pack<T>(t, T::ysl_mps()); // <T> needed when mps is empty else { static_assert(std::tuple_size_v<decltype(T::ysl_mps())> == 1); return t->*get<0>(T::ysl_mps()); // no tuple } } else { static_assert(T::tuple_unpack_for_single_member::value == false); if constexpr (std::tuple_size<decltype(T::ysl_mps())>::value == 0) return ysl_struct_tuple<B>(t); else return make_tuple(ysl_struct_tuple<B>(t), ysl_pack<T>(t, T::ysl_mps())); } } template <class Data> struct ysl_struct_final : public Data { using ysl_parent = Data; YSL_PACK(); virtual ysl_struct* ysl_factory() const { return new ysl_struct_final(); } virtual yobject ysl_dumps() const { return to(ysl_struct_tuple((Data*)this)); } virtual void ysl_loads(const yobject& p) { auto t = ysl_struct_tuple((Data*)this); from(p, t); ysl_loads_notify(); } virtual void ysl_loads_notify() {}; // constructor pass template <typename... Args> ysl_struct_final(Args&& ... args) : Data(args...) {} }; }
[ "junhayang1@gmail.com" ]
junhayang1@gmail.com
478b8808e8fe1f7c8768587c132fbf40c75f9aab
87dba8af46ec184556a7e9169767b29493ddfaaa
/arduino_code/stm_main/src/MotorBase.cpp
7c8f0a55cc621fa8f54396fcf8997e526327dbe6
[ "MIT" ]
permissive
CouchmobileUNSW/couchmobile-control-system
64fcaefed91026ebdc5d21dbd504acf032cd85f1
411dd8adacd46e1ab85556ed70ea5bca73ea771f
refs/heads/master
2020-07-05T18:11:55.826995
2019-10-21T05:56:44
2019-10-21T05:56:44
202,724,852
0
1
MIT
2019-09-16T06:37:04
2019-08-16T12:35:54
C++
UTF-8
C++
false
false
2,786
cpp
#include "MotorBase.h" MotorBase::MotorBase(int x, unsigned int T) : enc(quadTimer[x], TICK_RATIO, T), pwm(pwmPin[x], pwmTimer[x]) { } // Initialise motors void MotorBase::begin(){ // Initialise encoders enc.begin(); // Initialise pwm pwm.setInputPulse(PWM_PERIOD, PWM_PULSE_LOW, PWM_PULSE_HIGH); pwm.setRange(CONTROL_MIN, CONTROL_MAX); pwm.begin(); // Set controller limits cont.setRange(CONTROL_MIN, CONTROL_MAX); } // Sets controller gains void MotorBase::setGains(float *e_in, uint8_t _N_e, float *m_in, uint8_t _N_m) { cont.setGains(e_in, _N_e, m_in, _N_m); } // Sets encoder speed in rad/s void MotorBase::setRadianSpeed(float w) { w_d = w; } // Controls pwm to get desired speed rad/s void MotorBase::controlSpeed() { // Write to PWM pwm.writeValue(m); } // Samples data - updates all variables // Returns true if data was updated bool MotorBase::sampleData() { if(enc.sampleData()) { w_a = enc.getRadianSpeed(); // get actual w_a (rad/s) e = w_d - w_a; // get error in w (rad/s) m = cont.getControlEffort(e); // get control effort return true; } return false; } // Get speed in counts/s float MotorBase::getTickSpeed(){ return enc.getTickSpeed(); } // Get current time in microseconds unsigned long MotorBase::getCurrTime(){ return enc.getCurrTime(); } // Get difference in sample times in seconds float MotorBase::getDeltaTime(){ return (float)enc.getDeltaTime()/1e6; } // Gets desired speed in rad/s float MotorBase::getDesiredRadianSpeed() { return w_d; } // Get speed in rad/s float MotorBase::getRadianSpeed(){ return w_a; } // Getter speed error in RAD/S float MotorBase::getRadianError() { return e; } // Gets control effort - updated from sampleData() float MotorBase::getControlEffort() { return m; } // Print motor configs void MotorBase::printSettings(){ pwm.printSettings(); cont.printSettings(); } // Write to PWM using the control range void MotorBase::writeValue(float value){ pwm.writeValue(value); } // Gets PWM output int MotorBase::getPWMOutput() { return pwm.getPWMOutput(); } // Helper function - gets control effort for given error float MotorBase::getControlEffort(float e) { return cont.getControlEffort(e); } // Gets the current encoder ticks long MotorBase::getCurrTicks() { return enc.getCurrTicks(); } // Gets the previous encoder ticks long MotorBase::getPrevTicks() { return enc.getPrevTicks(); } // Get difference in counts between samples long MotorBase::getDeltaTicks(){ return enc.getDeltaTicks(); }
[ "williamchen755@gmail.com" ]
williamchen755@gmail.com
eb90f0af7d63daab54db580fd86461ba0a2fdaf2
07cbe159795612509c2e7e59eb9c8ff6c6ed6b0d
/partitioned/RayleighBenard/singleColumn/debuggingCases/gamma_5_e-4_effectiveDiffusivities_Prandtl_1_buoyancyAnomalyMeanCoeff_0_5/system/constant/b_init
3ea047a8a57a4a82664abefcb004a685814b2c8f
[]
no_license
AtmosFOAM/danRun
aacaaf8a22e47d1eb6390190cb98fbe846001e7a
94d19c4992053d7bd860923e9605c0cbb77ca8a2
refs/heads/master
2021-03-22T04:32:10.679600
2020-12-03T21:09:40
2020-12-03T21:09:40
118,792,506
0
0
null
null
null
null
UTF-8
C++
false
false
1,242
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: dev | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "constant"; object b; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -2 0 0 0 0]; internalField uniform 0; boundaryField { ground { type fixedValue; value uniform 0.0327; } top { type fixedValue; value uniform -0.0327; } left { type cyclic; } right { type cyclic; } } // ************************************************************************* //
[ "d.shipley.1341@gmail.com" ]
d.shipley.1341@gmail.com
ea77aa605a86a61ebf7985b19d5c82653cc8f87d
61310b623d7f18dacf056f5717178158ee022147
/turtlebot_controller/src/ros_ex2_solution.cpp
cad517230c5fd07ef99ff85256b042c83ed5f126
[]
no_license
CarmineD8/ROS_packages_RT1
d5d4ef4fd7bfc10e923e4e6245781d64188febc6
a7931f1095bf7748212a3e45b54de78c4e86c9a0
refs/heads/main
2023-01-19T07:48:49.477492
2020-11-01T12:41:25
2020-11-01T12:41:25
308,055,535
0
0
null
null
null
null
UTF-8
C++
false
false
2,113
cpp
#include "ros/ros.h" #include "geometry_msgs/Twist.h" #include "turtlesim/Pose.h" #include "turtlesim/Kill.h" #include "turtlesim/Spawn.h" #include <sstream> #include <iostream> #include "std_srvs/Empty.h" #include "turtlesim/TeleportAbsolute.h" #include "my_srv/Harmonic.h" ros::Publisher chatter_pub; ros::ServiceClient client5; void subscriberCallback(const turtlesim::Pose::ConstPtr& pose_msg) { geometry_msgs::Twist msg_sent; my_srv::Harmonic rec_vel; if ((pose_msg->x >= 2.0)&(pose_msg->x<=9.0)) { rec_vel.request.pos = pose_msg->x; client5.call(rec_vel); msg_sent.linear.x = rec_vel.response.vel; msg_sent.angular.z=0.0; } else if ((pose_msg->x > 9.0)) { msg_sent.linear.x = 0.1; msg_sent.angular.z=0.1; } else if ((pose_msg->x <2.0)) { msg_sent.linear.x = 0.1; msg_sent.angular.z=-0.1; } chatter_pub.publish(msg_sent); if ((pose_msg->y >8.9)) { ros::shutdown(); } } int main(int argc, char **argv) { ros::init(argc, argv, "turtlebot_controller"); ros::NodeHandle n; ros::ServiceClient client1 = n.serviceClient<turtlesim::Kill>("/kill"); ros::ServiceClient client2 = n.serviceClient<turtlesim::Spawn>("/spawn"); ros::ServiceClient client3 = n.serviceClient<std_srvs::Empty>("/clear"); ros::ServiceClient client4 = n.serviceClient<turtlesim::TeleportAbsolute>("/rt_turtle/teleport_absolute"); client5 = n.serviceClient<my_srv::Harmonic>("/harmonic"); turtlesim::Kill srv1; srv1.request.name = "turtle1"; client1.call(srv1); turtlesim::Spawn srv2; srv2.request.x=5.0; srv2.request.y=5.0; srv2.request.theta=0.0; srv2.request.name="rt_turtle"; client2.call(srv2); std_srvs::Empty srv3; turtlesim::TeleportAbsolute srv4; srv4.request.x=2.0; srv4.request.y=1.0; srv4.request.theta=0.0; client4.call(srv4); sleep(1); client3.call(srv3); sleep(1); ros::Subscriber pose_sub = n.subscribe("/rt_turtle/pose", 1000, subscriberCallback); chatter_pub = n.advertise<geometry_msgs::Twist>("/rt_turtle/cmd_vel", 1000); ros::spin(); return 0; }
[ "carmine.recchiuto@dibris.unige.it" ]
carmine.recchiuto@dibris.unige.it
e8fef71201d2dc388426ff09efc2d290d813c2ed
a8e25eb06f17e80e60213e304b092c47928b7a6f
/main.cpp
bf94231779b4d6ffef74ebf791c248deeb53f541
[]
no_license
AliRn76/N-Queens
d85b9ed0fcf19a360ee93d35b07f7aa2a3ab7430
ddd56d380b9a8ca632b9d9e55d48280f4c05043a
refs/heads/master
2020-05-24T17:47:01.342363
2019-05-18T18:59:17
2019-05-18T18:59:17
187,394,981
2
0
null
null
null
null
UTF-8
C++
false
false
1,166
cpp
#include <iostream> #include <windows.h> #define N 6 using namespace std; int board[N][N]; void printBoard(){ system("cls"); for(int i=0 ; i<N ; i++){ for(int j=0 ; j<N ; j++){ cout<<board[i][j]<<" "; } cout<<"\n"; } } bool isSafe(int row, int col){ int i , j; for(i=0 ; i<row ; i++){ if(board[i][col]) return false; } for(i=row , j=col ; i>=0 && j>=0 ; i-- , j--){ if(board[i][j]) return false; } for(i=row , j=col ; i>=0 && j<N ; i-- , j++){ if(board[i][j]) return false; } return true; } bool letsPlay(int row){ if(row >= N){ return true; } for(int col = 0; col<N ; col++){ if(isSafe(row, col)){ board[row][col] = 1; // printBoard(); // cin.get(); if(letsPlay(row+1)){ return true; } } board[row][col] = 0; } return false; } void start(){ if(letsPlay(0)){ printBoard(); }else{ cout<<"there is no solution"<<endl; } } int main(){ start(); cin.get(); return 0; }
[ "alirn76@yahoo.com" ]
alirn76@yahoo.com
50b609d3a94d423ae15cdbe95e1bc16db49db9f2
e2f3148365870b414b1f958e51a47e9b2dd9f28f
/liblgcodec/codec/audio/aac/au_packetizer.h
3d32e8a827d494cb391f58c4f3b49db43c97b95c
[]
no_license
vkurbatov/mcu_remake
2987d780a51fb155b702790b7cf586b964a95105
5e8be35f00e43568dd4ca0261dc5fec5deeb4e54
refs/heads/master
2021-06-24T07:09:10.160934
2020-12-07T11:43:40
2020-12-07T11:43:40
170,029,545
0
0
null
null
null
null
UTF-8
C++
false
false
1,233
h
#ifndef AU_PACKETIZER_H #define AU_PACKETIZER_H #include "codec/audio/aac/au_types.h" #include <queue> #include <vector> namespace largo { namespace codec { namespace audio { class AuPacketizer { public: using frame_t = std::vector<std::uint8_t>; using queue_t = std::queue<frame_t>; private: au_header_rules_t m_au_header_rules; queue_t m_frame_queue; public: AuPacketizer(const au_header_rules_t& au_header_rules = default_au_header_rules); std::size_t PushFrame(const void* frame, std::size_t size); std::size_t PopFrame(void* frame = nullptr, std::size_t size = 0); bool DropFrame(); std::size_t PushPacket(const void* packet, std::size_t size); std::size_t PopPacket(void* packet, std::size_t size); std::size_t GetNeedPacketSize(std::size_t frame_size, std::size_t frame_count = 1) const; std::size_t GetNeedFrameSize(std::size_t packet_size, std::size_t frame_count = 1) const; std::size_t Count() const; void SetRules(const au_header_rules_t& au_header_config); const au_header_rules_t& GetRules() const; std::size_t Clear(); private: std::size_t get_need_size(std::size_t size, bool is_packet ,std::size_t frames = 1) const; }; } // audio } // codec } // largo #endif // AU_PACKET_H
[ "kurbatovvv82@mail.ru" ]
kurbatovvv82@mail.ru
72444b02072e97fea240e86d2979412516072701
43593c4f3107aa90224583d41bbd3e390f29a16e
/probe/main.cpp
4ff70ca4e94b1da2fb4be4973bd66d7af01fdea4
[]
no_license
TuMePJlaH/EiveNeuralNetwork
31eaa95acc88576ad82f7026f531d50c17a039bb
4b2d8510f0120d7ff72506662b15400b729dd9ae
refs/heads/master
2021-01-13T07:00:19.085806
2017-02-09T09:18:06
2017-02-09T09:18:06
81,428,771
0
0
null
null
null
null
UTF-8
C++
false
false
9,207
cpp
#include <iostream> #include <fstream> #include <cmath> #include <cstdlib> #include <vector> #include <cstring> #include <iomanip> #include "eive_neuron_network.h" int main(int argc, char **argv) { //Создаём нейронную сеть из шести слоёв //Размер входных данных 28х28 //1 - свёрточный с 6 ядрами, размер ядра 5х5 //2 - субдискретизирующий, размер ядра 2х2 //3 - свёрточный с 50 ядрами, размер ядра 5х5 //4 - субдискретизирующий, размер ядра 2х2 //5 - полносвязный со 100 нейронами //6 - полносвязный с 10 нейронами //На всех слоях тангенсальная функция активации EiveNeuronNetwork _net; _net.setInDataW(28); _net.setInDataH(28); _net.setNLayer(6); _net.createNetwork(); _net.createCNNLayer(0, 6, 5, FT_TANH); _net.createMPLayer(1, 2); _net.createCNNLayer(2, 50, 5, FT_TANH); _net.createMPLayer(3, 2); _net.createFCLayer(4, 100, FT_TANH); _net.createFCLayer(5, 10, FT_TANH); /*float *ADJ = new float [_net.getCNNLayerAdjS(2)]; for(int i = 0; i < _net.getCNNLayerAdjS(2); i++) ADJ[i] = 1; _net.setAdjM(2,ADJ); delete ADJ;//*/ _net.setSpeedTeach(0.001); //ОБУЧЕНИЕ int iterations = 10000; //количество итерация обучения int iterCounter = 0; if(argc == 2) { iterations = atoi(argv[1]); } //проверяем, нет ли уже обученной сити, на таком количестве итераций char *filename = new char [256]; std::ifstream nnFile; sprintf(filename, "it%d.enn", iterations); if(_net.loadFromFile(filename) < 0) { //если файл не найден, приступаем к обучению //открываем файлы для обучения std::ifstream fileImages, fileLabels; fileImages.open("train-images-idx3-ubyte", std::ios::binary); if(!fileImages.good()) { std::cout << "!!!train-images-idx3-ubyte file not found, please run get_mnist.sh script!" << std::endl; return -1; } fileLabels.open("train-labels-idx1-ubyte", std::ios::binary); if(!fileLabels.good()) { std::cout << "!!!train-labels.idx1-ubyte file not found, please run get_mnist.sh script!" << std::endl; return -1; } int magicNumber1 = 0; int magicNumber2 = 0; int numberOfImages = 0; int numberOfLabels = 0; int numberOfRows = 0; int numberOfColums = 0; int imSize; unsigned char readBuff[4] = {0}; fileImages.read((char*)readBuff, 4); for(int i = 0; i < 4; i++) { magicNumber1 += readBuff[i]*pow((float)256, 3-i); } fileLabels.read((char*)readBuff, 4); for(int i = 0; i < 4; i++) { magicNumber2 += readBuff[i]*pow((float)256, 3-i); } fileImages.read((char*)readBuff, 4); for(int i = 0; i < 4; i++) { numberOfImages += readBuff[i]*pow((float)256, 3-i); } fileLabels.read((char*)readBuff, 4); for(int i = 0; i < 4; i++) { numberOfLabels += readBuff[i]*pow((float)256, 3-i); } fileImages.read((char*)readBuff, 4); for(int i = 0; i < 4; i++) { numberOfRows += readBuff[i]*pow((float)256, 3-i); } fileImages.read((char*)readBuff, 4); for(int i = 0; i < 4; i++) { numberOfColums += readBuff[i]*pow((float)256, 3-i); } imSize = numberOfRows*numberOfColums; unsigned char *images = new unsigned char [numberOfImages*imSize]; float *imagesF = new float [numberOfImages*imSize]; unsigned char *labels = new unsigned char [numberOfLabels]; fileImages.read((char*)images, numberOfImages*imSize); fileLabels.read((char*)labels, numberOfLabels); fileImages.close(); fileLabels.close(); for(int i = 0; i < numberOfImages*imSize; i++) { imagesF[i] = (float)images[i]; } int nImage = 0; float maxErr = 0.01; float *d = new float[_net.getOutDataSize()]; float *rezD = new float[_net.getOutDataSize()]; float *rez = new float[_net.getOutDataSize()]; //генерация случайной последовательности изображений std::vector<int> randomImagesNumber(numberOfImages); std::vector<int> objectImages; for(int i = 0; i < numberOfImages; i++) { objectImages.emplace_back(i); } for(int i = 0; i < numberOfImages; i++) { int n = rand()%(numberOfImages-i); randomImagesNumber[i] = objectImages[n]; objectImages.erase(objectImages.begin() + n); } //приступаем к обучению с заданным количеством итераций while(iterations) { memset(d, 0, sizeof(float)*_net.getOutDataSize()); float err = 0; //выставляем единицу на выходном нейроне, в зависимости от лейбла данного изображения d[labels[randomImagesNumber[nImage]]] = 1; _net.teachNetwork(imagesF + randomImagesNumber[nImage]*imSize, d, maxErr, &err); //сортируем для вывода int D = labels[randomImagesNumber[nImage]]; _net.getOutData(rezD); memset(rez, 0, sizeof(float)*_net.getOutDataSize()); for(int i = 0; i < _net.getOutDataSize(); i++) { double max = -2; int V = 0; for(int j = 0; j < _net.getOutDataSize(); j++) { if(rezD[j] > max) { max = rezD[j]; V = j; } } rezD[V] = -2; rez[i] = V; } std::cout << std::setw(10) << iterCounter++ << '(' << std::setw(6) << randomImagesNumber[nImage] << ") " << err << "\t\t" << "D:" << D << '\t' << "R:"; for(int i = 0; i < 10; i++) { std::cout << rez[i] << ' '; } std::cout << std::endl; nImage++; //если прошли по всем 60000 изображений, перемешиваем их заново if(nImage == numberOfImages) { nImage = 0; for(int i = 0; i < numberOfImages; i++) { objectImages.emplace_back(i); } for(int i = 0; i < numberOfImages; i++) { int n = rand()%(numberOfImages-i); randomImagesNumber[i] = objectImages[n]; objectImages.erase(objectImages.begin() + n); } } iterations--; } delete[] d; delete[] rezD; delete[] rez; _net.saveToFile(filename); } //ПРОВЕРКА //открываем файлы для проверки std::ifstream fileImages, fileLabels; fileImages.open("t10k-images-idx3-ubyte", std::ios::binary); if(!fileImages.good()) { std::cout << "!!!t10k-images-idx3-ubyte file not found, please run get_mnist.sh script!" << std::endl; return -1; } fileLabels.open("t10k-labels-idx1-ubyte", std::ios::binary); if(!fileLabels.good()) { std::cout << "!!!t10k-labels-idx1-ubyte file not found, please run get_mnist.sh script!" << std::endl; return -1; } int magicNumber1 = 0; int magicNumber2 = 0; int numberOfImages = 0; int numberOfLabels = 0; int numberOfRows = 0; int numberOfColums = 0; int imSize; unsigned char readBuff[4] = {0}; fileImages.read((char*)readBuff, 4); for(int i = 0; i < 4; i++) { magicNumber1 += readBuff[i]*pow((float)256, 3-i); } fileLabels.read((char*)readBuff, 4); for(int i = 0; i < 4; i++) { magicNumber2 += readBuff[i]*pow((float)256, 3-i); } fileImages.read((char*)readBuff, 4); for(int i = 0; i < 4; i++) { numberOfImages += readBuff[i]*pow((float)256, 3-i); } fileLabels.read((char*)readBuff, 4); for(int i = 0; i < 4; i++) { numberOfLabels += readBuff[i]*pow((float)256, 3-i); } fileImages.read((char*)readBuff, 4); for(int i = 0; i < 4; i++) { numberOfRows += readBuff[i]*pow((float)256, 3-i); } fileImages.read((char*)readBuff, 4); for(int i = 0; i < 4; i++) { numberOfColums += readBuff[i]*pow((float)256, 3-i); } imSize = numberOfRows*numberOfColums; unsigned char *images = new unsigned char [numberOfImages*imSize]; float *imagesF = new float [numberOfImages*imSize]; unsigned char *labels = new unsigned char [numberOfLabels]; fileImages.read((char*)images, numberOfImages*imSize); fileLabels.read((char*)labels, numberOfLabels); fileImages.close(); fileLabels.close(); for(int i = 0; i < numberOfImages*imSize; i++) { imagesF[i] = (float)images[i]; } float *outData = new float[_net.getOutDataSize()]; int err = 0; std::cout << "Testing..." << std::endl; for(int i = 0; i < numberOfImages; i++) { _net.colculateNetwork(imagesF + i*imSize); _net.getOutData(outData); float max = -2; int maxN = -1; for(int j = 0; j < _net.getOutDataSize(); j++) { if(outData[j] > max) { max = outData[j]; maxN = j; } } if(maxN != labels[i]) { err++; } } std::cout << std::endl; delete[] outData; std::cout << "Bad recognition = " << err << std::endl; std::cout << "Error percent = " << (float)err/(float)numberOfImages << "%" << std::endl; return 0; }
[ "Sadovskov.K@gmail.com" ]
Sadovskov.K@gmail.com
1b6d795e2c8054cfc3e09427b9416ea9e3725340
ad74f7a42e8dec14ec7576252fcbc3fc46679f27
/SupernodeDistributer/RacksSupernodesPage.cpp
789a8c0456a4fbe448e2b1b6616fc497442290c7
[]
no_license
radtek/TrapperKeeper
56fed7afa259aee20d6d81e71e19786f2f0d9418
63f87606ae02e7c29608fedfdf8b7e65339b8e9a
refs/heads/master
2020-05-29T16:49:29.708375
2013-05-15T08:33:23
2013-05-15T08:33:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,488
cpp
// RacksSupernodesPage.cpp : implementation file // #include "stdafx.h" #include "RacksSupernodesPage.h" #include "SupernodeDistributerDll.h" // CRacksSupernodesPage dialog IMPLEMENT_DYNAMIC(CRacksSupernodesPage, CPropertyPage) CRacksSupernodesPage::CRacksSupernodesPage() : CPropertyPage(CRacksSupernodesPage::IDD) { } CRacksSupernodesPage::~CRacksSupernodesPage() { } void CRacksSupernodesPage::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); DDX_Control(pDX, IDC_RACK_LIST, m_rack_list); DDX_Control(pDX, IDC_SUPERNODE_LIST, m_supernode_list); } BEGIN_MESSAGE_MAP(CRacksSupernodesPage, CPropertyPage) ON_WM_SIZE() ON_NOTIFY(NM_CLICK, IDC_RACK_LIST, OnNMClickRackList) // ON_MESSAGE(WM_DONE_EDITING, OnDoneEditing) ON_NOTIFY(NM_RCLICK, IDC_RACK_LIST, OnNMRclickRackList) ON_NOTIFY(LVN_KEYDOWN, IDC_RACK_LIST, OnLvnKeydownRackList) END_MESSAGE_MAP() // CRacksSupernodesPage message handlers BOOL CRacksSupernodesPage::OnInitDialog() { CPropertyPage::OnInitDialog(); //ShowWindow(SW_NORMAL); m_rack_list.m_parent_hwnd = GetSafeHwnd(); CRect main_rect,list_rect; GetWindowRect(&main_rect); GetDlgItem(IDC_RACK_LIST)->GetWindowRect(&list_rect); m_border=list_rect.left-main_rect.left; m_bottom=main_rect.bottom - list_rect.bottom; m_rack_list.SetExtendedStyle(m_rack_list.GetExtendedStyle() | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES); m_rack_list.InsertColumn(SUB_RACK_NAME,"Rack Name",LVCFMT_LEFT,100); // m_rack_list.InsertColumn(SUB_NUM_KAZAA,"Number of Kazaa",LVCFMT_LEFT,100); m_supernode_list.SetExtendedStyle(m_supernode_list.GetExtendedStyle() | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES); m_supernode_list.InsertColumn(0,"Supernode's IP",LVCFMT_LEFT,200); m_supernode_list.InsertColumn(1,"Port",LVCFMT_LEFT,50); m_supernode_list.InsertColumn(2,"Up Time",LVCFMT_LEFT,150); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } // // // void CRacksSupernodesPage::OnSize(UINT nType, int cx, int cy) { CPropertyPage::OnSize(nType, cx, cy); ResizePage(); } // // // void CRacksSupernodesPage::InitParent(SupernodeDistributerDll* parent) { p_parent = parent; } // // // void CRacksSupernodesPage::ResizePage(void) { if(IsWindowVisible()) { CRect main_rect,list1_rect,list2_rect; GetWindowRect(&main_rect); GetDlgItem(IDC_RACK_LIST)->GetWindowRect(&list1_rect); GetDlgItem(IDC_SUPERNODE_LIST)->GetWindowRect(&list2_rect); list1_rect.bottom=main_rect.bottom-m_border-m_bottom; list1_rect.right=((main_rect.right-main_rect.left)/3)+list1_rect.left-m_border; list2_rect.bottom=main_rect.bottom-m_border-m_bottom; list2_rect.left=list1_rect.right+m_border; list2_rect.right=main_rect.right-m_border; ScreenToClient(&list1_rect); ScreenToClient(&list2_rect); GetDlgItem(IDC_RACK_LIST)->MoveWindow(&list1_rect); GetDlgItem(IDC_SUPERNODE_LIST)->MoveWindow(&list2_rect); } } // // // BOOL CRacksSupernodesPage::OnSetActive() { CRect main_rect,list1_rect,list2_rect; GetWindowRect(&main_rect); GetDlgItem(IDC_RACK_LIST)->GetWindowRect(&list1_rect); GetDlgItem(IDC_SUPERNODE_LIST)->GetWindowRect(&list2_rect); list1_rect.bottom=main_rect.bottom-m_border-m_bottom; list1_rect.right=((main_rect.right-main_rect.left)/3)+list1_rect.left-m_border; list2_rect.bottom=main_rect.bottom-m_border-m_bottom; list2_rect.left=list1_rect.right+m_border; list2_rect.right=main_rect.right-m_border; ScreenToClient(&list1_rect); ScreenToClient(&list2_rect); GetDlgItem(IDC_RACK_LIST)->MoveWindow(&list1_rect); GetDlgItem(IDC_SUPERNODE_LIST)->MoveWindow(&list2_rect); return CPropertyPage::OnSetActive(); } // // // void CRacksSupernodesPage::OnNMClickRackList(NMHDR *pNMHDR, LRESULT *pResult) { //check if the user select any item UINT selected = m_rack_list.GetSelectedCount(); UINT kazaa_running = 0; if(selected > 0) { POSITION pos = m_rack_list.GetFirstSelectedItemPosition(); int index = m_rack_list.GetNextSelectedItem(pos); string rack_name = m_rack_list.GetItemText(index, 0); vector<IPAndPort> supernodes = p_parent->GetSupernodesFromRackList(rack_name, kazaa_running); //fill up the supernodes list m_supernode_list.DeleteAllItems(); for(unsigned int i=0; i<supernodes.size(); i++) { char ip[16+1]; char port[8]; itoa(supernodes[i].m_port, port, 10); GetIPStringFromInterger(supernodes[i].m_ip, ip); int inserted = m_supernode_list.InsertItem(m_supernode_list.GetItemCount(),ip); m_supernode_list.SetItemText(inserted, 1, port); CString up_time = (CTime::GetCurrentTime() - supernodes[i].m_up_since).Format("%D days - %H:%M:%S"); m_supernode_list.SetItemText(inserted, 2, up_time); } } char msg[32]; sprintf(msg, "Number of Supernodes: %d", m_supernode_list.GetItemCount()); GetDlgItem(IDC_SUPERNODE_NUM)->SetWindowText(msg); sprintf(msg, "Number of Kazaa: %u", kazaa_running); GetDlgItem(IDC_KAZAA_NUM)->SetWindowText(msg); *pResult = 0; } // // // void CRacksSupernodesPage::GetIPStringFromInterger(int ip_int, char* ip) { sprintf(ip, "%u.%u.%u.%u",(ip_int>>0)&0xFF,(ip_int>>8)&0xFF,(ip_int>>16)&0xFF,(ip_int>>24)&0xFF); } // // // void CRacksSupernodesPage::AddRack(RackSuperNodes& rack) { int index = m_rack_list.InsertItem(m_rack_list.GetItemCount(),rack.m_rack_name.c_str()); /* char num[4]; sprintf(num, "%d", rack.m_num_kazaa); m_rack_list.SetItemText(index, SUB_NUM_KAZAA, num); */ char msg[32]; sprintf(msg, "Number of Racks: %d", m_rack_list.GetItemCount()); GetDlgItem(IDC_RACKS_NUM)->SetWindowText(msg); } // // // //done editing kazaa number field /* LRESULT CRacksSupernodesPage::OnDoneEditing(WPARAM wparam,LPARAM lparam) { char numbers[8]; char rack_name[32]; int num; m_rack_list.GetItemText((int)wparam,(int)lparam,numbers,8); m_rack_list.GetItemText((int)wparam,SUB_RACK_NAME,rack_name,32); num = atoi(numbers); p_parent->OnEditKazaaNumber(rack_name, num); return 0; } */ // // // void CRacksSupernodesPage::OnNMRclickRackList(NMHDR *pNMHDR, LRESULT *pResult) { if(m_rack_list.GetSelectedCount()>0) { POINT point; GetCursorPos(&point); CMenu menu; menu.CreatePopupMenu(); menu.AppendMenu(MF_STRING,WM_STOP_KAZAA,"Stop Launching and Kill All Kazaa"); menu.AppendMenu(MF_STRING,WM_RESUME_KAZAA,"Resume Launching Kazaa"); menu.AppendMenu(MF_STRING,WM_RESTART_KAZAA,"Restart All Kazaa"); menu.AppendMenu(MF_STRING,WM_REFRESH_KAZAA_LIST,"Retrieve Remote Supernodes"); menu.TrackPopupMenu(TPM_LEFTALIGN,point.x,point.y,this,0); } *pResult = 0; } // // // BOOL CRacksSupernodesPage::OnCommand(WPARAM wParam, LPARAM lParam) { // Check for right-click popup menu items if(wParam>WM_USER_MENU) { switch(wParam) { case WM_STOP_KAZAA: { OnStopAndKillKazaa(); break; } case WM_RESUME_KAZAA: { OnResumeKazaa(); break; } case WM_RESTART_KAZAA: { OnRestartKazaa(); break; } case WM_REFRESH_KAZAA_LIST: { OnGetRemoteSupernodes(); break; } } } return CDialog::OnCommand(wParam,lParam); return CPropertyPage::OnCommand(wParam, lParam); } // // // void CRacksSupernodesPage::OnStopAndKillKazaa() { //erase current supernode list on the dialog m_supernode_list.DeleteAllItems(); vector<CString> selected_racks; CString rack_name; if(m_rack_list.GetSelectedCount()>0) { POSITION pos = m_rack_list.GetFirstSelectedItemPosition(); if(pos != NULL) { while(pos) { int nItem = m_rack_list.GetNextSelectedItem(pos); rack_name = m_rack_list.GetItemText(nItem,SUB_RACK_NAME); selected_racks.push_back(rack_name); } } p_parent->OnStopAndKillKazaa(selected_racks); } } // // // void CRacksSupernodesPage::OnResumeKazaa() { vector<CString> selected_racks; CString rack_name; if(m_rack_list.GetSelectedCount()>0) { POSITION pos = m_rack_list.GetFirstSelectedItemPosition(); if(pos != NULL) { while(pos) { int nItem = m_rack_list.GetNextSelectedItem(pos); rack_name = m_rack_list.GetItemText(nItem,SUB_RACK_NAME); selected_racks.push_back(rack_name); } } p_parent->OnResumeKazaa(selected_racks); } } // // // void CRacksSupernodesPage::OnRestartKazaa() { //erase current supernode list on the dialog m_supernode_list.DeleteAllItems(); vector<CString> selected_racks; CString rack_name; if(m_rack_list.GetSelectedCount()>0) { POSITION pos = m_rack_list.GetFirstSelectedItemPosition(); if(pos != NULL) { while(pos) { int nItem = m_rack_list.GetNextSelectedItem(pos); rack_name = m_rack_list.GetItemText(nItem,SUB_RACK_NAME); selected_racks.push_back(rack_name); } } p_parent->OnRestartKazaa(selected_racks); } } // // // void CRacksSupernodesPage::OnGetRemoteSupernodes() { vector<CString> selected_racks; CString rack_name; if(m_rack_list.GetSelectedCount()>0) { POSITION pos = m_rack_list.GetFirstSelectedItemPosition(); if(pos != NULL) { while(pos) { int nItem = m_rack_list.GetNextSelectedItem(pos); rack_name = m_rack_list.GetItemText(nItem,SUB_RACK_NAME); selected_racks.push_back(rack_name); } } p_parent->OnGetRemoteSupernodes(selected_racks); } } /* // // // void CRacksSupernodesPage::UpdateRackMaxKazaaNum(RackSuperNodes& rack) { int count = m_rack_list.GetItemCount(); for(int i=0; i<count; i++) { CString rack_name = m_rack_list.GetItemText(i, SUB_RACK_NAME); if(strcmp(rack.m_rack_name.c_str(), rack_name)==0) { char num[8]; sprintf(num, "%d", rack.m_num_kazaa); m_rack_list.SetItemText(i, SUB_NUM_KAZAA, num); break; } } } */ // // // void CRacksSupernodesPage::OnLvnKeydownRackList(NMHDR *pNMHDR, LRESULT *pResult) { LPNMLVKEYDOWN pLVKeyDow = reinterpret_cast<LPNMLVKEYDOWN>(pNMHDR); switch(pLVKeyDow->wVKey) { case VK_UP: { //check if the user select any item UINT selected = m_rack_list.GetSelectedCount(); UINT kazaa_running = 0; if(selected > 0) { POSITION pos = m_rack_list.GetFirstSelectedItemPosition(); int index = m_rack_list.GetNextSelectedItem(pos); index--; if(index < 0) index = 0; string rack_name = m_rack_list.GetItemText(index, 0); vector<IPAndPort> supernodes = p_parent->GetSupernodesFromRackList(rack_name, kazaa_running); //fill up the supernodes list m_supernode_list.DeleteAllItems(); for(unsigned int i=0; i<supernodes.size(); i++) { char ip[16+1]; char port[8]; itoa(supernodes[i].m_port, port, 10); GetIPStringFromInterger(supernodes[i].m_ip, ip); int inserted = m_supernode_list.InsertItem(m_supernode_list.GetItemCount(),ip); m_supernode_list.SetItemText(inserted, 1, port); CString up_time = (CTime::GetCurrentTime() - supernodes[i].m_up_since).Format("%D days - %H:%M:%S"); m_supernode_list.SetItemText(inserted, 2, up_time); } } char msg[32]; sprintf(msg, "Number of Supernodes: %d", m_supernode_list.GetItemCount()); GetDlgItem(IDC_SUPERNODE_NUM)->SetWindowText(msg); sprintf(msg, "Number of Kazaa: %u", kazaa_running); GetDlgItem(IDC_KAZAA_NUM)->SetWindowText(msg); break; } case VK_DOWN: { //check if the user select any item UINT selected = m_rack_list.GetSelectedCount(); UINT kazaa_running = 0; if(selected > 0) { POSITION pos = m_rack_list.GetFirstSelectedItemPosition(); int index = m_rack_list.GetNextSelectedItem(pos); index++; if(index >= m_rack_list.GetItemCount()) index = m_rack_list.GetItemCount()-1; string rack_name = m_rack_list.GetItemText(index, 0); vector<IPAndPort> supernodes = p_parent->GetSupernodesFromRackList(rack_name, kazaa_running); //fill up the supernodes list m_supernode_list.DeleteAllItems(); for(unsigned int i=0; i<supernodes.size(); i++) { char ip[16+1]; char port[8]; itoa(supernodes[i].m_port, port, 10); GetIPStringFromInterger(supernodes[i].m_ip, ip); int inserted = m_supernode_list.InsertItem(m_supernode_list.GetItemCount(),ip); m_supernode_list.SetItemText(inserted, 1, port); CString up_time = (CTime::GetCurrentTime() - supernodes[i].m_up_since).Format("%D days - %H:%M:%S"); m_supernode_list.SetItemText(inserted, 2, up_time); } } char msg[32]; sprintf(msg, "Number of Supernodes: %d", m_supernode_list.GetItemCount()); GetDlgItem(IDC_SUPERNODE_NUM)->SetWindowText(msg); sprintf(msg, "Number of Kazaa: %u", kazaa_running); GetDlgItem(IDC_KAZAA_NUM)->SetWindowText(msg); break; } } *pResult = 0; }
[ "occupymyday@gmail.com" ]
occupymyday@gmail.com
fbcb86ca7b200c532970f437f2ca19ded4b856d5
1f336fe2640e5b3512d8212c0b3865b568761c28
/c-tools/sTimer/sTimer.h
cd848419eacc8d3e26590278a0102b857455fe9d
[]
no_license
kniku/kuk-root
4b0968cae10826e5fe0e1c5024fd0c2900860954
117ad9f236c0a1edfea70b916ff861acbf2a9164
refs/heads/master
2023-03-03T05:59:40.972696
2023-02-23T09:23:02
2023-02-23T09:23:02
32,207,102
0
0
null
2022-12-22T16:49:19
2015-03-14T10:57:15
C
ISO-8859-1
C++
false
false
519
h
// sTimer.h : Hauptheaderdatei für die sTimer-Anwendung // #pragma once #ifndef __AFXWIN_H__ #error 'stdafx.h' muss vor dieser Datei in PCH eingeschlossen werden. #endif #include "resource.h" // Hauptsymbole // CsTimerApp: // Siehe sTimer.cpp für die Implementierung dieser Klasse // class CsTimerApp : public CWinApp { public: CsTimerApp(); // Überschreibungen public: virtual BOOL InitInstance(); // Implementierung DECLARE_MESSAGE_MAP() }; extern CsTimerApp theApp;
[ "kniku@users.noreply.github.com" ]
kniku@users.noreply.github.com
1faa2046a16a2e98b2b8c391415ec1a3efb68130
0c18c776835e51c1b0b1198e0a5370c84aaf8e83
/src/peefycpp/papi.cpp
9a9b088df27fa7e2549766ac1d9fc2446387948c
[ "Apache-2.0" ]
permissive
Peefy/PeefyCompiler
f769459b0f698403b0538fd46e46a340af0882ae
b54252ad43e8ff7be10f97bda3196137936ba4b6
refs/heads/master
2020-09-07T00:35:32.136797
2020-05-06T08:22:43
2020-05-06T08:22:43
220,604,030
1
0
null
null
null
null
UTF-8
C++
false
false
65
cpp
#include "papi.h" PEEFY_API int peefy_init() { return 0; }
[ "xpf6677@163.com" ]
xpf6677@163.com
49dff4daed44a3b450a73045130901975c06f100
a126a743e5f75da83421b79e37bada38574a1e77
/Plugins/PlayFabSDK/Source/PlayFabCpp/Private/Core/PlayFabServerDataModels.cpp
a4dc9b642e0ff51477c94fd30e20904978f323aa
[]
no_license
Unfound124/TimenoxMobile
253107901843cea5ec182e101f594d81b10a10e4
5412b134cf7880afb068f3de85f8fbe32606a901
refs/heads/master
2022-04-03T13:47:25.104564
2020-02-14T01:38:59
2020-02-14T01:38:59
212,334,677
1
0
null
null
null
null
UTF-8
C++
false
false
546,090
cpp
////////////////////////////////////////////////////// // Copyright (C) Microsoft. 2018. All rights reserved. ////////////////////////////////////////////////////// // This is automatically generated by PlayFab SDKGenerator. DO NOT modify this manually! #include "Core/PlayFabServerDataModels.h" #include "Core/PlayFabJsonHelpers.h" using namespace PlayFab; using namespace PlayFab::ServerModels; PlayFab::ServerModels::FAdCampaignAttribution::~FAdCampaignAttribution() { } void PlayFab::ServerModels::FAdCampaignAttribution::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("AttributedAt")); writeDatetime(AttributedAt, writer); if (CampaignId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CampaignId")); writer->WriteValue(CampaignId); } if (Platform.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Platform")); writer->WriteValue(Platform); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAdCampaignAttribution::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AttributedAtValue = obj->TryGetField(TEXT("AttributedAt")); if (AttributedAtValue.IsValid()) AttributedAt = readDatetime(AttributedAtValue); const TSharedPtr<FJsonValue> CampaignIdValue = obj->TryGetField(TEXT("CampaignId")); if (CampaignIdValue.IsValid() && !CampaignIdValue->IsNull()) { FString TmpValue; if (CampaignIdValue->TryGetString(TmpValue)) { CampaignId = TmpValue; } } const TSharedPtr<FJsonValue> PlatformValue = obj->TryGetField(TEXT("Platform")); if (PlatformValue.IsValid() && !PlatformValue->IsNull()) { FString TmpValue; if (PlatformValue->TryGetString(TmpValue)) { Platform = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FAdCampaignAttributionModel::~FAdCampaignAttributionModel() { } void PlayFab::ServerModels::FAdCampaignAttributionModel::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("AttributedAt")); writeDatetime(AttributedAt, writer); if (CampaignId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CampaignId")); writer->WriteValue(CampaignId); } if (Platform.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Platform")); writer->WriteValue(Platform); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAdCampaignAttributionModel::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AttributedAtValue = obj->TryGetField(TEXT("AttributedAt")); if (AttributedAtValue.IsValid()) AttributedAt = readDatetime(AttributedAtValue); const TSharedPtr<FJsonValue> CampaignIdValue = obj->TryGetField(TEXT("CampaignId")); if (CampaignIdValue.IsValid() && !CampaignIdValue->IsNull()) { FString TmpValue; if (CampaignIdValue->TryGetString(TmpValue)) { CampaignId = TmpValue; } } const TSharedPtr<FJsonValue> PlatformValue = obj->TryGetField(TEXT("Platform")); if (PlatformValue.IsValid() && !PlatformValue->IsNull()) { FString TmpValue; if (PlatformValue->TryGetString(TmpValue)) { Platform = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FAddCharacterVirtualCurrencyRequest::~FAddCharacterVirtualCurrencyRequest() { } void PlayFab::ServerModels::FAddCharacterVirtualCurrencyRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Amount")); writer->WriteValue(Amount); writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("VirtualCurrency")); writer->WriteValue(VirtualCurrency); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAddCharacterVirtualCurrencyRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AmountValue = obj->TryGetField(TEXT("Amount")); if (AmountValue.IsValid() && !AmountValue->IsNull()) { int32 TmpValue; if (AmountValue->TryGetNumber(TmpValue)) { Amount = TmpValue; } } const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> VirtualCurrencyValue = obj->TryGetField(TEXT("VirtualCurrency")); if (VirtualCurrencyValue.IsValid() && !VirtualCurrencyValue->IsNull()) { FString TmpValue; if (VirtualCurrencyValue->TryGetString(TmpValue)) { VirtualCurrency = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FAddFriendRequest::~FAddFriendRequest() { } void PlayFab::ServerModels::FAddFriendRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (FriendEmail.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("FriendEmail")); writer->WriteValue(FriendEmail); } if (FriendPlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("FriendPlayFabId")); writer->WriteValue(FriendPlayFabId); } if (FriendTitleDisplayName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("FriendTitleDisplayName")); writer->WriteValue(FriendTitleDisplayName); } if (FriendUsername.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("FriendUsername")); writer->WriteValue(FriendUsername); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAddFriendRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> FriendEmailValue = obj->TryGetField(TEXT("FriendEmail")); if (FriendEmailValue.IsValid() && !FriendEmailValue->IsNull()) { FString TmpValue; if (FriendEmailValue->TryGetString(TmpValue)) { FriendEmail = TmpValue; } } const TSharedPtr<FJsonValue> FriendPlayFabIdValue = obj->TryGetField(TEXT("FriendPlayFabId")); if (FriendPlayFabIdValue.IsValid() && !FriendPlayFabIdValue->IsNull()) { FString TmpValue; if (FriendPlayFabIdValue->TryGetString(TmpValue)) { FriendPlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> FriendTitleDisplayNameValue = obj->TryGetField(TEXT("FriendTitleDisplayName")); if (FriendTitleDisplayNameValue.IsValid() && !FriendTitleDisplayNameValue->IsNull()) { FString TmpValue; if (FriendTitleDisplayNameValue->TryGetString(TmpValue)) { FriendTitleDisplayName = TmpValue; } } const TSharedPtr<FJsonValue> FriendUsernameValue = obj->TryGetField(TEXT("FriendUsername")); if (FriendUsernameValue.IsValid() && !FriendUsernameValue->IsNull()) { FString TmpValue; if (FriendUsernameValue->TryGetString(TmpValue)) { FriendUsername = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGenericServiceId::~FGenericServiceId() { } void PlayFab::ServerModels::FGenericServiceId::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("ServiceName")); writer->WriteValue(ServiceName); writer->WriteIdentifierPrefix(TEXT("UserId")); writer->WriteValue(UserId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGenericServiceId::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ServiceNameValue = obj->TryGetField(TEXT("ServiceName")); if (ServiceNameValue.IsValid() && !ServiceNameValue->IsNull()) { FString TmpValue; if (ServiceNameValue->TryGetString(TmpValue)) { ServiceName = TmpValue; } } const TSharedPtr<FJsonValue> UserIdValue = obj->TryGetField(TEXT("UserId")); if (UserIdValue.IsValid() && !UserIdValue->IsNull()) { FString TmpValue; if (UserIdValue->TryGetString(TmpValue)) { UserId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FAddGenericIDRequest::~FAddGenericIDRequest() { } void PlayFab::ServerModels::FAddGenericIDRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("GenericId")); GenericId.writeJSON(writer); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAddGenericIDRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> GenericIdValue = obj->TryGetField(TEXT("GenericId")); if (GenericIdValue.IsValid() && !GenericIdValue->IsNull()) { GenericId = FGenericServiceId(GenericIdValue->AsObject()); } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FAddPlayerTagRequest::~FAddPlayerTagRequest() { } void PlayFab::ServerModels::FAddPlayerTagRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("TagName")); writer->WriteValue(TagName); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAddPlayerTagRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> TagNameValue = obj->TryGetField(TEXT("TagName")); if (TagNameValue.IsValid() && !TagNameValue->IsNull()) { FString TmpValue; if (TagNameValue->TryGetString(TmpValue)) { TagName = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FAddPlayerTagResult::~FAddPlayerTagResult() { } void PlayFab::ServerModels::FAddPlayerTagResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAddPlayerTagResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FAddSharedGroupMembersRequest::~FAddSharedGroupMembersRequest() { } void PlayFab::ServerModels::FAddSharedGroupMembersRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteArrayStart(TEXT("PlayFabIds")); for (const FString& item : PlayFabIds) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteIdentifierPrefix(TEXT("SharedGroupId")); writer->WriteValue(SharedGroupId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAddSharedGroupMembersRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; HasSucceeded &= obj->TryGetStringArrayField(TEXT("PlayFabIds"), PlayFabIds); const TSharedPtr<FJsonValue> SharedGroupIdValue = obj->TryGetField(TEXT("SharedGroupId")); if (SharedGroupIdValue.IsValid() && !SharedGroupIdValue->IsNull()) { FString TmpValue; if (SharedGroupIdValue->TryGetString(TmpValue)) { SharedGroupId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FAddSharedGroupMembersResult::~FAddSharedGroupMembersResult() { } void PlayFab::ServerModels::FAddSharedGroupMembersResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAddSharedGroupMembersResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FAddUserVirtualCurrencyRequest::~FAddUserVirtualCurrencyRequest() { } void PlayFab::ServerModels::FAddUserVirtualCurrencyRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Amount")); writer->WriteValue(Amount); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("VirtualCurrency")); writer->WriteValue(VirtualCurrency); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAddUserVirtualCurrencyRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AmountValue = obj->TryGetField(TEXT("Amount")); if (AmountValue.IsValid() && !AmountValue->IsNull()) { int32 TmpValue; if (AmountValue->TryGetNumber(TmpValue)) { Amount = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> VirtualCurrencyValue = obj->TryGetField(TEXT("VirtualCurrency")); if (VirtualCurrencyValue.IsValid() && !VirtualCurrencyValue->IsNull()) { FString TmpValue; if (VirtualCurrencyValue->TryGetString(TmpValue)) { VirtualCurrency = TmpValue; } } return HasSucceeded; } void PlayFab::ServerModels::writePushNotificationPlatformEnumJSON(PushNotificationPlatform enumVal, JsonWriter& writer) { switch (enumVal) { case PushNotificationPlatformApplePushNotificationService: writer->WriteValue(TEXT("ApplePushNotificationService")); break; case PushNotificationPlatformGoogleCloudMessaging: writer->WriteValue(TEXT("GoogleCloudMessaging")); break; } } ServerModels::PushNotificationPlatform PlayFab::ServerModels::readPushNotificationPlatformFromValue(const TSharedPtr<FJsonValue>& value) { return readPushNotificationPlatformFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::PushNotificationPlatform PlayFab::ServerModels::readPushNotificationPlatformFromValue(const FString& value) { static TMap<FString, PushNotificationPlatform> _PushNotificationPlatformMap; if (_PushNotificationPlatformMap.Num() == 0) { // Auto-generate the map on the first use _PushNotificationPlatformMap.Add(TEXT("ApplePushNotificationService"), PushNotificationPlatformApplePushNotificationService); _PushNotificationPlatformMap.Add(TEXT("GoogleCloudMessaging"), PushNotificationPlatformGoogleCloudMessaging); } if (!value.IsEmpty()) { auto output = _PushNotificationPlatformMap.Find(value); if (output != nullptr) return *output; } return PushNotificationPlatformApplePushNotificationService; // Basically critical fail } PlayFab::ServerModels::FAdvancedPushPlatformMsg::~FAdvancedPushPlatformMsg() { } void PlayFab::ServerModels::FAdvancedPushPlatformMsg::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Json")); writer->WriteValue(Json); writer->WriteIdentifierPrefix(TEXT("Platform")); writePushNotificationPlatformEnumJSON(Platform, writer); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAdvancedPushPlatformMsg::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> JsonValue = obj->TryGetField(TEXT("Json")); if (JsonValue.IsValid() && !JsonValue->IsNull()) { FString TmpValue; if (JsonValue->TryGetString(TmpValue)) { Json = TmpValue; } } Platform = readPushNotificationPlatformFromValue(obj->TryGetField(TEXT("Platform"))); return HasSucceeded; } PlayFab::ServerModels::FAuthenticateSessionTicketRequest::~FAuthenticateSessionTicketRequest() { } void PlayFab::ServerModels::FAuthenticateSessionTicketRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("SessionTicket")); writer->WriteValue(SessionTicket); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAuthenticateSessionTicketRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> SessionTicketValue = obj->TryGetField(TEXT("SessionTicket")); if (SessionTicketValue.IsValid() && !SessionTicketValue->IsNull()) { FString TmpValue; if (SessionTicketValue->TryGetString(TmpValue)) { SessionTicket = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserAndroidDeviceInfo::~FUserAndroidDeviceInfo() { } void PlayFab::ServerModels::FUserAndroidDeviceInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (AndroidDeviceId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("AndroidDeviceId")); writer->WriteValue(AndroidDeviceId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserAndroidDeviceInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AndroidDeviceIdValue = obj->TryGetField(TEXT("AndroidDeviceId")); if (AndroidDeviceIdValue.IsValid() && !AndroidDeviceIdValue->IsNull()) { FString TmpValue; if (AndroidDeviceIdValue->TryGetString(TmpValue)) { AndroidDeviceId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserCustomIdInfo::~FUserCustomIdInfo() { } void PlayFab::ServerModels::FUserCustomIdInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CustomId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CustomId")); writer->WriteValue(CustomId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserCustomIdInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CustomIdValue = obj->TryGetField(TEXT("CustomId")); if (CustomIdValue.IsValid() && !CustomIdValue->IsNull()) { FString TmpValue; if (CustomIdValue->TryGetString(TmpValue)) { CustomId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserFacebookInfo::~FUserFacebookInfo() { } void PlayFab::ServerModels::FUserFacebookInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (FacebookId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("FacebookId")); writer->WriteValue(FacebookId); } if (FullName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("FullName")); writer->WriteValue(FullName); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserFacebookInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> FacebookIdValue = obj->TryGetField(TEXT("FacebookId")); if (FacebookIdValue.IsValid() && !FacebookIdValue->IsNull()) { FString TmpValue; if (FacebookIdValue->TryGetString(TmpValue)) { FacebookId = TmpValue; } } const TSharedPtr<FJsonValue> FullNameValue = obj->TryGetField(TEXT("FullName")); if (FullNameValue.IsValid() && !FullNameValue->IsNull()) { FString TmpValue; if (FullNameValue->TryGetString(TmpValue)) { FullName = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserFacebookInstantGamesIdInfo::~FUserFacebookInstantGamesIdInfo() { } void PlayFab::ServerModels::FUserFacebookInstantGamesIdInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (FacebookInstantGamesId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("FacebookInstantGamesId")); writer->WriteValue(FacebookInstantGamesId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserFacebookInstantGamesIdInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> FacebookInstantGamesIdValue = obj->TryGetField(TEXT("FacebookInstantGamesId")); if (FacebookInstantGamesIdValue.IsValid() && !FacebookInstantGamesIdValue->IsNull()) { FString TmpValue; if (FacebookInstantGamesIdValue->TryGetString(TmpValue)) { FacebookInstantGamesId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserGameCenterInfo::~FUserGameCenterInfo() { } void PlayFab::ServerModels::FUserGameCenterInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (GameCenterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("GameCenterId")); writer->WriteValue(GameCenterId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserGameCenterInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> GameCenterIdValue = obj->TryGetField(TEXT("GameCenterId")); if (GameCenterIdValue.IsValid() && !GameCenterIdValue->IsNull()) { FString TmpValue; if (GameCenterIdValue->TryGetString(TmpValue)) { GameCenterId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserGoogleInfo::~FUserGoogleInfo() { } void PlayFab::ServerModels::FUserGoogleInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (GoogleEmail.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("GoogleEmail")); writer->WriteValue(GoogleEmail); } if (GoogleGender.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("GoogleGender")); writer->WriteValue(GoogleGender); } if (GoogleId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("GoogleId")); writer->WriteValue(GoogleId); } if (GoogleLocale.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("GoogleLocale")); writer->WriteValue(GoogleLocale); } if (GoogleName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("GoogleName")); writer->WriteValue(GoogleName); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserGoogleInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> GoogleEmailValue = obj->TryGetField(TEXT("GoogleEmail")); if (GoogleEmailValue.IsValid() && !GoogleEmailValue->IsNull()) { FString TmpValue; if (GoogleEmailValue->TryGetString(TmpValue)) { GoogleEmail = TmpValue; } } const TSharedPtr<FJsonValue> GoogleGenderValue = obj->TryGetField(TEXT("GoogleGender")); if (GoogleGenderValue.IsValid() && !GoogleGenderValue->IsNull()) { FString TmpValue; if (GoogleGenderValue->TryGetString(TmpValue)) { GoogleGender = TmpValue; } } const TSharedPtr<FJsonValue> GoogleIdValue = obj->TryGetField(TEXT("GoogleId")); if (GoogleIdValue.IsValid() && !GoogleIdValue->IsNull()) { FString TmpValue; if (GoogleIdValue->TryGetString(TmpValue)) { GoogleId = TmpValue; } } const TSharedPtr<FJsonValue> GoogleLocaleValue = obj->TryGetField(TEXT("GoogleLocale")); if (GoogleLocaleValue.IsValid() && !GoogleLocaleValue->IsNull()) { FString TmpValue; if (GoogleLocaleValue->TryGetString(TmpValue)) { GoogleLocale = TmpValue; } } const TSharedPtr<FJsonValue> GoogleNameValue = obj->TryGetField(TEXT("GoogleName")); if (GoogleNameValue.IsValid() && !GoogleNameValue->IsNull()) { FString TmpValue; if (GoogleNameValue->TryGetString(TmpValue)) { GoogleName = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserIosDeviceInfo::~FUserIosDeviceInfo() { } void PlayFab::ServerModels::FUserIosDeviceInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (IosDeviceId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("IosDeviceId")); writer->WriteValue(IosDeviceId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserIosDeviceInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> IosDeviceIdValue = obj->TryGetField(TEXT("IosDeviceId")); if (IosDeviceIdValue.IsValid() && !IosDeviceIdValue->IsNull()) { FString TmpValue; if (IosDeviceIdValue->TryGetString(TmpValue)) { IosDeviceId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserKongregateInfo::~FUserKongregateInfo() { } void PlayFab::ServerModels::FUserKongregateInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (KongregateId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("KongregateId")); writer->WriteValue(KongregateId); } if (KongregateName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("KongregateName")); writer->WriteValue(KongregateName); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserKongregateInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> KongregateIdValue = obj->TryGetField(TEXT("KongregateId")); if (KongregateIdValue.IsValid() && !KongregateIdValue->IsNull()) { FString TmpValue; if (KongregateIdValue->TryGetString(TmpValue)) { KongregateId = TmpValue; } } const TSharedPtr<FJsonValue> KongregateNameValue = obj->TryGetField(TEXT("KongregateName")); if (KongregateNameValue.IsValid() && !KongregateNameValue->IsNull()) { FString TmpValue; if (KongregateNameValue->TryGetString(TmpValue)) { KongregateName = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserNintendoSwitchDeviceIdInfo::~FUserNintendoSwitchDeviceIdInfo() { } void PlayFab::ServerModels::FUserNintendoSwitchDeviceIdInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (NintendoSwitchDeviceId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("NintendoSwitchDeviceId")); writer->WriteValue(NintendoSwitchDeviceId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserNintendoSwitchDeviceIdInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> NintendoSwitchDeviceIdValue = obj->TryGetField(TEXT("NintendoSwitchDeviceId")); if (NintendoSwitchDeviceIdValue.IsValid() && !NintendoSwitchDeviceIdValue->IsNull()) { FString TmpValue; if (NintendoSwitchDeviceIdValue->TryGetString(TmpValue)) { NintendoSwitchDeviceId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserOpenIdInfo::~FUserOpenIdInfo() { } void PlayFab::ServerModels::FUserOpenIdInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (ConnectionId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ConnectionId")); writer->WriteValue(ConnectionId); } if (Issuer.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Issuer")); writer->WriteValue(Issuer); } if (Subject.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Subject")); writer->WriteValue(Subject); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserOpenIdInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ConnectionIdValue = obj->TryGetField(TEXT("ConnectionId")); if (ConnectionIdValue.IsValid() && !ConnectionIdValue->IsNull()) { FString TmpValue; if (ConnectionIdValue->TryGetString(TmpValue)) { ConnectionId = TmpValue; } } const TSharedPtr<FJsonValue> IssuerValue = obj->TryGetField(TEXT("Issuer")); if (IssuerValue.IsValid() && !IssuerValue->IsNull()) { FString TmpValue; if (IssuerValue->TryGetString(TmpValue)) { Issuer = TmpValue; } } const TSharedPtr<FJsonValue> SubjectValue = obj->TryGetField(TEXT("Subject")); if (SubjectValue.IsValid() && !SubjectValue->IsNull()) { FString TmpValue; if (SubjectValue->TryGetString(TmpValue)) { Subject = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserPrivateAccountInfo::~FUserPrivateAccountInfo() { } void PlayFab::ServerModels::FUserPrivateAccountInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Email.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Email")); writer->WriteValue(Email); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserPrivateAccountInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> EmailValue = obj->TryGetField(TEXT("Email")); if (EmailValue.IsValid() && !EmailValue->IsNull()) { FString TmpValue; if (EmailValue->TryGetString(TmpValue)) { Email = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserPsnInfo::~FUserPsnInfo() { } void PlayFab::ServerModels::FUserPsnInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (PsnAccountId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PsnAccountId")); writer->WriteValue(PsnAccountId); } if (PsnOnlineId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PsnOnlineId")); writer->WriteValue(PsnOnlineId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserPsnInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PsnAccountIdValue = obj->TryGetField(TEXT("PsnAccountId")); if (PsnAccountIdValue.IsValid() && !PsnAccountIdValue->IsNull()) { FString TmpValue; if (PsnAccountIdValue->TryGetString(TmpValue)) { PsnAccountId = TmpValue; } } const TSharedPtr<FJsonValue> PsnOnlineIdValue = obj->TryGetField(TEXT("PsnOnlineId")); if (PsnOnlineIdValue.IsValid() && !PsnOnlineIdValue->IsNull()) { FString TmpValue; if (PsnOnlineIdValue->TryGetString(TmpValue)) { PsnOnlineId = TmpValue; } } return HasSucceeded; } void PlayFab::ServerModels::writeTitleActivationStatusEnumJSON(TitleActivationStatus enumVal, JsonWriter& writer) { switch (enumVal) { case TitleActivationStatusNone: writer->WriteValue(TEXT("None")); break; case TitleActivationStatusActivatedTitleKey: writer->WriteValue(TEXT("ActivatedTitleKey")); break; case TitleActivationStatusPendingSteam: writer->WriteValue(TEXT("PendingSteam")); break; case TitleActivationStatusActivatedSteam: writer->WriteValue(TEXT("ActivatedSteam")); break; case TitleActivationStatusRevokedSteam: writer->WriteValue(TEXT("RevokedSteam")); break; } } ServerModels::TitleActivationStatus PlayFab::ServerModels::readTitleActivationStatusFromValue(const TSharedPtr<FJsonValue>& value) { return readTitleActivationStatusFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::TitleActivationStatus PlayFab::ServerModels::readTitleActivationStatusFromValue(const FString& value) { static TMap<FString, TitleActivationStatus> _TitleActivationStatusMap; if (_TitleActivationStatusMap.Num() == 0) { // Auto-generate the map on the first use _TitleActivationStatusMap.Add(TEXT("None"), TitleActivationStatusNone); _TitleActivationStatusMap.Add(TEXT("ActivatedTitleKey"), TitleActivationStatusActivatedTitleKey); _TitleActivationStatusMap.Add(TEXT("PendingSteam"), TitleActivationStatusPendingSteam); _TitleActivationStatusMap.Add(TEXT("ActivatedSteam"), TitleActivationStatusActivatedSteam); _TitleActivationStatusMap.Add(TEXT("RevokedSteam"), TitleActivationStatusRevokedSteam); } if (!value.IsEmpty()) { auto output = _TitleActivationStatusMap.Find(value); if (output != nullptr) return *output; } return TitleActivationStatusNone; // Basically critical fail } void PlayFab::ServerModels::writeCurrencyEnumJSON(Currency enumVal, JsonWriter& writer) { switch (enumVal) { case CurrencyAED: writer->WriteValue(TEXT("AED")); break; case CurrencyAFN: writer->WriteValue(TEXT("AFN")); break; case CurrencyALL: writer->WriteValue(TEXT("ALL")); break; case CurrencyAMD: writer->WriteValue(TEXT("AMD")); break; case CurrencyANG: writer->WriteValue(TEXT("ANG")); break; case CurrencyAOA: writer->WriteValue(TEXT("AOA")); break; case CurrencyARS: writer->WriteValue(TEXT("ARS")); break; case CurrencyAUD: writer->WriteValue(TEXT("AUD")); break; case CurrencyAWG: writer->WriteValue(TEXT("AWG")); break; case CurrencyAZN: writer->WriteValue(TEXT("AZN")); break; case CurrencyBAM: writer->WriteValue(TEXT("BAM")); break; case CurrencyBBD: writer->WriteValue(TEXT("BBD")); break; case CurrencyBDT: writer->WriteValue(TEXT("BDT")); break; case CurrencyBGN: writer->WriteValue(TEXT("BGN")); break; case CurrencyBHD: writer->WriteValue(TEXT("BHD")); break; case CurrencyBIF: writer->WriteValue(TEXT("BIF")); break; case CurrencyBMD: writer->WriteValue(TEXT("BMD")); break; case CurrencyBND: writer->WriteValue(TEXT("BND")); break; case CurrencyBOB: writer->WriteValue(TEXT("BOB")); break; case CurrencyBRL: writer->WriteValue(TEXT("BRL")); break; case CurrencyBSD: writer->WriteValue(TEXT("BSD")); break; case CurrencyBTN: writer->WriteValue(TEXT("BTN")); break; case CurrencyBWP: writer->WriteValue(TEXT("BWP")); break; case CurrencyBYR: writer->WriteValue(TEXT("BYR")); break; case CurrencyBZD: writer->WriteValue(TEXT("BZD")); break; case CurrencyCAD: writer->WriteValue(TEXT("CAD")); break; case CurrencyCDF: writer->WriteValue(TEXT("CDF")); break; case CurrencyCHF: writer->WriteValue(TEXT("CHF")); break; case CurrencyCLP: writer->WriteValue(TEXT("CLP")); break; case CurrencyCNY: writer->WriteValue(TEXT("CNY")); break; case CurrencyCOP: writer->WriteValue(TEXT("COP")); break; case CurrencyCRC: writer->WriteValue(TEXT("CRC")); break; case CurrencyCUC: writer->WriteValue(TEXT("CUC")); break; case CurrencyCUP: writer->WriteValue(TEXT("CUP")); break; case CurrencyCVE: writer->WriteValue(TEXT("CVE")); break; case CurrencyCZK: writer->WriteValue(TEXT("CZK")); break; case CurrencyDJF: writer->WriteValue(TEXT("DJF")); break; case CurrencyDKK: writer->WriteValue(TEXT("DKK")); break; case CurrencyDOP: writer->WriteValue(TEXT("DOP")); break; case CurrencyDZD: writer->WriteValue(TEXT("DZD")); break; case CurrencyEGP: writer->WriteValue(TEXT("EGP")); break; case CurrencyERN: writer->WriteValue(TEXT("ERN")); break; case CurrencyETB: writer->WriteValue(TEXT("ETB")); break; case CurrencyEUR: writer->WriteValue(TEXT("EUR")); break; case CurrencyFJD: writer->WriteValue(TEXT("FJD")); break; case CurrencyFKP: writer->WriteValue(TEXT("FKP")); break; case CurrencyGBP: writer->WriteValue(TEXT("GBP")); break; case CurrencyGEL: writer->WriteValue(TEXT("GEL")); break; case CurrencyGGP: writer->WriteValue(TEXT("GGP")); break; case CurrencyGHS: writer->WriteValue(TEXT("GHS")); break; case CurrencyGIP: writer->WriteValue(TEXT("GIP")); break; case CurrencyGMD: writer->WriteValue(TEXT("GMD")); break; case CurrencyGNF: writer->WriteValue(TEXT("GNF")); break; case CurrencyGTQ: writer->WriteValue(TEXT("GTQ")); break; case CurrencyGYD: writer->WriteValue(TEXT("GYD")); break; case CurrencyHKD: writer->WriteValue(TEXT("HKD")); break; case CurrencyHNL: writer->WriteValue(TEXT("HNL")); break; case CurrencyHRK: writer->WriteValue(TEXT("HRK")); break; case CurrencyHTG: writer->WriteValue(TEXT("HTG")); break; case CurrencyHUF: writer->WriteValue(TEXT("HUF")); break; case CurrencyIDR: writer->WriteValue(TEXT("IDR")); break; case CurrencyILS: writer->WriteValue(TEXT("ILS")); break; case CurrencyIMP: writer->WriteValue(TEXT("IMP")); break; case CurrencyINR: writer->WriteValue(TEXT("INR")); break; case CurrencyIQD: writer->WriteValue(TEXT("IQD")); break; case CurrencyIRR: writer->WriteValue(TEXT("IRR")); break; case CurrencyISK: writer->WriteValue(TEXT("ISK")); break; case CurrencyJEP: writer->WriteValue(TEXT("JEP")); break; case CurrencyJMD: writer->WriteValue(TEXT("JMD")); break; case CurrencyJOD: writer->WriteValue(TEXT("JOD")); break; case CurrencyJPY: writer->WriteValue(TEXT("JPY")); break; case CurrencyKES: writer->WriteValue(TEXT("KES")); break; case CurrencyKGS: writer->WriteValue(TEXT("KGS")); break; case CurrencyKHR: writer->WriteValue(TEXT("KHR")); break; case CurrencyKMF: writer->WriteValue(TEXT("KMF")); break; case CurrencyKPW: writer->WriteValue(TEXT("KPW")); break; case CurrencyKRW: writer->WriteValue(TEXT("KRW")); break; case CurrencyKWD: writer->WriteValue(TEXT("KWD")); break; case CurrencyKYD: writer->WriteValue(TEXT("KYD")); break; case CurrencyKZT: writer->WriteValue(TEXT("KZT")); break; case CurrencyLAK: writer->WriteValue(TEXT("LAK")); break; case CurrencyLBP: writer->WriteValue(TEXT("LBP")); break; case CurrencyLKR: writer->WriteValue(TEXT("LKR")); break; case CurrencyLRD: writer->WriteValue(TEXT("LRD")); break; case CurrencyLSL: writer->WriteValue(TEXT("LSL")); break; case CurrencyLYD: writer->WriteValue(TEXT("LYD")); break; case CurrencyMAD: writer->WriteValue(TEXT("MAD")); break; case CurrencyMDL: writer->WriteValue(TEXT("MDL")); break; case CurrencyMGA: writer->WriteValue(TEXT("MGA")); break; case CurrencyMKD: writer->WriteValue(TEXT("MKD")); break; case CurrencyMMK: writer->WriteValue(TEXT("MMK")); break; case CurrencyMNT: writer->WriteValue(TEXT("MNT")); break; case CurrencyMOP: writer->WriteValue(TEXT("MOP")); break; case CurrencyMRO: writer->WriteValue(TEXT("MRO")); break; case CurrencyMUR: writer->WriteValue(TEXT("MUR")); break; case CurrencyMVR: writer->WriteValue(TEXT("MVR")); break; case CurrencyMWK: writer->WriteValue(TEXT("MWK")); break; case CurrencyMXN: writer->WriteValue(TEXT("MXN")); break; case CurrencyMYR: writer->WriteValue(TEXT("MYR")); break; case CurrencyMZN: writer->WriteValue(TEXT("MZN")); break; case CurrencyNAD: writer->WriteValue(TEXT("NAD")); break; case CurrencyNGN: writer->WriteValue(TEXT("NGN")); break; case CurrencyNIO: writer->WriteValue(TEXT("NIO")); break; case CurrencyNOK: writer->WriteValue(TEXT("NOK")); break; case CurrencyNPR: writer->WriteValue(TEXT("NPR")); break; case CurrencyNZD: writer->WriteValue(TEXT("NZD")); break; case CurrencyOMR: writer->WriteValue(TEXT("OMR")); break; case CurrencyPAB: writer->WriteValue(TEXT("PAB")); break; case CurrencyPEN: writer->WriteValue(TEXT("PEN")); break; case CurrencyPGK: writer->WriteValue(TEXT("PGK")); break; case CurrencyPHP: writer->WriteValue(TEXT("PHP")); break; case CurrencyPKR: writer->WriteValue(TEXT("PKR")); break; case CurrencyPLN: writer->WriteValue(TEXT("PLN")); break; case CurrencyPYG: writer->WriteValue(TEXT("PYG")); break; case CurrencyQAR: writer->WriteValue(TEXT("QAR")); break; case CurrencyRON: writer->WriteValue(TEXT("RON")); break; case CurrencyRSD: writer->WriteValue(TEXT("RSD")); break; case CurrencyRUB: writer->WriteValue(TEXT("RUB")); break; case CurrencyRWF: writer->WriteValue(TEXT("RWF")); break; case CurrencySAR: writer->WriteValue(TEXT("SAR")); break; case CurrencySBD: writer->WriteValue(TEXT("SBD")); break; case CurrencySCR: writer->WriteValue(TEXT("SCR")); break; case CurrencySDG: writer->WriteValue(TEXT("SDG")); break; case CurrencySEK: writer->WriteValue(TEXT("SEK")); break; case CurrencySGD: writer->WriteValue(TEXT("SGD")); break; case CurrencySHP: writer->WriteValue(TEXT("SHP")); break; case CurrencySLL: writer->WriteValue(TEXT("SLL")); break; case CurrencySOS: writer->WriteValue(TEXT("SOS")); break; case CurrencySPL: writer->WriteValue(TEXT("SPL")); break; case CurrencySRD: writer->WriteValue(TEXT("SRD")); break; case CurrencySTD: writer->WriteValue(TEXT("STD")); break; case CurrencySVC: writer->WriteValue(TEXT("SVC")); break; case CurrencySYP: writer->WriteValue(TEXT("SYP")); break; case CurrencySZL: writer->WriteValue(TEXT("SZL")); break; case CurrencyTHB: writer->WriteValue(TEXT("THB")); break; case CurrencyTJS: writer->WriteValue(TEXT("TJS")); break; case CurrencyTMT: writer->WriteValue(TEXT("TMT")); break; case CurrencyTND: writer->WriteValue(TEXT("TND")); break; case CurrencyTOP: writer->WriteValue(TEXT("TOP")); break; case CurrencyTRY: writer->WriteValue(TEXT("TRY")); break; case CurrencyTTD: writer->WriteValue(TEXT("TTD")); break; case CurrencyTVD: writer->WriteValue(TEXT("TVD")); break; case CurrencyTWD: writer->WriteValue(TEXT("TWD")); break; case CurrencyTZS: writer->WriteValue(TEXT("TZS")); break; case CurrencyUAH: writer->WriteValue(TEXT("UAH")); break; case CurrencyUGX: writer->WriteValue(TEXT("UGX")); break; case CurrencyUSD: writer->WriteValue(TEXT("USD")); break; case CurrencyUYU: writer->WriteValue(TEXT("UYU")); break; case CurrencyUZS: writer->WriteValue(TEXT("UZS")); break; case CurrencyVEF: writer->WriteValue(TEXT("VEF")); break; case CurrencyVND: writer->WriteValue(TEXT("VND")); break; case CurrencyVUV: writer->WriteValue(TEXT("VUV")); break; case CurrencyWST: writer->WriteValue(TEXT("WST")); break; case CurrencyXAF: writer->WriteValue(TEXT("XAF")); break; case CurrencyXCD: writer->WriteValue(TEXT("XCD")); break; case CurrencyXDR: writer->WriteValue(TEXT("XDR")); break; case CurrencyXOF: writer->WriteValue(TEXT("XOF")); break; case CurrencyXPF: writer->WriteValue(TEXT("XPF")); break; case CurrencyYER: writer->WriteValue(TEXT("YER")); break; case CurrencyZAR: writer->WriteValue(TEXT("ZAR")); break; case CurrencyZMW: writer->WriteValue(TEXT("ZMW")); break; case CurrencyZWD: writer->WriteValue(TEXT("ZWD")); break; } } ServerModels::Currency PlayFab::ServerModels::readCurrencyFromValue(const TSharedPtr<FJsonValue>& value) { return readCurrencyFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::Currency PlayFab::ServerModels::readCurrencyFromValue(const FString& value) { static TMap<FString, Currency> _CurrencyMap; if (_CurrencyMap.Num() == 0) { // Auto-generate the map on the first use _CurrencyMap.Add(TEXT("AED"), CurrencyAED); _CurrencyMap.Add(TEXT("AFN"), CurrencyAFN); _CurrencyMap.Add(TEXT("ALL"), CurrencyALL); _CurrencyMap.Add(TEXT("AMD"), CurrencyAMD); _CurrencyMap.Add(TEXT("ANG"), CurrencyANG); _CurrencyMap.Add(TEXT("AOA"), CurrencyAOA); _CurrencyMap.Add(TEXT("ARS"), CurrencyARS); _CurrencyMap.Add(TEXT("AUD"), CurrencyAUD); _CurrencyMap.Add(TEXT("AWG"), CurrencyAWG); _CurrencyMap.Add(TEXT("AZN"), CurrencyAZN); _CurrencyMap.Add(TEXT("BAM"), CurrencyBAM); _CurrencyMap.Add(TEXT("BBD"), CurrencyBBD); _CurrencyMap.Add(TEXT("BDT"), CurrencyBDT); _CurrencyMap.Add(TEXT("BGN"), CurrencyBGN); _CurrencyMap.Add(TEXT("BHD"), CurrencyBHD); _CurrencyMap.Add(TEXT("BIF"), CurrencyBIF); _CurrencyMap.Add(TEXT("BMD"), CurrencyBMD); _CurrencyMap.Add(TEXT("BND"), CurrencyBND); _CurrencyMap.Add(TEXT("BOB"), CurrencyBOB); _CurrencyMap.Add(TEXT("BRL"), CurrencyBRL); _CurrencyMap.Add(TEXT("BSD"), CurrencyBSD); _CurrencyMap.Add(TEXT("BTN"), CurrencyBTN); _CurrencyMap.Add(TEXT("BWP"), CurrencyBWP); _CurrencyMap.Add(TEXT("BYR"), CurrencyBYR); _CurrencyMap.Add(TEXT("BZD"), CurrencyBZD); _CurrencyMap.Add(TEXT("CAD"), CurrencyCAD); _CurrencyMap.Add(TEXT("CDF"), CurrencyCDF); _CurrencyMap.Add(TEXT("CHF"), CurrencyCHF); _CurrencyMap.Add(TEXT("CLP"), CurrencyCLP); _CurrencyMap.Add(TEXT("CNY"), CurrencyCNY); _CurrencyMap.Add(TEXT("COP"), CurrencyCOP); _CurrencyMap.Add(TEXT("CRC"), CurrencyCRC); _CurrencyMap.Add(TEXT("CUC"), CurrencyCUC); _CurrencyMap.Add(TEXT("CUP"), CurrencyCUP); _CurrencyMap.Add(TEXT("CVE"), CurrencyCVE); _CurrencyMap.Add(TEXT("CZK"), CurrencyCZK); _CurrencyMap.Add(TEXT("DJF"), CurrencyDJF); _CurrencyMap.Add(TEXT("DKK"), CurrencyDKK); _CurrencyMap.Add(TEXT("DOP"), CurrencyDOP); _CurrencyMap.Add(TEXT("DZD"), CurrencyDZD); _CurrencyMap.Add(TEXT("EGP"), CurrencyEGP); _CurrencyMap.Add(TEXT("ERN"), CurrencyERN); _CurrencyMap.Add(TEXT("ETB"), CurrencyETB); _CurrencyMap.Add(TEXT("EUR"), CurrencyEUR); _CurrencyMap.Add(TEXT("FJD"), CurrencyFJD); _CurrencyMap.Add(TEXT("FKP"), CurrencyFKP); _CurrencyMap.Add(TEXT("GBP"), CurrencyGBP); _CurrencyMap.Add(TEXT("GEL"), CurrencyGEL); _CurrencyMap.Add(TEXT("GGP"), CurrencyGGP); _CurrencyMap.Add(TEXT("GHS"), CurrencyGHS); _CurrencyMap.Add(TEXT("GIP"), CurrencyGIP); _CurrencyMap.Add(TEXT("GMD"), CurrencyGMD); _CurrencyMap.Add(TEXT("GNF"), CurrencyGNF); _CurrencyMap.Add(TEXT("GTQ"), CurrencyGTQ); _CurrencyMap.Add(TEXT("GYD"), CurrencyGYD); _CurrencyMap.Add(TEXT("HKD"), CurrencyHKD); _CurrencyMap.Add(TEXT("HNL"), CurrencyHNL); _CurrencyMap.Add(TEXT("HRK"), CurrencyHRK); _CurrencyMap.Add(TEXT("HTG"), CurrencyHTG); _CurrencyMap.Add(TEXT("HUF"), CurrencyHUF); _CurrencyMap.Add(TEXT("IDR"), CurrencyIDR); _CurrencyMap.Add(TEXT("ILS"), CurrencyILS); _CurrencyMap.Add(TEXT("IMP"), CurrencyIMP); _CurrencyMap.Add(TEXT("INR"), CurrencyINR); _CurrencyMap.Add(TEXT("IQD"), CurrencyIQD); _CurrencyMap.Add(TEXT("IRR"), CurrencyIRR); _CurrencyMap.Add(TEXT("ISK"), CurrencyISK); _CurrencyMap.Add(TEXT("JEP"), CurrencyJEP); _CurrencyMap.Add(TEXT("JMD"), CurrencyJMD); _CurrencyMap.Add(TEXT("JOD"), CurrencyJOD); _CurrencyMap.Add(TEXT("JPY"), CurrencyJPY); _CurrencyMap.Add(TEXT("KES"), CurrencyKES); _CurrencyMap.Add(TEXT("KGS"), CurrencyKGS); _CurrencyMap.Add(TEXT("KHR"), CurrencyKHR); _CurrencyMap.Add(TEXT("KMF"), CurrencyKMF); _CurrencyMap.Add(TEXT("KPW"), CurrencyKPW); _CurrencyMap.Add(TEXT("KRW"), CurrencyKRW); _CurrencyMap.Add(TEXT("KWD"), CurrencyKWD); _CurrencyMap.Add(TEXT("KYD"), CurrencyKYD); _CurrencyMap.Add(TEXT("KZT"), CurrencyKZT); _CurrencyMap.Add(TEXT("LAK"), CurrencyLAK); _CurrencyMap.Add(TEXT("LBP"), CurrencyLBP); _CurrencyMap.Add(TEXT("LKR"), CurrencyLKR); _CurrencyMap.Add(TEXT("LRD"), CurrencyLRD); _CurrencyMap.Add(TEXT("LSL"), CurrencyLSL); _CurrencyMap.Add(TEXT("LYD"), CurrencyLYD); _CurrencyMap.Add(TEXT("MAD"), CurrencyMAD); _CurrencyMap.Add(TEXT("MDL"), CurrencyMDL); _CurrencyMap.Add(TEXT("MGA"), CurrencyMGA); _CurrencyMap.Add(TEXT("MKD"), CurrencyMKD); _CurrencyMap.Add(TEXT("MMK"), CurrencyMMK); _CurrencyMap.Add(TEXT("MNT"), CurrencyMNT); _CurrencyMap.Add(TEXT("MOP"), CurrencyMOP); _CurrencyMap.Add(TEXT("MRO"), CurrencyMRO); _CurrencyMap.Add(TEXT("MUR"), CurrencyMUR); _CurrencyMap.Add(TEXT("MVR"), CurrencyMVR); _CurrencyMap.Add(TEXT("MWK"), CurrencyMWK); _CurrencyMap.Add(TEXT("MXN"), CurrencyMXN); _CurrencyMap.Add(TEXT("MYR"), CurrencyMYR); _CurrencyMap.Add(TEXT("MZN"), CurrencyMZN); _CurrencyMap.Add(TEXT("NAD"), CurrencyNAD); _CurrencyMap.Add(TEXT("NGN"), CurrencyNGN); _CurrencyMap.Add(TEXT("NIO"), CurrencyNIO); _CurrencyMap.Add(TEXT("NOK"), CurrencyNOK); _CurrencyMap.Add(TEXT("NPR"), CurrencyNPR); _CurrencyMap.Add(TEXT("NZD"), CurrencyNZD); _CurrencyMap.Add(TEXT("OMR"), CurrencyOMR); _CurrencyMap.Add(TEXT("PAB"), CurrencyPAB); _CurrencyMap.Add(TEXT("PEN"), CurrencyPEN); _CurrencyMap.Add(TEXT("PGK"), CurrencyPGK); _CurrencyMap.Add(TEXT("PHP"), CurrencyPHP); _CurrencyMap.Add(TEXT("PKR"), CurrencyPKR); _CurrencyMap.Add(TEXT("PLN"), CurrencyPLN); _CurrencyMap.Add(TEXT("PYG"), CurrencyPYG); _CurrencyMap.Add(TEXT("QAR"), CurrencyQAR); _CurrencyMap.Add(TEXT("RON"), CurrencyRON); _CurrencyMap.Add(TEXT("RSD"), CurrencyRSD); _CurrencyMap.Add(TEXT("RUB"), CurrencyRUB); _CurrencyMap.Add(TEXT("RWF"), CurrencyRWF); _CurrencyMap.Add(TEXT("SAR"), CurrencySAR); _CurrencyMap.Add(TEXT("SBD"), CurrencySBD); _CurrencyMap.Add(TEXT("SCR"), CurrencySCR); _CurrencyMap.Add(TEXT("SDG"), CurrencySDG); _CurrencyMap.Add(TEXT("SEK"), CurrencySEK); _CurrencyMap.Add(TEXT("SGD"), CurrencySGD); _CurrencyMap.Add(TEXT("SHP"), CurrencySHP); _CurrencyMap.Add(TEXT("SLL"), CurrencySLL); _CurrencyMap.Add(TEXT("SOS"), CurrencySOS); _CurrencyMap.Add(TEXT("SPL"), CurrencySPL); _CurrencyMap.Add(TEXT("SRD"), CurrencySRD); _CurrencyMap.Add(TEXT("STD"), CurrencySTD); _CurrencyMap.Add(TEXT("SVC"), CurrencySVC); _CurrencyMap.Add(TEXT("SYP"), CurrencySYP); _CurrencyMap.Add(TEXT("SZL"), CurrencySZL); _CurrencyMap.Add(TEXT("THB"), CurrencyTHB); _CurrencyMap.Add(TEXT("TJS"), CurrencyTJS); _CurrencyMap.Add(TEXT("TMT"), CurrencyTMT); _CurrencyMap.Add(TEXT("TND"), CurrencyTND); _CurrencyMap.Add(TEXT("TOP"), CurrencyTOP); _CurrencyMap.Add(TEXT("TRY"), CurrencyTRY); _CurrencyMap.Add(TEXT("TTD"), CurrencyTTD); _CurrencyMap.Add(TEXT("TVD"), CurrencyTVD); _CurrencyMap.Add(TEXT("TWD"), CurrencyTWD); _CurrencyMap.Add(TEXT("TZS"), CurrencyTZS); _CurrencyMap.Add(TEXT("UAH"), CurrencyUAH); _CurrencyMap.Add(TEXT("UGX"), CurrencyUGX); _CurrencyMap.Add(TEXT("USD"), CurrencyUSD); _CurrencyMap.Add(TEXT("UYU"), CurrencyUYU); _CurrencyMap.Add(TEXT("UZS"), CurrencyUZS); _CurrencyMap.Add(TEXT("VEF"), CurrencyVEF); _CurrencyMap.Add(TEXT("VND"), CurrencyVND); _CurrencyMap.Add(TEXT("VUV"), CurrencyVUV); _CurrencyMap.Add(TEXT("WST"), CurrencyWST); _CurrencyMap.Add(TEXT("XAF"), CurrencyXAF); _CurrencyMap.Add(TEXT("XCD"), CurrencyXCD); _CurrencyMap.Add(TEXT("XDR"), CurrencyXDR); _CurrencyMap.Add(TEXT("XOF"), CurrencyXOF); _CurrencyMap.Add(TEXT("XPF"), CurrencyXPF); _CurrencyMap.Add(TEXT("YER"), CurrencyYER); _CurrencyMap.Add(TEXT("ZAR"), CurrencyZAR); _CurrencyMap.Add(TEXT("ZMW"), CurrencyZMW); _CurrencyMap.Add(TEXT("ZWD"), CurrencyZWD); } if (!value.IsEmpty()) { auto output = _CurrencyMap.Find(value); if (output != nullptr) return *output; } return CurrencyAED; // Basically critical fail } PlayFab::ServerModels::FUserSteamInfo::~FUserSteamInfo() { } void PlayFab::ServerModels::FUserSteamInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (SteamActivationStatus.notNull()) { writer->WriteIdentifierPrefix(TEXT("SteamActivationStatus")); writeTitleActivationStatusEnumJSON(SteamActivationStatus, writer); } if (SteamCountry.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("SteamCountry")); writer->WriteValue(SteamCountry); } if (SteamCurrency.notNull()) { writer->WriteIdentifierPrefix(TEXT("SteamCurrency")); writeCurrencyEnumJSON(SteamCurrency, writer); } if (SteamId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("SteamId")); writer->WriteValue(SteamId); } if (SteamName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("SteamName")); writer->WriteValue(SteamName); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserSteamInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; SteamActivationStatus = readTitleActivationStatusFromValue(obj->TryGetField(TEXT("SteamActivationStatus"))); const TSharedPtr<FJsonValue> SteamCountryValue = obj->TryGetField(TEXT("SteamCountry")); if (SteamCountryValue.IsValid() && !SteamCountryValue->IsNull()) { FString TmpValue; if (SteamCountryValue->TryGetString(TmpValue)) { SteamCountry = TmpValue; } } SteamCurrency = readCurrencyFromValue(obj->TryGetField(TEXT("SteamCurrency"))); const TSharedPtr<FJsonValue> SteamIdValue = obj->TryGetField(TEXT("SteamId")); if (SteamIdValue.IsValid() && !SteamIdValue->IsNull()) { FString TmpValue; if (SteamIdValue->TryGetString(TmpValue)) { SteamId = TmpValue; } } const TSharedPtr<FJsonValue> SteamNameValue = obj->TryGetField(TEXT("SteamName")); if (SteamNameValue.IsValid() && !SteamNameValue->IsNull()) { FString TmpValue; if (SteamNameValue->TryGetString(TmpValue)) { SteamName = TmpValue; } } return HasSucceeded; } void PlayFab::ServerModels::writeUserOriginationEnumJSON(UserOrigination enumVal, JsonWriter& writer) { switch (enumVal) { case UserOriginationOrganic: writer->WriteValue(TEXT("Organic")); break; case UserOriginationSteam: writer->WriteValue(TEXT("Steam")); break; case UserOriginationGoogle: writer->WriteValue(TEXT("Google")); break; case UserOriginationAmazon: writer->WriteValue(TEXT("Amazon")); break; case UserOriginationFacebook: writer->WriteValue(TEXT("Facebook")); break; case UserOriginationKongregate: writer->WriteValue(TEXT("Kongregate")); break; case UserOriginationGamersFirst: writer->WriteValue(TEXT("GamersFirst")); break; case UserOriginationUnknown: writer->WriteValue(TEXT("Unknown")); break; case UserOriginationIOS: writer->WriteValue(TEXT("IOS")); break; case UserOriginationLoadTest: writer->WriteValue(TEXT("LoadTest")); break; case UserOriginationAndroid: writer->WriteValue(TEXT("Android")); break; case UserOriginationPSN: writer->WriteValue(TEXT("PSN")); break; case UserOriginationGameCenter: writer->WriteValue(TEXT("GameCenter")); break; case UserOriginationCustomId: writer->WriteValue(TEXT("CustomId")); break; case UserOriginationXboxLive: writer->WriteValue(TEXT("XboxLive")); break; case UserOriginationParse: writer->WriteValue(TEXT("Parse")); break; case UserOriginationTwitch: writer->WriteValue(TEXT("Twitch")); break; case UserOriginationWindowsHello: writer->WriteValue(TEXT("WindowsHello")); break; case UserOriginationServerCustomId: writer->WriteValue(TEXT("ServerCustomId")); break; case UserOriginationNintendoSwitchDeviceId: writer->WriteValue(TEXT("NintendoSwitchDeviceId")); break; case UserOriginationFacebookInstantGamesId: writer->WriteValue(TEXT("FacebookInstantGamesId")); break; case UserOriginationOpenIdConnect: writer->WriteValue(TEXT("OpenIdConnect")); break; } } ServerModels::UserOrigination PlayFab::ServerModels::readUserOriginationFromValue(const TSharedPtr<FJsonValue>& value) { return readUserOriginationFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::UserOrigination PlayFab::ServerModels::readUserOriginationFromValue(const FString& value) { static TMap<FString, UserOrigination> _UserOriginationMap; if (_UserOriginationMap.Num() == 0) { // Auto-generate the map on the first use _UserOriginationMap.Add(TEXT("Organic"), UserOriginationOrganic); _UserOriginationMap.Add(TEXT("Steam"), UserOriginationSteam); _UserOriginationMap.Add(TEXT("Google"), UserOriginationGoogle); _UserOriginationMap.Add(TEXT("Amazon"), UserOriginationAmazon); _UserOriginationMap.Add(TEXT("Facebook"), UserOriginationFacebook); _UserOriginationMap.Add(TEXT("Kongregate"), UserOriginationKongregate); _UserOriginationMap.Add(TEXT("GamersFirst"), UserOriginationGamersFirst); _UserOriginationMap.Add(TEXT("Unknown"), UserOriginationUnknown); _UserOriginationMap.Add(TEXT("IOS"), UserOriginationIOS); _UserOriginationMap.Add(TEXT("LoadTest"), UserOriginationLoadTest); _UserOriginationMap.Add(TEXT("Android"), UserOriginationAndroid); _UserOriginationMap.Add(TEXT("PSN"), UserOriginationPSN); _UserOriginationMap.Add(TEXT("GameCenter"), UserOriginationGameCenter); _UserOriginationMap.Add(TEXT("CustomId"), UserOriginationCustomId); _UserOriginationMap.Add(TEXT("XboxLive"), UserOriginationXboxLive); _UserOriginationMap.Add(TEXT("Parse"), UserOriginationParse); _UserOriginationMap.Add(TEXT("Twitch"), UserOriginationTwitch); _UserOriginationMap.Add(TEXT("WindowsHello"), UserOriginationWindowsHello); _UserOriginationMap.Add(TEXT("ServerCustomId"), UserOriginationServerCustomId); _UserOriginationMap.Add(TEXT("NintendoSwitchDeviceId"), UserOriginationNintendoSwitchDeviceId); _UserOriginationMap.Add(TEXT("FacebookInstantGamesId"), UserOriginationFacebookInstantGamesId); _UserOriginationMap.Add(TEXT("OpenIdConnect"), UserOriginationOpenIdConnect); } if (!value.IsEmpty()) { auto output = _UserOriginationMap.Find(value); if (output != nullptr) return *output; } return UserOriginationOrganic; // Basically critical fail } PlayFab::ServerModels::FEntityKey::~FEntityKey() { } void PlayFab::ServerModels::FEntityKey::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Id")); writer->WriteValue(Id); if (Type.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Type")); writer->WriteValue(Type); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FEntityKey::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> IdValue = obj->TryGetField(TEXT("Id")); if (IdValue.IsValid() && !IdValue->IsNull()) { FString TmpValue; if (IdValue->TryGetString(TmpValue)) { Id = TmpValue; } } const TSharedPtr<FJsonValue> TypeValue = obj->TryGetField(TEXT("Type")); if (TypeValue.IsValid() && !TypeValue->IsNull()) { FString TmpValue; if (TypeValue->TryGetString(TmpValue)) { Type = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserTitleInfo::~FUserTitleInfo() { //if (TitlePlayerAccount != nullptr) delete TitlePlayerAccount; } void PlayFab::ServerModels::FUserTitleInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (AvatarUrl.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("AvatarUrl")); writer->WriteValue(AvatarUrl); } writer->WriteIdentifierPrefix(TEXT("Created")); writeDatetime(Created, writer); if (DisplayName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("DisplayName")); writer->WriteValue(DisplayName); } if (FirstLogin.notNull()) { writer->WriteIdentifierPrefix(TEXT("FirstLogin")); writeDatetime(FirstLogin, writer); } if (isBanned.notNull()) { writer->WriteIdentifierPrefix(TEXT("isBanned")); writer->WriteValue(isBanned); } if (LastLogin.notNull()) { writer->WriteIdentifierPrefix(TEXT("LastLogin")); writeDatetime(LastLogin, writer); } if (Origination.notNull()) { writer->WriteIdentifierPrefix(TEXT("Origination")); writeUserOriginationEnumJSON(Origination, writer); } if (TitlePlayerAccount.IsValid()) { writer->WriteIdentifierPrefix(TEXT("TitlePlayerAccount")); TitlePlayerAccount->writeJSON(writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserTitleInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AvatarUrlValue = obj->TryGetField(TEXT("AvatarUrl")); if (AvatarUrlValue.IsValid() && !AvatarUrlValue->IsNull()) { FString TmpValue; if (AvatarUrlValue->TryGetString(TmpValue)) { AvatarUrl = TmpValue; } } const TSharedPtr<FJsonValue> CreatedValue = obj->TryGetField(TEXT("Created")); if (CreatedValue.IsValid()) Created = readDatetime(CreatedValue); const TSharedPtr<FJsonValue> DisplayNameValue = obj->TryGetField(TEXT("DisplayName")); if (DisplayNameValue.IsValid() && !DisplayNameValue->IsNull()) { FString TmpValue; if (DisplayNameValue->TryGetString(TmpValue)) { DisplayName = TmpValue; } } const TSharedPtr<FJsonValue> FirstLoginValue = obj->TryGetField(TEXT("FirstLogin")); if (FirstLoginValue.IsValid()) FirstLogin = readDatetime(FirstLoginValue); const TSharedPtr<FJsonValue> isBannedValue = obj->TryGetField(TEXT("isBanned")); if (isBannedValue.IsValid() && !isBannedValue->IsNull()) { bool TmpValue; if (isBannedValue->TryGetBool(TmpValue)) { isBanned = TmpValue; } } const TSharedPtr<FJsonValue> LastLoginValue = obj->TryGetField(TEXT("LastLogin")); if (LastLoginValue.IsValid()) LastLogin = readDatetime(LastLoginValue); Origination = readUserOriginationFromValue(obj->TryGetField(TEXT("Origination"))); const TSharedPtr<FJsonValue> TitlePlayerAccountValue = obj->TryGetField(TEXT("TitlePlayerAccount")); if (TitlePlayerAccountValue.IsValid() && !TitlePlayerAccountValue->IsNull()) { TitlePlayerAccount = MakeShareable(new FEntityKey(TitlePlayerAccountValue->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FUserTwitchInfo::~FUserTwitchInfo() { } void PlayFab::ServerModels::FUserTwitchInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (TwitchId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("TwitchId")); writer->WriteValue(TwitchId); } if (TwitchUserName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("TwitchUserName")); writer->WriteValue(TwitchUserName); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserTwitchInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> TwitchIdValue = obj->TryGetField(TEXT("TwitchId")); if (TwitchIdValue.IsValid() && !TwitchIdValue->IsNull()) { FString TmpValue; if (TwitchIdValue->TryGetString(TmpValue)) { TwitchId = TmpValue; } } const TSharedPtr<FJsonValue> TwitchUserNameValue = obj->TryGetField(TEXT("TwitchUserName")); if (TwitchUserNameValue.IsValid() && !TwitchUserNameValue->IsNull()) { FString TmpValue; if (TwitchUserNameValue->TryGetString(TmpValue)) { TwitchUserName = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserWindowsHelloInfo::~FUserWindowsHelloInfo() { } void PlayFab::ServerModels::FUserWindowsHelloInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (WindowsHelloDeviceName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("WindowsHelloDeviceName")); writer->WriteValue(WindowsHelloDeviceName); } if (WindowsHelloPublicKeyHash.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("WindowsHelloPublicKeyHash")); writer->WriteValue(WindowsHelloPublicKeyHash); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserWindowsHelloInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> WindowsHelloDeviceNameValue = obj->TryGetField(TEXT("WindowsHelloDeviceName")); if (WindowsHelloDeviceNameValue.IsValid() && !WindowsHelloDeviceNameValue->IsNull()) { FString TmpValue; if (WindowsHelloDeviceNameValue->TryGetString(TmpValue)) { WindowsHelloDeviceName = TmpValue; } } const TSharedPtr<FJsonValue> WindowsHelloPublicKeyHashValue = obj->TryGetField(TEXT("WindowsHelloPublicKeyHash")); if (WindowsHelloPublicKeyHashValue.IsValid() && !WindowsHelloPublicKeyHashValue->IsNull()) { FString TmpValue; if (WindowsHelloPublicKeyHashValue->TryGetString(TmpValue)) { WindowsHelloPublicKeyHash = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserXboxInfo::~FUserXboxInfo() { } void PlayFab::ServerModels::FUserXboxInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (XboxUserId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("XboxUserId")); writer->WriteValue(XboxUserId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserXboxInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> XboxUserIdValue = obj->TryGetField(TEXT("XboxUserId")); if (XboxUserIdValue.IsValid() && !XboxUserIdValue->IsNull()) { FString TmpValue; if (XboxUserIdValue->TryGetString(TmpValue)) { XboxUserId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUserAccountInfo::~FUserAccountInfo() { //if (AndroidDeviceInfo != nullptr) delete AndroidDeviceInfo; //if (CustomIdInfo != nullptr) delete CustomIdInfo; //if (FacebookInfo != nullptr) delete FacebookInfo; //if (FacebookInstantGamesIdInfo != nullptr) delete FacebookInstantGamesIdInfo; //if (GameCenterInfo != nullptr) delete GameCenterInfo; //if (GoogleInfo != nullptr) delete GoogleInfo; //if (IosDeviceInfo != nullptr) delete IosDeviceInfo; //if (KongregateInfo != nullptr) delete KongregateInfo; //if (NintendoSwitchDeviceIdInfo != nullptr) delete NintendoSwitchDeviceIdInfo; //if (PrivateInfo != nullptr) delete PrivateInfo; //if (PsnInfo != nullptr) delete PsnInfo; //if (SteamInfo != nullptr) delete SteamInfo; //if (TitleInfo != nullptr) delete TitleInfo; //if (TwitchInfo != nullptr) delete TwitchInfo; //if (WindowsHelloInfo != nullptr) delete WindowsHelloInfo; //if (XboxInfo != nullptr) delete XboxInfo; } void PlayFab::ServerModels::FUserAccountInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (AndroidDeviceInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("AndroidDeviceInfo")); AndroidDeviceInfo->writeJSON(writer); } writer->WriteIdentifierPrefix(TEXT("Created")); writeDatetime(Created, writer); if (CustomIdInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("CustomIdInfo")); CustomIdInfo->writeJSON(writer); } if (FacebookInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("FacebookInfo")); FacebookInfo->writeJSON(writer); } if (FacebookInstantGamesIdInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("FacebookInstantGamesIdInfo")); FacebookInstantGamesIdInfo->writeJSON(writer); } if (GameCenterInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("GameCenterInfo")); GameCenterInfo->writeJSON(writer); } if (GoogleInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("GoogleInfo")); GoogleInfo->writeJSON(writer); } if (IosDeviceInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("IosDeviceInfo")); IosDeviceInfo->writeJSON(writer); } if (KongregateInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("KongregateInfo")); KongregateInfo->writeJSON(writer); } if (NintendoSwitchDeviceIdInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("NintendoSwitchDeviceIdInfo")); NintendoSwitchDeviceIdInfo->writeJSON(writer); } if (OpenIdInfo.Num() != 0) { writer->WriteArrayStart(TEXT("OpenIdInfo")); for (const FUserOpenIdInfo& item : OpenIdInfo) item.writeJSON(writer); writer->WriteArrayEnd(); } if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } if (PrivateInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("PrivateInfo")); PrivateInfo->writeJSON(writer); } if (PsnInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("PsnInfo")); PsnInfo->writeJSON(writer); } if (SteamInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("SteamInfo")); SteamInfo->writeJSON(writer); } if (TitleInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("TitleInfo")); TitleInfo->writeJSON(writer); } if (TwitchInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("TwitchInfo")); TwitchInfo->writeJSON(writer); } if (Username.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Username")); writer->WriteValue(Username); } if (WindowsHelloInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("WindowsHelloInfo")); WindowsHelloInfo->writeJSON(writer); } if (XboxInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("XboxInfo")); XboxInfo->writeJSON(writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserAccountInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AndroidDeviceInfoValue = obj->TryGetField(TEXT("AndroidDeviceInfo")); if (AndroidDeviceInfoValue.IsValid() && !AndroidDeviceInfoValue->IsNull()) { AndroidDeviceInfo = MakeShareable(new FUserAndroidDeviceInfo(AndroidDeviceInfoValue->AsObject())); } const TSharedPtr<FJsonValue> CreatedValue = obj->TryGetField(TEXT("Created")); if (CreatedValue.IsValid()) Created = readDatetime(CreatedValue); const TSharedPtr<FJsonValue> CustomIdInfoValue = obj->TryGetField(TEXT("CustomIdInfo")); if (CustomIdInfoValue.IsValid() && !CustomIdInfoValue->IsNull()) { CustomIdInfo = MakeShareable(new FUserCustomIdInfo(CustomIdInfoValue->AsObject())); } const TSharedPtr<FJsonValue> FacebookInfoValue = obj->TryGetField(TEXT("FacebookInfo")); if (FacebookInfoValue.IsValid() && !FacebookInfoValue->IsNull()) { FacebookInfo = MakeShareable(new FUserFacebookInfo(FacebookInfoValue->AsObject())); } const TSharedPtr<FJsonValue> FacebookInstantGamesIdInfoValue = obj->TryGetField(TEXT("FacebookInstantGamesIdInfo")); if (FacebookInstantGamesIdInfoValue.IsValid() && !FacebookInstantGamesIdInfoValue->IsNull()) { FacebookInstantGamesIdInfo = MakeShareable(new FUserFacebookInstantGamesIdInfo(FacebookInstantGamesIdInfoValue->AsObject())); } const TSharedPtr<FJsonValue> GameCenterInfoValue = obj->TryGetField(TEXT("GameCenterInfo")); if (GameCenterInfoValue.IsValid() && !GameCenterInfoValue->IsNull()) { GameCenterInfo = MakeShareable(new FUserGameCenterInfo(GameCenterInfoValue->AsObject())); } const TSharedPtr<FJsonValue> GoogleInfoValue = obj->TryGetField(TEXT("GoogleInfo")); if (GoogleInfoValue.IsValid() && !GoogleInfoValue->IsNull()) { GoogleInfo = MakeShareable(new FUserGoogleInfo(GoogleInfoValue->AsObject())); } const TSharedPtr<FJsonValue> IosDeviceInfoValue = obj->TryGetField(TEXT("IosDeviceInfo")); if (IosDeviceInfoValue.IsValid() && !IosDeviceInfoValue->IsNull()) { IosDeviceInfo = MakeShareable(new FUserIosDeviceInfo(IosDeviceInfoValue->AsObject())); } const TSharedPtr<FJsonValue> KongregateInfoValue = obj->TryGetField(TEXT("KongregateInfo")); if (KongregateInfoValue.IsValid() && !KongregateInfoValue->IsNull()) { KongregateInfo = MakeShareable(new FUserKongregateInfo(KongregateInfoValue->AsObject())); } const TSharedPtr<FJsonValue> NintendoSwitchDeviceIdInfoValue = obj->TryGetField(TEXT("NintendoSwitchDeviceIdInfo")); if (NintendoSwitchDeviceIdInfoValue.IsValid() && !NintendoSwitchDeviceIdInfoValue->IsNull()) { NintendoSwitchDeviceIdInfo = MakeShareable(new FUserNintendoSwitchDeviceIdInfo(NintendoSwitchDeviceIdInfoValue->AsObject())); } const TArray<TSharedPtr<FJsonValue>>&OpenIdInfoArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("OpenIdInfo")); for (int32 Idx = 0; Idx < OpenIdInfoArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = OpenIdInfoArray[Idx]; OpenIdInfo.Add(FUserOpenIdInfo(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> PrivateInfoValue = obj->TryGetField(TEXT("PrivateInfo")); if (PrivateInfoValue.IsValid() && !PrivateInfoValue->IsNull()) { PrivateInfo = MakeShareable(new FUserPrivateAccountInfo(PrivateInfoValue->AsObject())); } const TSharedPtr<FJsonValue> PsnInfoValue = obj->TryGetField(TEXT("PsnInfo")); if (PsnInfoValue.IsValid() && !PsnInfoValue->IsNull()) { PsnInfo = MakeShareable(new FUserPsnInfo(PsnInfoValue->AsObject())); } const TSharedPtr<FJsonValue> SteamInfoValue = obj->TryGetField(TEXT("SteamInfo")); if (SteamInfoValue.IsValid() && !SteamInfoValue->IsNull()) { SteamInfo = MakeShareable(new FUserSteamInfo(SteamInfoValue->AsObject())); } const TSharedPtr<FJsonValue> TitleInfoValue = obj->TryGetField(TEXT("TitleInfo")); if (TitleInfoValue.IsValid() && !TitleInfoValue->IsNull()) { TitleInfo = MakeShareable(new FUserTitleInfo(TitleInfoValue->AsObject())); } const TSharedPtr<FJsonValue> TwitchInfoValue = obj->TryGetField(TEXT("TwitchInfo")); if (TwitchInfoValue.IsValid() && !TwitchInfoValue->IsNull()) { TwitchInfo = MakeShareable(new FUserTwitchInfo(TwitchInfoValue->AsObject())); } const TSharedPtr<FJsonValue> UsernameValue = obj->TryGetField(TEXT("Username")); if (UsernameValue.IsValid() && !UsernameValue->IsNull()) { FString TmpValue; if (UsernameValue->TryGetString(TmpValue)) { Username = TmpValue; } } const TSharedPtr<FJsonValue> WindowsHelloInfoValue = obj->TryGetField(TEXT("WindowsHelloInfo")); if (WindowsHelloInfoValue.IsValid() && !WindowsHelloInfoValue->IsNull()) { WindowsHelloInfo = MakeShareable(new FUserWindowsHelloInfo(WindowsHelloInfoValue->AsObject())); } const TSharedPtr<FJsonValue> XboxInfoValue = obj->TryGetField(TEXT("XboxInfo")); if (XboxInfoValue.IsValid() && !XboxInfoValue->IsNull()) { XboxInfo = MakeShareable(new FUserXboxInfo(XboxInfoValue->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FAuthenticateSessionTicketResult::~FAuthenticateSessionTicketResult() { //if (UserInfo != nullptr) delete UserInfo; } void PlayFab::ServerModels::FAuthenticateSessionTicketResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (UserInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("UserInfo")); UserInfo->writeJSON(writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAuthenticateSessionTicketResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> UserInfoValue = obj->TryGetField(TEXT("UserInfo")); if (UserInfoValue.IsValid() && !UserInfoValue->IsNull()) { UserInfo = MakeShareable(new FUserAccountInfo(UserInfoValue->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FAwardSteamAchievementItem::~FAwardSteamAchievementItem() { } void PlayFab::ServerModels::FAwardSteamAchievementItem::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("AchievementName")); writer->WriteValue(AchievementName); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("Result")); writer->WriteValue(Result); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAwardSteamAchievementItem::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AchievementNameValue = obj->TryGetField(TEXT("AchievementName")); if (AchievementNameValue.IsValid() && !AchievementNameValue->IsNull()) { FString TmpValue; if (AchievementNameValue->TryGetString(TmpValue)) { AchievementName = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> ResultValue = obj->TryGetField(TEXT("Result")); if (ResultValue.IsValid() && !ResultValue->IsNull()) { bool TmpValue; if (ResultValue->TryGetBool(TmpValue)) { Result = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FAwardSteamAchievementRequest::~FAwardSteamAchievementRequest() { } void PlayFab::ServerModels::FAwardSteamAchievementRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteArrayStart(TEXT("Achievements")); for (const FAwardSteamAchievementItem& item : Achievements) item.writeJSON(writer); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAwardSteamAchievementRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&AchievementsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Achievements")); for (int32 Idx = 0; Idx < AchievementsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = AchievementsArray[Idx]; Achievements.Add(FAwardSteamAchievementItem(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FAwardSteamAchievementResult::~FAwardSteamAchievementResult() { } void PlayFab::ServerModels::FAwardSteamAchievementResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (AchievementResults.Num() != 0) { writer->WriteArrayStart(TEXT("AchievementResults")); for (const FAwardSteamAchievementItem& item : AchievementResults) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FAwardSteamAchievementResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&AchievementResultsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("AchievementResults")); for (int32 Idx = 0; Idx < AchievementResultsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = AchievementResultsArray[Idx]; AchievementResults.Add(FAwardSteamAchievementItem(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FBanInfo::~FBanInfo() { } void PlayFab::ServerModels::FBanInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Active")); writer->WriteValue(Active); if (BanId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("BanId")); writer->WriteValue(BanId); } if (Created.notNull()) { writer->WriteIdentifierPrefix(TEXT("Created")); writeDatetime(Created, writer); } if (Expires.notNull()) { writer->WriteIdentifierPrefix(TEXT("Expires")); writeDatetime(Expires, writer); } if (IPAddress.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("IPAddress")); writer->WriteValue(IPAddress); } if (MACAddress.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("MACAddress")); writer->WriteValue(MACAddress); } if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } if (Reason.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Reason")); writer->WriteValue(Reason); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FBanInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ActiveValue = obj->TryGetField(TEXT("Active")); if (ActiveValue.IsValid() && !ActiveValue->IsNull()) { bool TmpValue; if (ActiveValue->TryGetBool(TmpValue)) { Active = TmpValue; } } const TSharedPtr<FJsonValue> BanIdValue = obj->TryGetField(TEXT("BanId")); if (BanIdValue.IsValid() && !BanIdValue->IsNull()) { FString TmpValue; if (BanIdValue->TryGetString(TmpValue)) { BanId = TmpValue; } } const TSharedPtr<FJsonValue> CreatedValue = obj->TryGetField(TEXT("Created")); if (CreatedValue.IsValid()) Created = readDatetime(CreatedValue); const TSharedPtr<FJsonValue> ExpiresValue = obj->TryGetField(TEXT("Expires")); if (ExpiresValue.IsValid()) Expires = readDatetime(ExpiresValue); const TSharedPtr<FJsonValue> IPAddressValue = obj->TryGetField(TEXT("IPAddress")); if (IPAddressValue.IsValid() && !IPAddressValue->IsNull()) { FString TmpValue; if (IPAddressValue->TryGetString(TmpValue)) { IPAddress = TmpValue; } } const TSharedPtr<FJsonValue> MACAddressValue = obj->TryGetField(TEXT("MACAddress")); if (MACAddressValue.IsValid() && !MACAddressValue->IsNull()) { FString TmpValue; if (MACAddressValue->TryGetString(TmpValue)) { MACAddress = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> ReasonValue = obj->TryGetField(TEXT("Reason")); if (ReasonValue.IsValid() && !ReasonValue->IsNull()) { FString TmpValue; if (ReasonValue->TryGetString(TmpValue)) { Reason = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FBanRequest::~FBanRequest() { } void PlayFab::ServerModels::FBanRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (DurationInHours.notNull()) { writer->WriteIdentifierPrefix(TEXT("DurationInHours")); writer->WriteValue(static_cast<int64>(DurationInHours)); } if (IPAddress.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("IPAddress")); writer->WriteValue(IPAddress); } if (MACAddress.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("MACAddress")); writer->WriteValue(MACAddress); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); if (Reason.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Reason")); writer->WriteValue(Reason); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FBanRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> DurationInHoursValue = obj->TryGetField(TEXT("DurationInHours")); if (DurationInHoursValue.IsValid() && !DurationInHoursValue->IsNull()) { uint32 TmpValue; if (DurationInHoursValue->TryGetNumber(TmpValue)) { DurationInHours = TmpValue; } } const TSharedPtr<FJsonValue> IPAddressValue = obj->TryGetField(TEXT("IPAddress")); if (IPAddressValue.IsValid() && !IPAddressValue->IsNull()) { FString TmpValue; if (IPAddressValue->TryGetString(TmpValue)) { IPAddress = TmpValue; } } const TSharedPtr<FJsonValue> MACAddressValue = obj->TryGetField(TEXT("MACAddress")); if (MACAddressValue.IsValid() && !MACAddressValue->IsNull()) { FString TmpValue; if (MACAddressValue->TryGetString(TmpValue)) { MACAddress = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> ReasonValue = obj->TryGetField(TEXT("Reason")); if (ReasonValue.IsValid() && !ReasonValue->IsNull()) { FString TmpValue; if (ReasonValue->TryGetString(TmpValue)) { Reason = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FBanUsersRequest::~FBanUsersRequest() { } void PlayFab::ServerModels::FBanUsersRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteArrayStart(TEXT("Bans")); for (const FBanRequest& item : Bans) item.writeJSON(writer); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FBanUsersRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&BansArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Bans")); for (int32 Idx = 0; Idx < BansArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = BansArray[Idx]; Bans.Add(FBanRequest(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FBanUsersResult::~FBanUsersResult() { } void PlayFab::ServerModels::FBanUsersResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (BanData.Num() != 0) { writer->WriteArrayStart(TEXT("BanData")); for (const FBanInfo& item : BanData) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FBanUsersResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&BanDataArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("BanData")); for (int32 Idx = 0; Idx < BanDataArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = BanDataArray[Idx]; BanData.Add(FBanInfo(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FCatalogItemBundleInfo::~FCatalogItemBundleInfo() { } void PlayFab::ServerModels::FCatalogItemBundleInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (BundledItems.Num() != 0) { writer->WriteArrayStart(TEXT("BundledItems")); for (const FString& item : BundledItems) writer->WriteValue(item); writer->WriteArrayEnd(); } if (BundledResultTables.Num() != 0) { writer->WriteArrayStart(TEXT("BundledResultTables")); for (const FString& item : BundledResultTables) writer->WriteValue(item); writer->WriteArrayEnd(); } if (BundledVirtualCurrencies.Num() != 0) { writer->WriteObjectStart(TEXT("BundledVirtualCurrencies")); for (TMap<FString, uint32>::TConstIterator It(BundledVirtualCurrencies); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue(static_cast<int64>((*It).Value)); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FCatalogItemBundleInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; obj->TryGetStringArrayField(TEXT("BundledItems"), BundledItems); obj->TryGetStringArrayField(TEXT("BundledResultTables"), BundledResultTables); const TSharedPtr<FJsonObject>* BundledVirtualCurrenciesObject; if (obj->TryGetObjectField(TEXT("BundledVirtualCurrencies"), BundledVirtualCurrenciesObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*BundledVirtualCurrenciesObject)->Values); It; ++It) { uint32 TmpValue; It.Value()->TryGetNumber(TmpValue); BundledVirtualCurrencies.Add(It.Key(), TmpValue); } } return HasSucceeded; } PlayFab::ServerModels::FCatalogItemConsumableInfo::~FCatalogItemConsumableInfo() { } void PlayFab::ServerModels::FCatalogItemConsumableInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (UsageCount.notNull()) { writer->WriteIdentifierPrefix(TEXT("UsageCount")); writer->WriteValue(static_cast<int64>(UsageCount)); } if (UsagePeriod.notNull()) { writer->WriteIdentifierPrefix(TEXT("UsagePeriod")); writer->WriteValue(static_cast<int64>(UsagePeriod)); } if (UsagePeriodGroup.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("UsagePeriodGroup")); writer->WriteValue(UsagePeriodGroup); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FCatalogItemConsumableInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> UsageCountValue = obj->TryGetField(TEXT("UsageCount")); if (UsageCountValue.IsValid() && !UsageCountValue->IsNull()) { uint32 TmpValue; if (UsageCountValue->TryGetNumber(TmpValue)) { UsageCount = TmpValue; } } const TSharedPtr<FJsonValue> UsagePeriodValue = obj->TryGetField(TEXT("UsagePeriod")); if (UsagePeriodValue.IsValid() && !UsagePeriodValue->IsNull()) { uint32 TmpValue; if (UsagePeriodValue->TryGetNumber(TmpValue)) { UsagePeriod = TmpValue; } } const TSharedPtr<FJsonValue> UsagePeriodGroupValue = obj->TryGetField(TEXT("UsagePeriodGroup")); if (UsagePeriodGroupValue.IsValid() && !UsagePeriodGroupValue->IsNull()) { FString TmpValue; if (UsagePeriodGroupValue->TryGetString(TmpValue)) { UsagePeriodGroup = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FCatalogItemContainerInfo::~FCatalogItemContainerInfo() { } void PlayFab::ServerModels::FCatalogItemContainerInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (ItemContents.Num() != 0) { writer->WriteArrayStart(TEXT("ItemContents")); for (const FString& item : ItemContents) writer->WriteValue(item); writer->WriteArrayEnd(); } if (KeyItemId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("KeyItemId")); writer->WriteValue(KeyItemId); } if (ResultTableContents.Num() != 0) { writer->WriteArrayStart(TEXT("ResultTableContents")); for (const FString& item : ResultTableContents) writer->WriteValue(item); writer->WriteArrayEnd(); } if (VirtualCurrencyContents.Num() != 0) { writer->WriteObjectStart(TEXT("VirtualCurrencyContents")); for (TMap<FString, uint32>::TConstIterator It(VirtualCurrencyContents); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue(static_cast<int64>((*It).Value)); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FCatalogItemContainerInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; obj->TryGetStringArrayField(TEXT("ItemContents"), ItemContents); const TSharedPtr<FJsonValue> KeyItemIdValue = obj->TryGetField(TEXT("KeyItemId")); if (KeyItemIdValue.IsValid() && !KeyItemIdValue->IsNull()) { FString TmpValue; if (KeyItemIdValue->TryGetString(TmpValue)) { KeyItemId = TmpValue; } } obj->TryGetStringArrayField(TEXT("ResultTableContents"), ResultTableContents); const TSharedPtr<FJsonObject>* VirtualCurrencyContentsObject; if (obj->TryGetObjectField(TEXT("VirtualCurrencyContents"), VirtualCurrencyContentsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*VirtualCurrencyContentsObject)->Values); It; ++It) { uint32 TmpValue; It.Value()->TryGetNumber(TmpValue); VirtualCurrencyContents.Add(It.Key(), TmpValue); } } return HasSucceeded; } PlayFab::ServerModels::FCatalogItem::~FCatalogItem() { //if (Bundle != nullptr) delete Bundle; //if (Consumable != nullptr) delete Consumable; //if (Container != nullptr) delete Container; } void PlayFab::ServerModels::FCatalogItem::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Bundle.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Bundle")); Bundle->writeJSON(writer); } writer->WriteIdentifierPrefix(TEXT("CanBecomeCharacter")); writer->WriteValue(CanBecomeCharacter); if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } if (Consumable.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Consumable")); Consumable->writeJSON(writer); } if (Container.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Container")); Container->writeJSON(writer); } if (CustomData.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CustomData")); writer->WriteValue(CustomData); } if (Description.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Description")); writer->WriteValue(Description); } if (DisplayName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("DisplayName")); writer->WriteValue(DisplayName); } writer->WriteIdentifierPrefix(TEXT("InitialLimitedEditionCount")); writer->WriteValue(InitialLimitedEditionCount); writer->WriteIdentifierPrefix(TEXT("IsLimitedEdition")); writer->WriteValue(IsLimitedEdition); writer->WriteIdentifierPrefix(TEXT("IsStackable")); writer->WriteValue(IsStackable); writer->WriteIdentifierPrefix(TEXT("IsTradable")); writer->WriteValue(IsTradable); if (ItemClass.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ItemClass")); writer->WriteValue(ItemClass); } writer->WriteIdentifierPrefix(TEXT("ItemId")); writer->WriteValue(ItemId); if (ItemImageUrl.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ItemImageUrl")); writer->WriteValue(ItemImageUrl); } if (RealCurrencyPrices.Num() != 0) { writer->WriteObjectStart(TEXT("RealCurrencyPrices")); for (TMap<FString, uint32>::TConstIterator It(RealCurrencyPrices); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue(static_cast<int64>((*It).Value)); } writer->WriteObjectEnd(); } if (Tags.Num() != 0) { writer->WriteArrayStart(TEXT("Tags")); for (const FString& item : Tags) writer->WriteValue(item); writer->WriteArrayEnd(); } if (VirtualCurrencyPrices.Num() != 0) { writer->WriteObjectStart(TEXT("VirtualCurrencyPrices")); for (TMap<FString, uint32>::TConstIterator It(VirtualCurrencyPrices); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue(static_cast<int64>((*It).Value)); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FCatalogItem::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> BundleValue = obj->TryGetField(TEXT("Bundle")); if (BundleValue.IsValid() && !BundleValue->IsNull()) { Bundle = MakeShareable(new FCatalogItemBundleInfo(BundleValue->AsObject())); } const TSharedPtr<FJsonValue> CanBecomeCharacterValue = obj->TryGetField(TEXT("CanBecomeCharacter")); if (CanBecomeCharacterValue.IsValid() && !CanBecomeCharacterValue->IsNull()) { bool TmpValue; if (CanBecomeCharacterValue->TryGetBool(TmpValue)) { CanBecomeCharacter = TmpValue; } } const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } const TSharedPtr<FJsonValue> ConsumableValue = obj->TryGetField(TEXT("Consumable")); if (ConsumableValue.IsValid() && !ConsumableValue->IsNull()) { Consumable = MakeShareable(new FCatalogItemConsumableInfo(ConsumableValue->AsObject())); } const TSharedPtr<FJsonValue> ContainerValue = obj->TryGetField(TEXT("Container")); if (ContainerValue.IsValid() && !ContainerValue->IsNull()) { Container = MakeShareable(new FCatalogItemContainerInfo(ContainerValue->AsObject())); } const TSharedPtr<FJsonValue> CustomDataValue = obj->TryGetField(TEXT("CustomData")); if (CustomDataValue.IsValid() && !CustomDataValue->IsNull()) { FString TmpValue; if (CustomDataValue->TryGetString(TmpValue)) { CustomData = TmpValue; } } const TSharedPtr<FJsonValue> DescriptionValue = obj->TryGetField(TEXT("Description")); if (DescriptionValue.IsValid() && !DescriptionValue->IsNull()) { FString TmpValue; if (DescriptionValue->TryGetString(TmpValue)) { Description = TmpValue; } } const TSharedPtr<FJsonValue> DisplayNameValue = obj->TryGetField(TEXT("DisplayName")); if (DisplayNameValue.IsValid() && !DisplayNameValue->IsNull()) { FString TmpValue; if (DisplayNameValue->TryGetString(TmpValue)) { DisplayName = TmpValue; } } const TSharedPtr<FJsonValue> InitialLimitedEditionCountValue = obj->TryGetField(TEXT("InitialLimitedEditionCount")); if (InitialLimitedEditionCountValue.IsValid() && !InitialLimitedEditionCountValue->IsNull()) { int32 TmpValue; if (InitialLimitedEditionCountValue->TryGetNumber(TmpValue)) { InitialLimitedEditionCount = TmpValue; } } const TSharedPtr<FJsonValue> IsLimitedEditionValue = obj->TryGetField(TEXT("IsLimitedEdition")); if (IsLimitedEditionValue.IsValid() && !IsLimitedEditionValue->IsNull()) { bool TmpValue; if (IsLimitedEditionValue->TryGetBool(TmpValue)) { IsLimitedEdition = TmpValue; } } const TSharedPtr<FJsonValue> IsStackableValue = obj->TryGetField(TEXT("IsStackable")); if (IsStackableValue.IsValid() && !IsStackableValue->IsNull()) { bool TmpValue; if (IsStackableValue->TryGetBool(TmpValue)) { IsStackable = TmpValue; } } const TSharedPtr<FJsonValue> IsTradableValue = obj->TryGetField(TEXT("IsTradable")); if (IsTradableValue.IsValid() && !IsTradableValue->IsNull()) { bool TmpValue; if (IsTradableValue->TryGetBool(TmpValue)) { IsTradable = TmpValue; } } const TSharedPtr<FJsonValue> ItemClassValue = obj->TryGetField(TEXT("ItemClass")); if (ItemClassValue.IsValid() && !ItemClassValue->IsNull()) { FString TmpValue; if (ItemClassValue->TryGetString(TmpValue)) { ItemClass = TmpValue; } } const TSharedPtr<FJsonValue> ItemIdValue = obj->TryGetField(TEXT("ItemId")); if (ItemIdValue.IsValid() && !ItemIdValue->IsNull()) { FString TmpValue; if (ItemIdValue->TryGetString(TmpValue)) { ItemId = TmpValue; } } const TSharedPtr<FJsonValue> ItemImageUrlValue = obj->TryGetField(TEXT("ItemImageUrl")); if (ItemImageUrlValue.IsValid() && !ItemImageUrlValue->IsNull()) { FString TmpValue; if (ItemImageUrlValue->TryGetString(TmpValue)) { ItemImageUrl = TmpValue; } } const TSharedPtr<FJsonObject>* RealCurrencyPricesObject; if (obj->TryGetObjectField(TEXT("RealCurrencyPrices"), RealCurrencyPricesObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*RealCurrencyPricesObject)->Values); It; ++It) { uint32 TmpValue; It.Value()->TryGetNumber(TmpValue); RealCurrencyPrices.Add(It.Key(), TmpValue); } } obj->TryGetStringArrayField(TEXT("Tags"), Tags); const TSharedPtr<FJsonObject>* VirtualCurrencyPricesObject; if (obj->TryGetObjectField(TEXT("VirtualCurrencyPrices"), VirtualCurrencyPricesObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*VirtualCurrencyPricesObject)->Values); It; ++It) { uint32 TmpValue; It.Value()->TryGetNumber(TmpValue); VirtualCurrencyPrices.Add(It.Key(), TmpValue); } } return HasSucceeded; } PlayFab::ServerModels::FItemInstance::~FItemInstance() { } void PlayFab::ServerModels::FItemInstance::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Annotation.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Annotation")); writer->WriteValue(Annotation); } if (BundleContents.Num() != 0) { writer->WriteArrayStart(TEXT("BundleContents")); for (const FString& item : BundleContents) writer->WriteValue(item); writer->WriteArrayEnd(); } if (BundleParent.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("BundleParent")); writer->WriteValue(BundleParent); } if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } if (CustomData.Num() != 0) { writer->WriteObjectStart(TEXT("CustomData")); for (TMap<FString, FString>::TConstIterator It(CustomData); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (DisplayName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("DisplayName")); writer->WriteValue(DisplayName); } if (Expiration.notNull()) { writer->WriteIdentifierPrefix(TEXT("Expiration")); writeDatetime(Expiration, writer); } if (ItemClass.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ItemClass")); writer->WriteValue(ItemClass); } if (ItemId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ItemId")); writer->WriteValue(ItemId); } if (ItemInstanceId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ItemInstanceId")); writer->WriteValue(ItemInstanceId); } if (PurchaseDate.notNull()) { writer->WriteIdentifierPrefix(TEXT("PurchaseDate")); writeDatetime(PurchaseDate, writer); } if (RemainingUses.notNull()) { writer->WriteIdentifierPrefix(TEXT("RemainingUses")); writer->WriteValue(RemainingUses); } if (UnitCurrency.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("UnitCurrency")); writer->WriteValue(UnitCurrency); } writer->WriteIdentifierPrefix(TEXT("UnitPrice")); writer->WriteValue(static_cast<int64>(UnitPrice)); if (UsesIncrementedBy.notNull()) { writer->WriteIdentifierPrefix(TEXT("UsesIncrementedBy")); writer->WriteValue(UsesIncrementedBy); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FItemInstance::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AnnotationValue = obj->TryGetField(TEXT("Annotation")); if (AnnotationValue.IsValid() && !AnnotationValue->IsNull()) { FString TmpValue; if (AnnotationValue->TryGetString(TmpValue)) { Annotation = TmpValue; } } obj->TryGetStringArrayField(TEXT("BundleContents"), BundleContents); const TSharedPtr<FJsonValue> BundleParentValue = obj->TryGetField(TEXT("BundleParent")); if (BundleParentValue.IsValid() && !BundleParentValue->IsNull()) { FString TmpValue; if (BundleParentValue->TryGetString(TmpValue)) { BundleParent = TmpValue; } } const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } const TSharedPtr<FJsonObject>* CustomDataObject; if (obj->TryGetObjectField(TEXT("CustomData"), CustomDataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*CustomDataObject)->Values); It; ++It) { CustomData.Add(It.Key(), It.Value()->AsString()); } } const TSharedPtr<FJsonValue> DisplayNameValue = obj->TryGetField(TEXT("DisplayName")); if (DisplayNameValue.IsValid() && !DisplayNameValue->IsNull()) { FString TmpValue; if (DisplayNameValue->TryGetString(TmpValue)) { DisplayName = TmpValue; } } const TSharedPtr<FJsonValue> ExpirationValue = obj->TryGetField(TEXT("Expiration")); if (ExpirationValue.IsValid()) Expiration = readDatetime(ExpirationValue); const TSharedPtr<FJsonValue> ItemClassValue = obj->TryGetField(TEXT("ItemClass")); if (ItemClassValue.IsValid() && !ItemClassValue->IsNull()) { FString TmpValue; if (ItemClassValue->TryGetString(TmpValue)) { ItemClass = TmpValue; } } const TSharedPtr<FJsonValue> ItemIdValue = obj->TryGetField(TEXT("ItemId")); if (ItemIdValue.IsValid() && !ItemIdValue->IsNull()) { FString TmpValue; if (ItemIdValue->TryGetString(TmpValue)) { ItemId = TmpValue; } } const TSharedPtr<FJsonValue> ItemInstanceIdValue = obj->TryGetField(TEXT("ItemInstanceId")); if (ItemInstanceIdValue.IsValid() && !ItemInstanceIdValue->IsNull()) { FString TmpValue; if (ItemInstanceIdValue->TryGetString(TmpValue)) { ItemInstanceId = TmpValue; } } const TSharedPtr<FJsonValue> PurchaseDateValue = obj->TryGetField(TEXT("PurchaseDate")); if (PurchaseDateValue.IsValid()) PurchaseDate = readDatetime(PurchaseDateValue); const TSharedPtr<FJsonValue> RemainingUsesValue = obj->TryGetField(TEXT("RemainingUses")); if (RemainingUsesValue.IsValid() && !RemainingUsesValue->IsNull()) { int32 TmpValue; if (RemainingUsesValue->TryGetNumber(TmpValue)) { RemainingUses = TmpValue; } } const TSharedPtr<FJsonValue> UnitCurrencyValue = obj->TryGetField(TEXT("UnitCurrency")); if (UnitCurrencyValue.IsValid() && !UnitCurrencyValue->IsNull()) { FString TmpValue; if (UnitCurrencyValue->TryGetString(TmpValue)) { UnitCurrency = TmpValue; } } const TSharedPtr<FJsonValue> UnitPriceValue = obj->TryGetField(TEXT("UnitPrice")); if (UnitPriceValue.IsValid() && !UnitPriceValue->IsNull()) { uint32 TmpValue; if (UnitPriceValue->TryGetNumber(TmpValue)) { UnitPrice = TmpValue; } } const TSharedPtr<FJsonValue> UsesIncrementedByValue = obj->TryGetField(TEXT("UsesIncrementedBy")); if (UsesIncrementedByValue.IsValid() && !UsesIncrementedByValue->IsNull()) { int32 TmpValue; if (UsesIncrementedByValue->TryGetNumber(TmpValue)) { UsesIncrementedBy = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FCharacterInventory::~FCharacterInventory() { } void PlayFab::ServerModels::FCharacterInventory::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } if (Inventory.Num() != 0) { writer->WriteArrayStart(TEXT("Inventory")); for (const FItemInstance& item : Inventory) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FCharacterInventory::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&InventoryArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Inventory")); for (int32 Idx = 0; Idx < InventoryArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = InventoryArray[Idx]; Inventory.Add(FItemInstance(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FCharacterLeaderboardEntry::~FCharacterLeaderboardEntry() { } void PlayFab::ServerModels::FCharacterLeaderboardEntry::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } if (CharacterName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterName")); writer->WriteValue(CharacterName); } if (CharacterType.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterType")); writer->WriteValue(CharacterType); } if (DisplayName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("DisplayName")); writer->WriteValue(DisplayName); } if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } writer->WriteIdentifierPrefix(TEXT("Position")); writer->WriteValue(Position); writer->WriteIdentifierPrefix(TEXT("StatValue")); writer->WriteValue(StatValue); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FCharacterLeaderboardEntry::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> CharacterNameValue = obj->TryGetField(TEXT("CharacterName")); if (CharacterNameValue.IsValid() && !CharacterNameValue->IsNull()) { FString TmpValue; if (CharacterNameValue->TryGetString(TmpValue)) { CharacterName = TmpValue; } } const TSharedPtr<FJsonValue> CharacterTypeValue = obj->TryGetField(TEXT("CharacterType")); if (CharacterTypeValue.IsValid() && !CharacterTypeValue->IsNull()) { FString TmpValue; if (CharacterTypeValue->TryGetString(TmpValue)) { CharacterType = TmpValue; } } const TSharedPtr<FJsonValue> DisplayNameValue = obj->TryGetField(TEXT("DisplayName")); if (DisplayNameValue.IsValid() && !DisplayNameValue->IsNull()) { FString TmpValue; if (DisplayNameValue->TryGetString(TmpValue)) { DisplayName = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> PositionValue = obj->TryGetField(TEXT("Position")); if (PositionValue.IsValid() && !PositionValue->IsNull()) { int32 TmpValue; if (PositionValue->TryGetNumber(TmpValue)) { Position = TmpValue; } } const TSharedPtr<FJsonValue> StatValueValue = obj->TryGetField(TEXT("StatValue")); if (StatValueValue.IsValid() && !StatValueValue->IsNull()) { int32 TmpValue; if (StatValueValue->TryGetNumber(TmpValue)) { StatValue = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FCharacterResult::~FCharacterResult() { } void PlayFab::ServerModels::FCharacterResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } if (CharacterName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterName")); writer->WriteValue(CharacterName); } if (CharacterType.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterType")); writer->WriteValue(CharacterType); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FCharacterResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> CharacterNameValue = obj->TryGetField(TEXT("CharacterName")); if (CharacterNameValue.IsValid() && !CharacterNameValue->IsNull()) { FString TmpValue; if (CharacterNameValue->TryGetString(TmpValue)) { CharacterName = TmpValue; } } const TSharedPtr<FJsonValue> CharacterTypeValue = obj->TryGetField(TEXT("CharacterType")); if (CharacterTypeValue.IsValid() && !CharacterTypeValue->IsNull()) { FString TmpValue; if (CharacterTypeValue->TryGetString(TmpValue)) { CharacterType = TmpValue; } } return HasSucceeded; } void PlayFab::ServerModels::writeCloudScriptRevisionOptionEnumJSON(CloudScriptRevisionOption enumVal, JsonWriter& writer) { switch (enumVal) { case CloudScriptRevisionOptionLive: writer->WriteValue(TEXT("Live")); break; case CloudScriptRevisionOptionLatest: writer->WriteValue(TEXT("Latest")); break; case CloudScriptRevisionOptionSpecific: writer->WriteValue(TEXT("Specific")); break; } } ServerModels::CloudScriptRevisionOption PlayFab::ServerModels::readCloudScriptRevisionOptionFromValue(const TSharedPtr<FJsonValue>& value) { return readCloudScriptRevisionOptionFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::CloudScriptRevisionOption PlayFab::ServerModels::readCloudScriptRevisionOptionFromValue(const FString& value) { static TMap<FString, CloudScriptRevisionOption> _CloudScriptRevisionOptionMap; if (_CloudScriptRevisionOptionMap.Num() == 0) { // Auto-generate the map on the first use _CloudScriptRevisionOptionMap.Add(TEXT("Live"), CloudScriptRevisionOptionLive); _CloudScriptRevisionOptionMap.Add(TEXT("Latest"), CloudScriptRevisionOptionLatest); _CloudScriptRevisionOptionMap.Add(TEXT("Specific"), CloudScriptRevisionOptionSpecific); } if (!value.IsEmpty()) { auto output = _CloudScriptRevisionOptionMap.Find(value); if (output != nullptr) return *output; } return CloudScriptRevisionOptionLive; // Basically critical fail } PlayFab::ServerModels::FConsumeItemRequest::~FConsumeItemRequest() { } void PlayFab::ServerModels::FConsumeItemRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } writer->WriteIdentifierPrefix(TEXT("ConsumeCount")); writer->WriteValue(ConsumeCount); writer->WriteIdentifierPrefix(TEXT("ItemInstanceId")); writer->WriteValue(ItemInstanceId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FConsumeItemRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> ConsumeCountValue = obj->TryGetField(TEXT("ConsumeCount")); if (ConsumeCountValue.IsValid() && !ConsumeCountValue->IsNull()) { int32 TmpValue; if (ConsumeCountValue->TryGetNumber(TmpValue)) { ConsumeCount = TmpValue; } } const TSharedPtr<FJsonValue> ItemInstanceIdValue = obj->TryGetField(TEXT("ItemInstanceId")); if (ItemInstanceIdValue.IsValid() && !ItemInstanceIdValue->IsNull()) { FString TmpValue; if (ItemInstanceIdValue->TryGetString(TmpValue)) { ItemInstanceId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FConsumeItemResult::~FConsumeItemResult() { } void PlayFab::ServerModels::FConsumeItemResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (ItemInstanceId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ItemInstanceId")); writer->WriteValue(ItemInstanceId); } writer->WriteIdentifierPrefix(TEXT("RemainingUses")); writer->WriteValue(RemainingUses); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FConsumeItemResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ItemInstanceIdValue = obj->TryGetField(TEXT("ItemInstanceId")); if (ItemInstanceIdValue.IsValid() && !ItemInstanceIdValue->IsNull()) { FString TmpValue; if (ItemInstanceIdValue->TryGetString(TmpValue)) { ItemInstanceId = TmpValue; } } const TSharedPtr<FJsonValue> RemainingUsesValue = obj->TryGetField(TEXT("RemainingUses")); if (RemainingUsesValue.IsValid() && !RemainingUsesValue->IsNull()) { int32 TmpValue; if (RemainingUsesValue->TryGetNumber(TmpValue)) { RemainingUses = TmpValue; } } return HasSucceeded; } void PlayFab::ServerModels::writeEmailVerificationStatusEnumJSON(EmailVerificationStatus enumVal, JsonWriter& writer) { switch (enumVal) { case EmailVerificationStatusUnverified: writer->WriteValue(TEXT("Unverified")); break; case EmailVerificationStatusPending: writer->WriteValue(TEXT("Pending")); break; case EmailVerificationStatusConfirmed: writer->WriteValue(TEXT("Confirmed")); break; } } ServerModels::EmailVerificationStatus PlayFab::ServerModels::readEmailVerificationStatusFromValue(const TSharedPtr<FJsonValue>& value) { return readEmailVerificationStatusFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::EmailVerificationStatus PlayFab::ServerModels::readEmailVerificationStatusFromValue(const FString& value) { static TMap<FString, EmailVerificationStatus> _EmailVerificationStatusMap; if (_EmailVerificationStatusMap.Num() == 0) { // Auto-generate the map on the first use _EmailVerificationStatusMap.Add(TEXT("Unverified"), EmailVerificationStatusUnverified); _EmailVerificationStatusMap.Add(TEXT("Pending"), EmailVerificationStatusPending); _EmailVerificationStatusMap.Add(TEXT("Confirmed"), EmailVerificationStatusConfirmed); } if (!value.IsEmpty()) { auto output = _EmailVerificationStatusMap.Find(value); if (output != nullptr) return *output; } return EmailVerificationStatusUnverified; // Basically critical fail } PlayFab::ServerModels::FContactEmailInfo::~FContactEmailInfo() { } void PlayFab::ServerModels::FContactEmailInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (EmailAddress.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("EmailAddress")); writer->WriteValue(EmailAddress); } if (Name.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Name")); writer->WriteValue(Name); } if (VerificationStatus.notNull()) { writer->WriteIdentifierPrefix(TEXT("VerificationStatus")); writeEmailVerificationStatusEnumJSON(VerificationStatus, writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FContactEmailInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> EmailAddressValue = obj->TryGetField(TEXT("EmailAddress")); if (EmailAddressValue.IsValid() && !EmailAddressValue->IsNull()) { FString TmpValue; if (EmailAddressValue->TryGetString(TmpValue)) { EmailAddress = TmpValue; } } const TSharedPtr<FJsonValue> NameValue = obj->TryGetField(TEXT("Name")); if (NameValue.IsValid() && !NameValue->IsNull()) { FString TmpValue; if (NameValue->TryGetString(TmpValue)) { Name = TmpValue; } } VerificationStatus = readEmailVerificationStatusFromValue(obj->TryGetField(TEXT("VerificationStatus"))); return HasSucceeded; } PlayFab::ServerModels::FContactEmailInfoModel::~FContactEmailInfoModel() { } void PlayFab::ServerModels::FContactEmailInfoModel::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (EmailAddress.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("EmailAddress")); writer->WriteValue(EmailAddress); } if (Name.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Name")); writer->WriteValue(Name); } if (VerificationStatus.notNull()) { writer->WriteIdentifierPrefix(TEXT("VerificationStatus")); writeEmailVerificationStatusEnumJSON(VerificationStatus, writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FContactEmailInfoModel::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> EmailAddressValue = obj->TryGetField(TEXT("EmailAddress")); if (EmailAddressValue.IsValid() && !EmailAddressValue->IsNull()) { FString TmpValue; if (EmailAddressValue->TryGetString(TmpValue)) { EmailAddress = TmpValue; } } const TSharedPtr<FJsonValue> NameValue = obj->TryGetField(TEXT("Name")); if (NameValue.IsValid() && !NameValue->IsNull()) { FString TmpValue; if (NameValue->TryGetString(TmpValue)) { Name = TmpValue; } } VerificationStatus = readEmailVerificationStatusFromValue(obj->TryGetField(TEXT("VerificationStatus"))); return HasSucceeded; } void PlayFab::ServerModels::writeContinentCodeEnumJSON(ContinentCode enumVal, JsonWriter& writer) { switch (enumVal) { case ContinentCodeAF: writer->WriteValue(TEXT("AF")); break; case ContinentCodeAN: writer->WriteValue(TEXT("AN")); break; case ContinentCodeAS: writer->WriteValue(TEXT("AS")); break; case ContinentCodeEU: writer->WriteValue(TEXT("EU")); break; case ContinentCodeNA: writer->WriteValue(TEXT("NA")); break; case ContinentCodeOC: writer->WriteValue(TEXT("OC")); break; case ContinentCodeSA: writer->WriteValue(TEXT("SA")); break; } } ServerModels::ContinentCode PlayFab::ServerModels::readContinentCodeFromValue(const TSharedPtr<FJsonValue>& value) { return readContinentCodeFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::ContinentCode PlayFab::ServerModels::readContinentCodeFromValue(const FString& value) { static TMap<FString, ContinentCode> _ContinentCodeMap; if (_ContinentCodeMap.Num() == 0) { // Auto-generate the map on the first use _ContinentCodeMap.Add(TEXT("AF"), ContinentCodeAF); _ContinentCodeMap.Add(TEXT("AN"), ContinentCodeAN); _ContinentCodeMap.Add(TEXT("AS"), ContinentCodeAS); _ContinentCodeMap.Add(TEXT("EU"), ContinentCodeEU); _ContinentCodeMap.Add(TEXT("NA"), ContinentCodeNA); _ContinentCodeMap.Add(TEXT("OC"), ContinentCodeOC); _ContinentCodeMap.Add(TEXT("SA"), ContinentCodeSA); } if (!value.IsEmpty()) { auto output = _ContinentCodeMap.Find(value); if (output != nullptr) return *output; } return ContinentCodeAF; // Basically critical fail } void PlayFab::ServerModels::writeCountryCodeEnumJSON(CountryCode enumVal, JsonWriter& writer) { switch (enumVal) { case CountryCodeAF: writer->WriteValue(TEXT("AF")); break; case CountryCodeAX: writer->WriteValue(TEXT("AX")); break; case CountryCodeAL: writer->WriteValue(TEXT("AL")); break; case CountryCodeDZ: writer->WriteValue(TEXT("DZ")); break; case CountryCodeAS: writer->WriteValue(TEXT("AS")); break; case CountryCodeAD: writer->WriteValue(TEXT("AD")); break; case CountryCodeAO: writer->WriteValue(TEXT("AO")); break; case CountryCodeAI: writer->WriteValue(TEXT("AI")); break; case CountryCodeAQ: writer->WriteValue(TEXT("AQ")); break; case CountryCodeAG: writer->WriteValue(TEXT("AG")); break; case CountryCodeAR: writer->WriteValue(TEXT("AR")); break; case CountryCodeAM: writer->WriteValue(TEXT("AM")); break; case CountryCodeAW: writer->WriteValue(TEXT("AW")); break; case CountryCodeAU: writer->WriteValue(TEXT("AU")); break; case CountryCodeAT: writer->WriteValue(TEXT("AT")); break; case CountryCodeAZ: writer->WriteValue(TEXT("AZ")); break; case CountryCodeBS: writer->WriteValue(TEXT("BS")); break; case CountryCodeBH: writer->WriteValue(TEXT("BH")); break; case CountryCodeBD: writer->WriteValue(TEXT("BD")); break; case CountryCodeBB: writer->WriteValue(TEXT("BB")); break; case CountryCodeBY: writer->WriteValue(TEXT("BY")); break; case CountryCodeBE: writer->WriteValue(TEXT("BE")); break; case CountryCodeBZ: writer->WriteValue(TEXT("BZ")); break; case CountryCodeBJ: writer->WriteValue(TEXT("BJ")); break; case CountryCodeBM: writer->WriteValue(TEXT("BM")); break; case CountryCodeBT: writer->WriteValue(TEXT("BT")); break; case CountryCodeBO: writer->WriteValue(TEXT("BO")); break; case CountryCodeBQ: writer->WriteValue(TEXT("BQ")); break; case CountryCodeBA: writer->WriteValue(TEXT("BA")); break; case CountryCodeBW: writer->WriteValue(TEXT("BW")); break; case CountryCodeBV: writer->WriteValue(TEXT("BV")); break; case CountryCodeBR: writer->WriteValue(TEXT("BR")); break; case CountryCodeIO: writer->WriteValue(TEXT("IO")); break; case CountryCodeBN: writer->WriteValue(TEXT("BN")); break; case CountryCodeBG: writer->WriteValue(TEXT("BG")); break; case CountryCodeBF: writer->WriteValue(TEXT("BF")); break; case CountryCodeBI: writer->WriteValue(TEXT("BI")); break; case CountryCodeKH: writer->WriteValue(TEXT("KH")); break; case CountryCodeCM: writer->WriteValue(TEXT("CM")); break; case CountryCodeCA: writer->WriteValue(TEXT("CA")); break; case CountryCodeCV: writer->WriteValue(TEXT("CV")); break; case CountryCodeKY: writer->WriteValue(TEXT("KY")); break; case CountryCodeCF: writer->WriteValue(TEXT("CF")); break; case CountryCodeTD: writer->WriteValue(TEXT("TD")); break; case CountryCodeCL: writer->WriteValue(TEXT("CL")); break; case CountryCodeCN: writer->WriteValue(TEXT("CN")); break; case CountryCodeCX: writer->WriteValue(TEXT("CX")); break; case CountryCodeCC: writer->WriteValue(TEXT("CC")); break; case CountryCodeCO: writer->WriteValue(TEXT("CO")); break; case CountryCodeKM: writer->WriteValue(TEXT("KM")); break; case CountryCodeCG: writer->WriteValue(TEXT("CG")); break; case CountryCodeCD: writer->WriteValue(TEXT("CD")); break; case CountryCodeCK: writer->WriteValue(TEXT("CK")); break; case CountryCodeCR: writer->WriteValue(TEXT("CR")); break; case CountryCodeCI: writer->WriteValue(TEXT("CI")); break; case CountryCodeHR: writer->WriteValue(TEXT("HR")); break; case CountryCodeCU: writer->WriteValue(TEXT("CU")); break; case CountryCodeCW: writer->WriteValue(TEXT("CW")); break; case CountryCodeCY: writer->WriteValue(TEXT("CY")); break; case CountryCodeCZ: writer->WriteValue(TEXT("CZ")); break; case CountryCodeDK: writer->WriteValue(TEXT("DK")); break; case CountryCodeDJ: writer->WriteValue(TEXT("DJ")); break; case CountryCodeDM: writer->WriteValue(TEXT("DM")); break; case CountryCodeDO: writer->WriteValue(TEXT("DO")); break; case CountryCodeEC: writer->WriteValue(TEXT("EC")); break; case CountryCodeEG: writer->WriteValue(TEXT("EG")); break; case CountryCodeSV: writer->WriteValue(TEXT("SV")); break; case CountryCodeGQ: writer->WriteValue(TEXT("GQ")); break; case CountryCodeER: writer->WriteValue(TEXT("ER")); break; case CountryCodeEE: writer->WriteValue(TEXT("EE")); break; case CountryCodeET: writer->WriteValue(TEXT("ET")); break; case CountryCodeFK: writer->WriteValue(TEXT("FK")); break; case CountryCodeFO: writer->WriteValue(TEXT("FO")); break; case CountryCodeFJ: writer->WriteValue(TEXT("FJ")); break; case CountryCodeFI: writer->WriteValue(TEXT("FI")); break; case CountryCodeFR: writer->WriteValue(TEXT("FR")); break; case CountryCodeGF: writer->WriteValue(TEXT("GF")); break; case CountryCodePF: writer->WriteValue(TEXT("PF")); break; case CountryCodeTF: writer->WriteValue(TEXT("TF")); break; case CountryCodeGA: writer->WriteValue(TEXT("GA")); break; case CountryCodeGM: writer->WriteValue(TEXT("GM")); break; case CountryCodeGE: writer->WriteValue(TEXT("GE")); break; case CountryCodeDE: writer->WriteValue(TEXT("DE")); break; case CountryCodeGH: writer->WriteValue(TEXT("GH")); break; case CountryCodeGI: writer->WriteValue(TEXT("GI")); break; case CountryCodeGR: writer->WriteValue(TEXT("GR")); break; case CountryCodeGL: writer->WriteValue(TEXT("GL")); break; case CountryCodeGD: writer->WriteValue(TEXT("GD")); break; case CountryCodeGP: writer->WriteValue(TEXT("GP")); break; case CountryCodeGU: writer->WriteValue(TEXT("GU")); break; case CountryCodeGT: writer->WriteValue(TEXT("GT")); break; case CountryCodeGG: writer->WriteValue(TEXT("GG")); break; case CountryCodeGN: writer->WriteValue(TEXT("GN")); break; case CountryCodeGW: writer->WriteValue(TEXT("GW")); break; case CountryCodeGY: writer->WriteValue(TEXT("GY")); break; case CountryCodeHT: writer->WriteValue(TEXT("HT")); break; case CountryCodeHM: writer->WriteValue(TEXT("HM")); break; case CountryCodeVA: writer->WriteValue(TEXT("VA")); break; case CountryCodeHN: writer->WriteValue(TEXT("HN")); break; case CountryCodeHK: writer->WriteValue(TEXT("HK")); break; case CountryCodeHU: writer->WriteValue(TEXT("HU")); break; case CountryCodeIS: writer->WriteValue(TEXT("IS")); break; case CountryCodeIN: writer->WriteValue(TEXT("IN")); break; case CountryCodeID: writer->WriteValue(TEXT("ID")); break; case CountryCodeIR: writer->WriteValue(TEXT("IR")); break; case CountryCodeIQ: writer->WriteValue(TEXT("IQ")); break; case CountryCodeIE: writer->WriteValue(TEXT("IE")); break; case CountryCodeIM: writer->WriteValue(TEXT("IM")); break; case CountryCodeIL: writer->WriteValue(TEXT("IL")); break; case CountryCodeIT: writer->WriteValue(TEXT("IT")); break; case CountryCodeJM: writer->WriteValue(TEXT("JM")); break; case CountryCodeJP: writer->WriteValue(TEXT("JP")); break; case CountryCodeJE: writer->WriteValue(TEXT("JE")); break; case CountryCodeJO: writer->WriteValue(TEXT("JO")); break; case CountryCodeKZ: writer->WriteValue(TEXT("KZ")); break; case CountryCodeKE: writer->WriteValue(TEXT("KE")); break; case CountryCodeKI: writer->WriteValue(TEXT("KI")); break; case CountryCodeKP: writer->WriteValue(TEXT("KP")); break; case CountryCodeKR: writer->WriteValue(TEXT("KR")); break; case CountryCodeKW: writer->WriteValue(TEXT("KW")); break; case CountryCodeKG: writer->WriteValue(TEXT("KG")); break; case CountryCodeLA: writer->WriteValue(TEXT("LA")); break; case CountryCodeLV: writer->WriteValue(TEXT("LV")); break; case CountryCodeLB: writer->WriteValue(TEXT("LB")); break; case CountryCodeLS: writer->WriteValue(TEXT("LS")); break; case CountryCodeLR: writer->WriteValue(TEXT("LR")); break; case CountryCodeLY: writer->WriteValue(TEXT("LY")); break; case CountryCodeLI: writer->WriteValue(TEXT("LI")); break; case CountryCodeLT: writer->WriteValue(TEXT("LT")); break; case CountryCodeLU: writer->WriteValue(TEXT("LU")); break; case CountryCodeMO: writer->WriteValue(TEXT("MO")); break; case CountryCodeMK: writer->WriteValue(TEXT("MK")); break; case CountryCodeMG: writer->WriteValue(TEXT("MG")); break; case CountryCodeMW: writer->WriteValue(TEXT("MW")); break; case CountryCodeMY: writer->WriteValue(TEXT("MY")); break; case CountryCodeMV: writer->WriteValue(TEXT("MV")); break; case CountryCodeML: writer->WriteValue(TEXT("ML")); break; case CountryCodeMT: writer->WriteValue(TEXT("MT")); break; case CountryCodeMH: writer->WriteValue(TEXT("MH")); break; case CountryCodeMQ: writer->WriteValue(TEXT("MQ")); break; case CountryCodeMR: writer->WriteValue(TEXT("MR")); break; case CountryCodeMU: writer->WriteValue(TEXT("MU")); break; case CountryCodeYT: writer->WriteValue(TEXT("YT")); break; case CountryCodeMX: writer->WriteValue(TEXT("MX")); break; case CountryCodeFM: writer->WriteValue(TEXT("FM")); break; case CountryCodeMD: writer->WriteValue(TEXT("MD")); break; case CountryCodeMC: writer->WriteValue(TEXT("MC")); break; case CountryCodeMN: writer->WriteValue(TEXT("MN")); break; case CountryCodeME: writer->WriteValue(TEXT("ME")); break; case CountryCodeMS: writer->WriteValue(TEXT("MS")); break; case CountryCodeMA: writer->WriteValue(TEXT("MA")); break; case CountryCodeMZ: writer->WriteValue(TEXT("MZ")); break; case CountryCodeMM: writer->WriteValue(TEXT("MM")); break; case CountryCodeNA: writer->WriteValue(TEXT("NA")); break; case CountryCodeNR: writer->WriteValue(TEXT("NR")); break; case CountryCodeNP: writer->WriteValue(TEXT("NP")); break; case CountryCodeNL: writer->WriteValue(TEXT("NL")); break; case CountryCodeNC: writer->WriteValue(TEXT("NC")); break; case CountryCodeNZ: writer->WriteValue(TEXT("NZ")); break; case CountryCodeNI: writer->WriteValue(TEXT("NI")); break; case CountryCodeNE: writer->WriteValue(TEXT("NE")); break; case CountryCodeNG: writer->WriteValue(TEXT("NG")); break; case CountryCodeNU: writer->WriteValue(TEXT("NU")); break; case CountryCodeNF: writer->WriteValue(TEXT("NF")); break; case CountryCodeMP: writer->WriteValue(TEXT("MP")); break; case CountryCodeNO: writer->WriteValue(TEXT("NO")); break; case CountryCodeOM: writer->WriteValue(TEXT("OM")); break; case CountryCodePK: writer->WriteValue(TEXT("PK")); break; case CountryCodePW: writer->WriteValue(TEXT("PW")); break; case CountryCodePS: writer->WriteValue(TEXT("PS")); break; case CountryCodePA: writer->WriteValue(TEXT("PA")); break; case CountryCodePG: writer->WriteValue(TEXT("PG")); break; case CountryCodePY: writer->WriteValue(TEXT("PY")); break; case CountryCodePE: writer->WriteValue(TEXT("PE")); break; case CountryCodePH: writer->WriteValue(TEXT("PH")); break; case CountryCodePN: writer->WriteValue(TEXT("PN")); break; case CountryCodePL: writer->WriteValue(TEXT("PL")); break; case CountryCodePT: writer->WriteValue(TEXT("PT")); break; case CountryCodePR: writer->WriteValue(TEXT("PR")); break; case CountryCodeQA: writer->WriteValue(TEXT("QA")); break; case CountryCodeRE: writer->WriteValue(TEXT("RE")); break; case CountryCodeRO: writer->WriteValue(TEXT("RO")); break; case CountryCodeRU: writer->WriteValue(TEXT("RU")); break; case CountryCodeRW: writer->WriteValue(TEXT("RW")); break; case CountryCodeBL: writer->WriteValue(TEXT("BL")); break; case CountryCodeSH: writer->WriteValue(TEXT("SH")); break; case CountryCodeKN: writer->WriteValue(TEXT("KN")); break; case CountryCodeLC: writer->WriteValue(TEXT("LC")); break; case CountryCodeMF: writer->WriteValue(TEXT("MF")); break; case CountryCodePM: writer->WriteValue(TEXT("PM")); break; case CountryCodeVC: writer->WriteValue(TEXT("VC")); break; case CountryCodeWS: writer->WriteValue(TEXT("WS")); break; case CountryCodeSM: writer->WriteValue(TEXT("SM")); break; case CountryCodeST: writer->WriteValue(TEXT("ST")); break; case CountryCodeSA: writer->WriteValue(TEXT("SA")); break; case CountryCodeSN: writer->WriteValue(TEXT("SN")); break; case CountryCodeRS: writer->WriteValue(TEXT("RS")); break; case CountryCodeSC: writer->WriteValue(TEXT("SC")); break; case CountryCodeSL: writer->WriteValue(TEXT("SL")); break; case CountryCodeSG: writer->WriteValue(TEXT("SG")); break; case CountryCodeSX: writer->WriteValue(TEXT("SX")); break; case CountryCodeSK: writer->WriteValue(TEXT("SK")); break; case CountryCodeSI: writer->WriteValue(TEXT("SI")); break; case CountryCodeSB: writer->WriteValue(TEXT("SB")); break; case CountryCodeSO: writer->WriteValue(TEXT("SO")); break; case CountryCodeZA: writer->WriteValue(TEXT("ZA")); break; case CountryCodeGS: writer->WriteValue(TEXT("GS")); break; case CountryCodeSS: writer->WriteValue(TEXT("SS")); break; case CountryCodeES: writer->WriteValue(TEXT("ES")); break; case CountryCodeLK: writer->WriteValue(TEXT("LK")); break; case CountryCodeSD: writer->WriteValue(TEXT("SD")); break; case CountryCodeSR: writer->WriteValue(TEXT("SR")); break; case CountryCodeSJ: writer->WriteValue(TEXT("SJ")); break; case CountryCodeSZ: writer->WriteValue(TEXT("SZ")); break; case CountryCodeSE: writer->WriteValue(TEXT("SE")); break; case CountryCodeCH: writer->WriteValue(TEXT("CH")); break; case CountryCodeSY: writer->WriteValue(TEXT("SY")); break; case CountryCodeTW: writer->WriteValue(TEXT("TW")); break; case CountryCodeTJ: writer->WriteValue(TEXT("TJ")); break; case CountryCodeTZ: writer->WriteValue(TEXT("TZ")); break; case CountryCodeTH: writer->WriteValue(TEXT("TH")); break; case CountryCodeTL: writer->WriteValue(TEXT("TL")); break; case CountryCodeTG: writer->WriteValue(TEXT("TG")); break; case CountryCodeTK: writer->WriteValue(TEXT("TK")); break; case CountryCodeTO: writer->WriteValue(TEXT("TO")); break; case CountryCodeTT: writer->WriteValue(TEXT("TT")); break; case CountryCodeTN: writer->WriteValue(TEXT("TN")); break; case CountryCodeTR: writer->WriteValue(TEXT("TR")); break; case CountryCodeTM: writer->WriteValue(TEXT("TM")); break; case CountryCodeTC: writer->WriteValue(TEXT("TC")); break; case CountryCodeTV: writer->WriteValue(TEXT("TV")); break; case CountryCodeUG: writer->WriteValue(TEXT("UG")); break; case CountryCodeUA: writer->WriteValue(TEXT("UA")); break; case CountryCodeAE: writer->WriteValue(TEXT("AE")); break; case CountryCodeGB: writer->WriteValue(TEXT("GB")); break; case CountryCodeUS: writer->WriteValue(TEXT("US")); break; case CountryCodeUM: writer->WriteValue(TEXT("UM")); break; case CountryCodeUY: writer->WriteValue(TEXT("UY")); break; case CountryCodeUZ: writer->WriteValue(TEXT("UZ")); break; case CountryCodeVU: writer->WriteValue(TEXT("VU")); break; case CountryCodeVE: writer->WriteValue(TEXT("VE")); break; case CountryCodeVN: writer->WriteValue(TEXT("VN")); break; case CountryCodeVG: writer->WriteValue(TEXT("VG")); break; case CountryCodeVI: writer->WriteValue(TEXT("VI")); break; case CountryCodeWF: writer->WriteValue(TEXT("WF")); break; case CountryCodeEH: writer->WriteValue(TEXT("EH")); break; case CountryCodeYE: writer->WriteValue(TEXT("YE")); break; case CountryCodeZM: writer->WriteValue(TEXT("ZM")); break; case CountryCodeZW: writer->WriteValue(TEXT("ZW")); break; } } ServerModels::CountryCode PlayFab::ServerModels::readCountryCodeFromValue(const TSharedPtr<FJsonValue>& value) { return readCountryCodeFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::CountryCode PlayFab::ServerModels::readCountryCodeFromValue(const FString& value) { static TMap<FString, CountryCode> _CountryCodeMap; if (_CountryCodeMap.Num() == 0) { // Auto-generate the map on the first use _CountryCodeMap.Add(TEXT("AF"), CountryCodeAF); _CountryCodeMap.Add(TEXT("AX"), CountryCodeAX); _CountryCodeMap.Add(TEXT("AL"), CountryCodeAL); _CountryCodeMap.Add(TEXT("DZ"), CountryCodeDZ); _CountryCodeMap.Add(TEXT("AS"), CountryCodeAS); _CountryCodeMap.Add(TEXT("AD"), CountryCodeAD); _CountryCodeMap.Add(TEXT("AO"), CountryCodeAO); _CountryCodeMap.Add(TEXT("AI"), CountryCodeAI); _CountryCodeMap.Add(TEXT("AQ"), CountryCodeAQ); _CountryCodeMap.Add(TEXT("AG"), CountryCodeAG); _CountryCodeMap.Add(TEXT("AR"), CountryCodeAR); _CountryCodeMap.Add(TEXT("AM"), CountryCodeAM); _CountryCodeMap.Add(TEXT("AW"), CountryCodeAW); _CountryCodeMap.Add(TEXT("AU"), CountryCodeAU); _CountryCodeMap.Add(TEXT("AT"), CountryCodeAT); _CountryCodeMap.Add(TEXT("AZ"), CountryCodeAZ); _CountryCodeMap.Add(TEXT("BS"), CountryCodeBS); _CountryCodeMap.Add(TEXT("BH"), CountryCodeBH); _CountryCodeMap.Add(TEXT("BD"), CountryCodeBD); _CountryCodeMap.Add(TEXT("BB"), CountryCodeBB); _CountryCodeMap.Add(TEXT("BY"), CountryCodeBY); _CountryCodeMap.Add(TEXT("BE"), CountryCodeBE); _CountryCodeMap.Add(TEXT("BZ"), CountryCodeBZ); _CountryCodeMap.Add(TEXT("BJ"), CountryCodeBJ); _CountryCodeMap.Add(TEXT("BM"), CountryCodeBM); _CountryCodeMap.Add(TEXT("BT"), CountryCodeBT); _CountryCodeMap.Add(TEXT("BO"), CountryCodeBO); _CountryCodeMap.Add(TEXT("BQ"), CountryCodeBQ); _CountryCodeMap.Add(TEXT("BA"), CountryCodeBA); _CountryCodeMap.Add(TEXT("BW"), CountryCodeBW); _CountryCodeMap.Add(TEXT("BV"), CountryCodeBV); _CountryCodeMap.Add(TEXT("BR"), CountryCodeBR); _CountryCodeMap.Add(TEXT("IO"), CountryCodeIO); _CountryCodeMap.Add(TEXT("BN"), CountryCodeBN); _CountryCodeMap.Add(TEXT("BG"), CountryCodeBG); _CountryCodeMap.Add(TEXT("BF"), CountryCodeBF); _CountryCodeMap.Add(TEXT("BI"), CountryCodeBI); _CountryCodeMap.Add(TEXT("KH"), CountryCodeKH); _CountryCodeMap.Add(TEXT("CM"), CountryCodeCM); _CountryCodeMap.Add(TEXT("CA"), CountryCodeCA); _CountryCodeMap.Add(TEXT("CV"), CountryCodeCV); _CountryCodeMap.Add(TEXT("KY"), CountryCodeKY); _CountryCodeMap.Add(TEXT("CF"), CountryCodeCF); _CountryCodeMap.Add(TEXT("TD"), CountryCodeTD); _CountryCodeMap.Add(TEXT("CL"), CountryCodeCL); _CountryCodeMap.Add(TEXT("CN"), CountryCodeCN); _CountryCodeMap.Add(TEXT("CX"), CountryCodeCX); _CountryCodeMap.Add(TEXT("CC"), CountryCodeCC); _CountryCodeMap.Add(TEXT("CO"), CountryCodeCO); _CountryCodeMap.Add(TEXT("KM"), CountryCodeKM); _CountryCodeMap.Add(TEXT("CG"), CountryCodeCG); _CountryCodeMap.Add(TEXT("CD"), CountryCodeCD); _CountryCodeMap.Add(TEXT("CK"), CountryCodeCK); _CountryCodeMap.Add(TEXT("CR"), CountryCodeCR); _CountryCodeMap.Add(TEXT("CI"), CountryCodeCI); _CountryCodeMap.Add(TEXT("HR"), CountryCodeHR); _CountryCodeMap.Add(TEXT("CU"), CountryCodeCU); _CountryCodeMap.Add(TEXT("CW"), CountryCodeCW); _CountryCodeMap.Add(TEXT("CY"), CountryCodeCY); _CountryCodeMap.Add(TEXT("CZ"), CountryCodeCZ); _CountryCodeMap.Add(TEXT("DK"), CountryCodeDK); _CountryCodeMap.Add(TEXT("DJ"), CountryCodeDJ); _CountryCodeMap.Add(TEXT("DM"), CountryCodeDM); _CountryCodeMap.Add(TEXT("DO"), CountryCodeDO); _CountryCodeMap.Add(TEXT("EC"), CountryCodeEC); _CountryCodeMap.Add(TEXT("EG"), CountryCodeEG); _CountryCodeMap.Add(TEXT("SV"), CountryCodeSV); _CountryCodeMap.Add(TEXT("GQ"), CountryCodeGQ); _CountryCodeMap.Add(TEXT("ER"), CountryCodeER); _CountryCodeMap.Add(TEXT("EE"), CountryCodeEE); _CountryCodeMap.Add(TEXT("ET"), CountryCodeET); _CountryCodeMap.Add(TEXT("FK"), CountryCodeFK); _CountryCodeMap.Add(TEXT("FO"), CountryCodeFO); _CountryCodeMap.Add(TEXT("FJ"), CountryCodeFJ); _CountryCodeMap.Add(TEXT("FI"), CountryCodeFI); _CountryCodeMap.Add(TEXT("FR"), CountryCodeFR); _CountryCodeMap.Add(TEXT("GF"), CountryCodeGF); _CountryCodeMap.Add(TEXT("PF"), CountryCodePF); _CountryCodeMap.Add(TEXT("TF"), CountryCodeTF); _CountryCodeMap.Add(TEXT("GA"), CountryCodeGA); _CountryCodeMap.Add(TEXT("GM"), CountryCodeGM); _CountryCodeMap.Add(TEXT("GE"), CountryCodeGE); _CountryCodeMap.Add(TEXT("DE"), CountryCodeDE); _CountryCodeMap.Add(TEXT("GH"), CountryCodeGH); _CountryCodeMap.Add(TEXT("GI"), CountryCodeGI); _CountryCodeMap.Add(TEXT("GR"), CountryCodeGR); _CountryCodeMap.Add(TEXT("GL"), CountryCodeGL); _CountryCodeMap.Add(TEXT("GD"), CountryCodeGD); _CountryCodeMap.Add(TEXT("GP"), CountryCodeGP); _CountryCodeMap.Add(TEXT("GU"), CountryCodeGU); _CountryCodeMap.Add(TEXT("GT"), CountryCodeGT); _CountryCodeMap.Add(TEXT("GG"), CountryCodeGG); _CountryCodeMap.Add(TEXT("GN"), CountryCodeGN); _CountryCodeMap.Add(TEXT("GW"), CountryCodeGW); _CountryCodeMap.Add(TEXT("GY"), CountryCodeGY); _CountryCodeMap.Add(TEXT("HT"), CountryCodeHT); _CountryCodeMap.Add(TEXT("HM"), CountryCodeHM); _CountryCodeMap.Add(TEXT("VA"), CountryCodeVA); _CountryCodeMap.Add(TEXT("HN"), CountryCodeHN); _CountryCodeMap.Add(TEXT("HK"), CountryCodeHK); _CountryCodeMap.Add(TEXT("HU"), CountryCodeHU); _CountryCodeMap.Add(TEXT("IS"), CountryCodeIS); _CountryCodeMap.Add(TEXT("IN"), CountryCodeIN); _CountryCodeMap.Add(TEXT("ID"), CountryCodeID); _CountryCodeMap.Add(TEXT("IR"), CountryCodeIR); _CountryCodeMap.Add(TEXT("IQ"), CountryCodeIQ); _CountryCodeMap.Add(TEXT("IE"), CountryCodeIE); _CountryCodeMap.Add(TEXT("IM"), CountryCodeIM); _CountryCodeMap.Add(TEXT("IL"), CountryCodeIL); _CountryCodeMap.Add(TEXT("IT"), CountryCodeIT); _CountryCodeMap.Add(TEXT("JM"), CountryCodeJM); _CountryCodeMap.Add(TEXT("JP"), CountryCodeJP); _CountryCodeMap.Add(TEXT("JE"), CountryCodeJE); _CountryCodeMap.Add(TEXT("JO"), CountryCodeJO); _CountryCodeMap.Add(TEXT("KZ"), CountryCodeKZ); _CountryCodeMap.Add(TEXT("KE"), CountryCodeKE); _CountryCodeMap.Add(TEXT("KI"), CountryCodeKI); _CountryCodeMap.Add(TEXT("KP"), CountryCodeKP); _CountryCodeMap.Add(TEXT("KR"), CountryCodeKR); _CountryCodeMap.Add(TEXT("KW"), CountryCodeKW); _CountryCodeMap.Add(TEXT("KG"), CountryCodeKG); _CountryCodeMap.Add(TEXT("LA"), CountryCodeLA); _CountryCodeMap.Add(TEXT("LV"), CountryCodeLV); _CountryCodeMap.Add(TEXT("LB"), CountryCodeLB); _CountryCodeMap.Add(TEXT("LS"), CountryCodeLS); _CountryCodeMap.Add(TEXT("LR"), CountryCodeLR); _CountryCodeMap.Add(TEXT("LY"), CountryCodeLY); _CountryCodeMap.Add(TEXT("LI"), CountryCodeLI); _CountryCodeMap.Add(TEXT("LT"), CountryCodeLT); _CountryCodeMap.Add(TEXT("LU"), CountryCodeLU); _CountryCodeMap.Add(TEXT("MO"), CountryCodeMO); _CountryCodeMap.Add(TEXT("MK"), CountryCodeMK); _CountryCodeMap.Add(TEXT("MG"), CountryCodeMG); _CountryCodeMap.Add(TEXT("MW"), CountryCodeMW); _CountryCodeMap.Add(TEXT("MY"), CountryCodeMY); _CountryCodeMap.Add(TEXT("MV"), CountryCodeMV); _CountryCodeMap.Add(TEXT("ML"), CountryCodeML); _CountryCodeMap.Add(TEXT("MT"), CountryCodeMT); _CountryCodeMap.Add(TEXT("MH"), CountryCodeMH); _CountryCodeMap.Add(TEXT("MQ"), CountryCodeMQ); _CountryCodeMap.Add(TEXT("MR"), CountryCodeMR); _CountryCodeMap.Add(TEXT("MU"), CountryCodeMU); _CountryCodeMap.Add(TEXT("YT"), CountryCodeYT); _CountryCodeMap.Add(TEXT("MX"), CountryCodeMX); _CountryCodeMap.Add(TEXT("FM"), CountryCodeFM); _CountryCodeMap.Add(TEXT("MD"), CountryCodeMD); _CountryCodeMap.Add(TEXT("MC"), CountryCodeMC); _CountryCodeMap.Add(TEXT("MN"), CountryCodeMN); _CountryCodeMap.Add(TEXT("ME"), CountryCodeME); _CountryCodeMap.Add(TEXT("MS"), CountryCodeMS); _CountryCodeMap.Add(TEXT("MA"), CountryCodeMA); _CountryCodeMap.Add(TEXT("MZ"), CountryCodeMZ); _CountryCodeMap.Add(TEXT("MM"), CountryCodeMM); _CountryCodeMap.Add(TEXT("NA"), CountryCodeNA); _CountryCodeMap.Add(TEXT("NR"), CountryCodeNR); _CountryCodeMap.Add(TEXT("NP"), CountryCodeNP); _CountryCodeMap.Add(TEXT("NL"), CountryCodeNL); _CountryCodeMap.Add(TEXT("NC"), CountryCodeNC); _CountryCodeMap.Add(TEXT("NZ"), CountryCodeNZ); _CountryCodeMap.Add(TEXT("NI"), CountryCodeNI); _CountryCodeMap.Add(TEXT("NE"), CountryCodeNE); _CountryCodeMap.Add(TEXT("NG"), CountryCodeNG); _CountryCodeMap.Add(TEXT("NU"), CountryCodeNU); _CountryCodeMap.Add(TEXT("NF"), CountryCodeNF); _CountryCodeMap.Add(TEXT("MP"), CountryCodeMP); _CountryCodeMap.Add(TEXT("NO"), CountryCodeNO); _CountryCodeMap.Add(TEXT("OM"), CountryCodeOM); _CountryCodeMap.Add(TEXT("PK"), CountryCodePK); _CountryCodeMap.Add(TEXT("PW"), CountryCodePW); _CountryCodeMap.Add(TEXT("PS"), CountryCodePS); _CountryCodeMap.Add(TEXT("PA"), CountryCodePA); _CountryCodeMap.Add(TEXT("PG"), CountryCodePG); _CountryCodeMap.Add(TEXT("PY"), CountryCodePY); _CountryCodeMap.Add(TEXT("PE"), CountryCodePE); _CountryCodeMap.Add(TEXT("PH"), CountryCodePH); _CountryCodeMap.Add(TEXT("PN"), CountryCodePN); _CountryCodeMap.Add(TEXT("PL"), CountryCodePL); _CountryCodeMap.Add(TEXT("PT"), CountryCodePT); _CountryCodeMap.Add(TEXT("PR"), CountryCodePR); _CountryCodeMap.Add(TEXT("QA"), CountryCodeQA); _CountryCodeMap.Add(TEXT("RE"), CountryCodeRE); _CountryCodeMap.Add(TEXT("RO"), CountryCodeRO); _CountryCodeMap.Add(TEXT("RU"), CountryCodeRU); _CountryCodeMap.Add(TEXT("RW"), CountryCodeRW); _CountryCodeMap.Add(TEXT("BL"), CountryCodeBL); _CountryCodeMap.Add(TEXT("SH"), CountryCodeSH); _CountryCodeMap.Add(TEXT("KN"), CountryCodeKN); _CountryCodeMap.Add(TEXT("LC"), CountryCodeLC); _CountryCodeMap.Add(TEXT("MF"), CountryCodeMF); _CountryCodeMap.Add(TEXT("PM"), CountryCodePM); _CountryCodeMap.Add(TEXT("VC"), CountryCodeVC); _CountryCodeMap.Add(TEXT("WS"), CountryCodeWS); _CountryCodeMap.Add(TEXT("SM"), CountryCodeSM); _CountryCodeMap.Add(TEXT("ST"), CountryCodeST); _CountryCodeMap.Add(TEXT("SA"), CountryCodeSA); _CountryCodeMap.Add(TEXT("SN"), CountryCodeSN); _CountryCodeMap.Add(TEXT("RS"), CountryCodeRS); _CountryCodeMap.Add(TEXT("SC"), CountryCodeSC); _CountryCodeMap.Add(TEXT("SL"), CountryCodeSL); _CountryCodeMap.Add(TEXT("SG"), CountryCodeSG); _CountryCodeMap.Add(TEXT("SX"), CountryCodeSX); _CountryCodeMap.Add(TEXT("SK"), CountryCodeSK); _CountryCodeMap.Add(TEXT("SI"), CountryCodeSI); _CountryCodeMap.Add(TEXT("SB"), CountryCodeSB); _CountryCodeMap.Add(TEXT("SO"), CountryCodeSO); _CountryCodeMap.Add(TEXT("ZA"), CountryCodeZA); _CountryCodeMap.Add(TEXT("GS"), CountryCodeGS); _CountryCodeMap.Add(TEXT("SS"), CountryCodeSS); _CountryCodeMap.Add(TEXT("ES"), CountryCodeES); _CountryCodeMap.Add(TEXT("LK"), CountryCodeLK); _CountryCodeMap.Add(TEXT("SD"), CountryCodeSD); _CountryCodeMap.Add(TEXT("SR"), CountryCodeSR); _CountryCodeMap.Add(TEXT("SJ"), CountryCodeSJ); _CountryCodeMap.Add(TEXT("SZ"), CountryCodeSZ); _CountryCodeMap.Add(TEXT("SE"), CountryCodeSE); _CountryCodeMap.Add(TEXT("CH"), CountryCodeCH); _CountryCodeMap.Add(TEXT("SY"), CountryCodeSY); _CountryCodeMap.Add(TEXT("TW"), CountryCodeTW); _CountryCodeMap.Add(TEXT("TJ"), CountryCodeTJ); _CountryCodeMap.Add(TEXT("TZ"), CountryCodeTZ); _CountryCodeMap.Add(TEXT("TH"), CountryCodeTH); _CountryCodeMap.Add(TEXT("TL"), CountryCodeTL); _CountryCodeMap.Add(TEXT("TG"), CountryCodeTG); _CountryCodeMap.Add(TEXT("TK"), CountryCodeTK); _CountryCodeMap.Add(TEXT("TO"), CountryCodeTO); _CountryCodeMap.Add(TEXT("TT"), CountryCodeTT); _CountryCodeMap.Add(TEXT("TN"), CountryCodeTN); _CountryCodeMap.Add(TEXT("TR"), CountryCodeTR); _CountryCodeMap.Add(TEXT("TM"), CountryCodeTM); _CountryCodeMap.Add(TEXT("TC"), CountryCodeTC); _CountryCodeMap.Add(TEXT("TV"), CountryCodeTV); _CountryCodeMap.Add(TEXT("UG"), CountryCodeUG); _CountryCodeMap.Add(TEXT("UA"), CountryCodeUA); _CountryCodeMap.Add(TEXT("AE"), CountryCodeAE); _CountryCodeMap.Add(TEXT("GB"), CountryCodeGB); _CountryCodeMap.Add(TEXT("US"), CountryCodeUS); _CountryCodeMap.Add(TEXT("UM"), CountryCodeUM); _CountryCodeMap.Add(TEXT("UY"), CountryCodeUY); _CountryCodeMap.Add(TEXT("UZ"), CountryCodeUZ); _CountryCodeMap.Add(TEXT("VU"), CountryCodeVU); _CountryCodeMap.Add(TEXT("VE"), CountryCodeVE); _CountryCodeMap.Add(TEXT("VN"), CountryCodeVN); _CountryCodeMap.Add(TEXT("VG"), CountryCodeVG); _CountryCodeMap.Add(TEXT("VI"), CountryCodeVI); _CountryCodeMap.Add(TEXT("WF"), CountryCodeWF); _CountryCodeMap.Add(TEXT("EH"), CountryCodeEH); _CountryCodeMap.Add(TEXT("YE"), CountryCodeYE); _CountryCodeMap.Add(TEXT("ZM"), CountryCodeZM); _CountryCodeMap.Add(TEXT("ZW"), CountryCodeZW); } if (!value.IsEmpty()) { auto output = _CountryCodeMap.Find(value); if (output != nullptr) return *output; } return CountryCodeAF; // Basically critical fail } PlayFab::ServerModels::FCreateSharedGroupRequest::~FCreateSharedGroupRequest() { } void PlayFab::ServerModels::FCreateSharedGroupRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (SharedGroupId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("SharedGroupId")); writer->WriteValue(SharedGroupId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FCreateSharedGroupRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> SharedGroupIdValue = obj->TryGetField(TEXT("SharedGroupId")); if (SharedGroupIdValue.IsValid() && !SharedGroupIdValue->IsNull()) { FString TmpValue; if (SharedGroupIdValue->TryGetString(TmpValue)) { SharedGroupId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FCreateSharedGroupResult::~FCreateSharedGroupResult() { } void PlayFab::ServerModels::FCreateSharedGroupResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (SharedGroupId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("SharedGroupId")); writer->WriteValue(SharedGroupId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FCreateSharedGroupResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> SharedGroupIdValue = obj->TryGetField(TEXT("SharedGroupId")); if (SharedGroupIdValue.IsValid() && !SharedGroupIdValue->IsNull()) { FString TmpValue; if (SharedGroupIdValue->TryGetString(TmpValue)) { SharedGroupId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FDeleteCharacterFromUserRequest::~FDeleteCharacterFromUserRequest() { } void PlayFab::ServerModels::FDeleteCharacterFromUserRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("SaveCharacterInventory")); writer->WriteValue(SaveCharacterInventory); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FDeleteCharacterFromUserRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> SaveCharacterInventoryValue = obj->TryGetField(TEXT("SaveCharacterInventory")); if (SaveCharacterInventoryValue.IsValid() && !SaveCharacterInventoryValue->IsNull()) { bool TmpValue; if (SaveCharacterInventoryValue->TryGetBool(TmpValue)) { SaveCharacterInventory = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FDeleteCharacterFromUserResult::~FDeleteCharacterFromUserResult() { } void PlayFab::ServerModels::FDeleteCharacterFromUserResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FDeleteCharacterFromUserResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FDeletePlayerRequest::~FDeletePlayerRequest() { } void PlayFab::ServerModels::FDeletePlayerRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FDeletePlayerRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FDeletePlayerResult::~FDeletePlayerResult() { } void PlayFab::ServerModels::FDeletePlayerResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FDeletePlayerResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FDeletePushNotificationTemplateRequest::~FDeletePushNotificationTemplateRequest() { } void PlayFab::ServerModels::FDeletePushNotificationTemplateRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PushNotificationTemplateId")); writer->WriteValue(PushNotificationTemplateId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FDeletePushNotificationTemplateRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PushNotificationTemplateIdValue = obj->TryGetField(TEXT("PushNotificationTemplateId")); if (PushNotificationTemplateIdValue.IsValid() && !PushNotificationTemplateIdValue->IsNull()) { FString TmpValue; if (PushNotificationTemplateIdValue->TryGetString(TmpValue)) { PushNotificationTemplateId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FDeletePushNotificationTemplateResult::~FDeletePushNotificationTemplateResult() { } void PlayFab::ServerModels::FDeletePushNotificationTemplateResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FDeletePushNotificationTemplateResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FDeleteSharedGroupRequest::~FDeleteSharedGroupRequest() { } void PlayFab::ServerModels::FDeleteSharedGroupRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("SharedGroupId")); writer->WriteValue(SharedGroupId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FDeleteSharedGroupRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> SharedGroupIdValue = obj->TryGetField(TEXT("SharedGroupId")); if (SharedGroupIdValue.IsValid() && !SharedGroupIdValue->IsNull()) { FString TmpValue; if (SharedGroupIdValue->TryGetString(TmpValue)) { SharedGroupId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FDeregisterGameRequest::~FDeregisterGameRequest() { } void PlayFab::ServerModels::FDeregisterGameRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("LobbyId")); writer->WriteValue(LobbyId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FDeregisterGameRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> LobbyIdValue = obj->TryGetField(TEXT("LobbyId")); if (LobbyIdValue.IsValid() && !LobbyIdValue->IsNull()) { FString TmpValue; if (LobbyIdValue->TryGetString(TmpValue)) { LobbyId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FDeregisterGameResponse::~FDeregisterGameResponse() { } void PlayFab::ServerModels::FDeregisterGameResponse::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FDeregisterGameResponse::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FEmptyResponse::~FEmptyResponse() { } void PlayFab::ServerModels::FEmptyResponse::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FEmptyResponse::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FEmptyResult::~FEmptyResult() { } void PlayFab::ServerModels::FEmptyResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FEmptyResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FEntityTokenResponse::~FEntityTokenResponse() { //if (Entity != nullptr) delete Entity; } void PlayFab::ServerModels::FEntityTokenResponse::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Entity.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Entity")); Entity->writeJSON(writer); } if (EntityToken.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("EntityToken")); writer->WriteValue(EntityToken); } if (TokenExpiration.notNull()) { writer->WriteIdentifierPrefix(TEXT("TokenExpiration")); writeDatetime(TokenExpiration, writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FEntityTokenResponse::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> EntityValue = obj->TryGetField(TEXT("Entity")); if (EntityValue.IsValid() && !EntityValue->IsNull()) { Entity = MakeShareable(new FEntityKey(EntityValue->AsObject())); } const TSharedPtr<FJsonValue> EntityTokenValue = obj->TryGetField(TEXT("EntityToken")); if (EntityTokenValue.IsValid() && !EntityTokenValue->IsNull()) { FString TmpValue; if (EntityTokenValue->TryGetString(TmpValue)) { EntityToken = TmpValue; } } const TSharedPtr<FJsonValue> TokenExpirationValue = obj->TryGetField(TEXT("TokenExpiration")); if (TokenExpirationValue.IsValid()) TokenExpiration = readDatetime(TokenExpirationValue); return HasSucceeded; } PlayFab::ServerModels::FEvaluateRandomResultTableRequest::~FEvaluateRandomResultTableRequest() { } void PlayFab::ServerModels::FEvaluateRandomResultTableRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } writer->WriteIdentifierPrefix(TEXT("TableId")); writer->WriteValue(TableId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FEvaluateRandomResultTableRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } const TSharedPtr<FJsonValue> TableIdValue = obj->TryGetField(TEXT("TableId")); if (TableIdValue.IsValid() && !TableIdValue->IsNull()) { FString TmpValue; if (TableIdValue->TryGetString(TmpValue)) { TableId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FEvaluateRandomResultTableResult::~FEvaluateRandomResultTableResult() { } void PlayFab::ServerModels::FEvaluateRandomResultTableResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (ResultItemId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ResultItemId")); writer->WriteValue(ResultItemId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FEvaluateRandomResultTableResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ResultItemIdValue = obj->TryGetField(TEXT("ResultItemId")); if (ResultItemIdValue.IsValid() && !ResultItemIdValue->IsNull()) { FString TmpValue; if (ResultItemIdValue->TryGetString(TmpValue)) { ResultItemId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FScriptExecutionError::~FScriptExecutionError() { } void PlayFab::ServerModels::FScriptExecutionError::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Error.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Error")); writer->WriteValue(Error); } if (Message.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Message")); writer->WriteValue(Message); } if (StackTrace.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("StackTrace")); writer->WriteValue(StackTrace); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FScriptExecutionError::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ErrorValue = obj->TryGetField(TEXT("Error")); if (ErrorValue.IsValid() && !ErrorValue->IsNull()) { FString TmpValue; if (ErrorValue->TryGetString(TmpValue)) { Error = TmpValue; } } const TSharedPtr<FJsonValue> MessageValue = obj->TryGetField(TEXT("Message")); if (MessageValue.IsValid() && !MessageValue->IsNull()) { FString TmpValue; if (MessageValue->TryGetString(TmpValue)) { Message = TmpValue; } } const TSharedPtr<FJsonValue> StackTraceValue = obj->TryGetField(TEXT("StackTrace")); if (StackTraceValue.IsValid() && !StackTraceValue->IsNull()) { FString TmpValue; if (StackTraceValue->TryGetString(TmpValue)) { StackTrace = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FLogStatement::~FLogStatement() { } void PlayFab::ServerModels::FLogStatement::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.notNull()) { writer->WriteIdentifierPrefix(TEXT("Data")); Data.writeJSON(writer); } if (Level.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Level")); writer->WriteValue(Level); } if (Message.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Message")); writer->WriteValue(Message); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FLogStatement::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> DataValue = obj->TryGetField(TEXT("Data")); if (DataValue.IsValid() && !DataValue->IsNull()) { Data = FJsonKeeper(DataValue); } const TSharedPtr<FJsonValue> LevelValue = obj->TryGetField(TEXT("Level")); if (LevelValue.IsValid() && !LevelValue->IsNull()) { FString TmpValue; if (LevelValue->TryGetString(TmpValue)) { Level = TmpValue; } } const TSharedPtr<FJsonValue> MessageValue = obj->TryGetField(TEXT("Message")); if (MessageValue.IsValid() && !MessageValue->IsNull()) { FString TmpValue; if (MessageValue->TryGetString(TmpValue)) { Message = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FExecuteCloudScriptResult::~FExecuteCloudScriptResult() { //if (Error != nullptr) delete Error; } void PlayFab::ServerModels::FExecuteCloudScriptResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("APIRequestsIssued")); writer->WriteValue(APIRequestsIssued); if (Error.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Error")); Error->writeJSON(writer); } writer->WriteIdentifierPrefix(TEXT("ExecutionTimeSeconds")); writer->WriteValue(ExecutionTimeSeconds); if (FunctionName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("FunctionName")); writer->WriteValue(FunctionName); } if (FunctionResult.notNull()) { writer->WriteIdentifierPrefix(TEXT("FunctionResult")); FunctionResult.writeJSON(writer); } if (FunctionResultTooLarge.notNull()) { writer->WriteIdentifierPrefix(TEXT("FunctionResultTooLarge")); writer->WriteValue(FunctionResultTooLarge); } writer->WriteIdentifierPrefix(TEXT("HttpRequestsIssued")); writer->WriteValue(HttpRequestsIssued); if (Logs.Num() != 0) { writer->WriteArrayStart(TEXT("Logs")); for (const FLogStatement& item : Logs) item.writeJSON(writer); writer->WriteArrayEnd(); } if (LogsTooLarge.notNull()) { writer->WriteIdentifierPrefix(TEXT("LogsTooLarge")); writer->WriteValue(LogsTooLarge); } writer->WriteIdentifierPrefix(TEXT("MemoryConsumedBytes")); writer->WriteValue(static_cast<int64>(MemoryConsumedBytes)); writer->WriteIdentifierPrefix(TEXT("ProcessorTimeSeconds")); writer->WriteValue(ProcessorTimeSeconds); writer->WriteIdentifierPrefix(TEXT("Revision")); writer->WriteValue(Revision); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FExecuteCloudScriptResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> APIRequestsIssuedValue = obj->TryGetField(TEXT("APIRequestsIssued")); if (APIRequestsIssuedValue.IsValid() && !APIRequestsIssuedValue->IsNull()) { int32 TmpValue; if (APIRequestsIssuedValue->TryGetNumber(TmpValue)) { APIRequestsIssued = TmpValue; } } const TSharedPtr<FJsonValue> ErrorValue = obj->TryGetField(TEXT("Error")); if (ErrorValue.IsValid() && !ErrorValue->IsNull()) { Error = MakeShareable(new FScriptExecutionError(ErrorValue->AsObject())); } const TSharedPtr<FJsonValue> ExecutionTimeSecondsValue = obj->TryGetField(TEXT("ExecutionTimeSeconds")); if (ExecutionTimeSecondsValue.IsValid() && !ExecutionTimeSecondsValue->IsNull()) { double TmpValue; if (ExecutionTimeSecondsValue->TryGetNumber(TmpValue)) { ExecutionTimeSeconds = TmpValue; } } const TSharedPtr<FJsonValue> FunctionNameValue = obj->TryGetField(TEXT("FunctionName")); if (FunctionNameValue.IsValid() && !FunctionNameValue->IsNull()) { FString TmpValue; if (FunctionNameValue->TryGetString(TmpValue)) { FunctionName = TmpValue; } } const TSharedPtr<FJsonValue> FunctionResultValue = obj->TryGetField(TEXT("FunctionResult")); if (FunctionResultValue.IsValid() && !FunctionResultValue->IsNull()) { FunctionResult = FJsonKeeper(FunctionResultValue); } const TSharedPtr<FJsonValue> FunctionResultTooLargeValue = obj->TryGetField(TEXT("FunctionResultTooLarge")); if (FunctionResultTooLargeValue.IsValid() && !FunctionResultTooLargeValue->IsNull()) { bool TmpValue; if (FunctionResultTooLargeValue->TryGetBool(TmpValue)) { FunctionResultTooLarge = TmpValue; } } const TSharedPtr<FJsonValue> HttpRequestsIssuedValue = obj->TryGetField(TEXT("HttpRequestsIssued")); if (HttpRequestsIssuedValue.IsValid() && !HttpRequestsIssuedValue->IsNull()) { int32 TmpValue; if (HttpRequestsIssuedValue->TryGetNumber(TmpValue)) { HttpRequestsIssued = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&LogsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Logs")); for (int32 Idx = 0; Idx < LogsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = LogsArray[Idx]; Logs.Add(FLogStatement(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> LogsTooLargeValue = obj->TryGetField(TEXT("LogsTooLarge")); if (LogsTooLargeValue.IsValid() && !LogsTooLargeValue->IsNull()) { bool TmpValue; if (LogsTooLargeValue->TryGetBool(TmpValue)) { LogsTooLarge = TmpValue; } } const TSharedPtr<FJsonValue> MemoryConsumedBytesValue = obj->TryGetField(TEXT("MemoryConsumedBytes")); if (MemoryConsumedBytesValue.IsValid() && !MemoryConsumedBytesValue->IsNull()) { uint32 TmpValue; if (MemoryConsumedBytesValue->TryGetNumber(TmpValue)) { MemoryConsumedBytes = TmpValue; } } const TSharedPtr<FJsonValue> ProcessorTimeSecondsValue = obj->TryGetField(TEXT("ProcessorTimeSeconds")); if (ProcessorTimeSecondsValue.IsValid() && !ProcessorTimeSecondsValue->IsNull()) { double TmpValue; if (ProcessorTimeSecondsValue->TryGetNumber(TmpValue)) { ProcessorTimeSeconds = TmpValue; } } const TSharedPtr<FJsonValue> RevisionValue = obj->TryGetField(TEXT("Revision")); if (RevisionValue.IsValid() && !RevisionValue->IsNull()) { int32 TmpValue; if (RevisionValue->TryGetNumber(TmpValue)) { Revision = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FExecuteCloudScriptServerRequest::~FExecuteCloudScriptServerRequest() { } void PlayFab::ServerModels::FExecuteCloudScriptServerRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("FunctionName")); writer->WriteValue(FunctionName); if (FunctionParameter.notNull()) { writer->WriteIdentifierPrefix(TEXT("FunctionParameter")); FunctionParameter.writeJSON(writer); } if (GeneratePlayStreamEvent.notNull()) { writer->WriteIdentifierPrefix(TEXT("GeneratePlayStreamEvent")); writer->WriteValue(GeneratePlayStreamEvent); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); if (RevisionSelection.notNull()) { writer->WriteIdentifierPrefix(TEXT("RevisionSelection")); writeCloudScriptRevisionOptionEnumJSON(RevisionSelection, writer); } if (SpecificRevision.notNull()) { writer->WriteIdentifierPrefix(TEXT("SpecificRevision")); writer->WriteValue(SpecificRevision); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FExecuteCloudScriptServerRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> FunctionNameValue = obj->TryGetField(TEXT("FunctionName")); if (FunctionNameValue.IsValid() && !FunctionNameValue->IsNull()) { FString TmpValue; if (FunctionNameValue->TryGetString(TmpValue)) { FunctionName = TmpValue; } } const TSharedPtr<FJsonValue> FunctionParameterValue = obj->TryGetField(TEXT("FunctionParameter")); if (FunctionParameterValue.IsValid() && !FunctionParameterValue->IsNull()) { FunctionParameter = FJsonKeeper(FunctionParameterValue); } const TSharedPtr<FJsonValue> GeneratePlayStreamEventValue = obj->TryGetField(TEXT("GeneratePlayStreamEvent")); if (GeneratePlayStreamEventValue.IsValid() && !GeneratePlayStreamEventValue->IsNull()) { bool TmpValue; if (GeneratePlayStreamEventValue->TryGetBool(TmpValue)) { GeneratePlayStreamEvent = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } RevisionSelection = readCloudScriptRevisionOptionFromValue(obj->TryGetField(TEXT("RevisionSelection"))); const TSharedPtr<FJsonValue> SpecificRevisionValue = obj->TryGetField(TEXT("SpecificRevision")); if (SpecificRevisionValue.IsValid() && !SpecificRevisionValue->IsNull()) { int32 TmpValue; if (SpecificRevisionValue->TryGetNumber(TmpValue)) { SpecificRevision = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FFacebookInstantGamesPlayFabIdPair::~FFacebookInstantGamesPlayFabIdPair() { } void PlayFab::ServerModels::FFacebookInstantGamesPlayFabIdPair::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (FacebookInstantGamesId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("FacebookInstantGamesId")); writer->WriteValue(FacebookInstantGamesId); } if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FFacebookInstantGamesPlayFabIdPair::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> FacebookInstantGamesIdValue = obj->TryGetField(TEXT("FacebookInstantGamesId")); if (FacebookInstantGamesIdValue.IsValid() && !FacebookInstantGamesIdValue->IsNull()) { FString TmpValue; if (FacebookInstantGamesIdValue->TryGetString(TmpValue)) { FacebookInstantGamesId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FFacebookPlayFabIdPair::~FFacebookPlayFabIdPair() { } void PlayFab::ServerModels::FFacebookPlayFabIdPair::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (FacebookId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("FacebookId")); writer->WriteValue(FacebookId); } if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FFacebookPlayFabIdPair::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> FacebookIdValue = obj->TryGetField(TEXT("FacebookId")); if (FacebookIdValue.IsValid() && !FacebookIdValue->IsNull()) { FString TmpValue; if (FacebookIdValue->TryGetString(TmpValue)) { FacebookId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } void PlayFab::ServerModels::writeLoginIdentityProviderEnumJSON(LoginIdentityProvider enumVal, JsonWriter& writer) { switch (enumVal) { case LoginIdentityProviderUnknown: writer->WriteValue(TEXT("Unknown")); break; case LoginIdentityProviderPlayFab: writer->WriteValue(TEXT("PlayFab")); break; case LoginIdentityProviderCustom: writer->WriteValue(TEXT("Custom")); break; case LoginIdentityProviderGameCenter: writer->WriteValue(TEXT("GameCenter")); break; case LoginIdentityProviderGooglePlay: writer->WriteValue(TEXT("GooglePlay")); break; case LoginIdentityProviderSteam: writer->WriteValue(TEXT("Steam")); break; case LoginIdentityProviderXBoxLive: writer->WriteValue(TEXT("XBoxLive")); break; case LoginIdentityProviderPSN: writer->WriteValue(TEXT("PSN")); break; case LoginIdentityProviderKongregate: writer->WriteValue(TEXT("Kongregate")); break; case LoginIdentityProviderFacebook: writer->WriteValue(TEXT("Facebook")); break; case LoginIdentityProviderIOSDevice: writer->WriteValue(TEXT("IOSDevice")); break; case LoginIdentityProviderAndroidDevice: writer->WriteValue(TEXT("AndroidDevice")); break; case LoginIdentityProviderTwitch: writer->WriteValue(TEXT("Twitch")); break; case LoginIdentityProviderWindowsHello: writer->WriteValue(TEXT("WindowsHello")); break; case LoginIdentityProviderGameServer: writer->WriteValue(TEXT("GameServer")); break; case LoginIdentityProviderCustomServer: writer->WriteValue(TEXT("CustomServer")); break; case LoginIdentityProviderNintendoSwitch: writer->WriteValue(TEXT("NintendoSwitch")); break; case LoginIdentityProviderFacebookInstantGames: writer->WriteValue(TEXT("FacebookInstantGames")); break; case LoginIdentityProviderOpenIdConnect: writer->WriteValue(TEXT("OpenIdConnect")); break; } } ServerModels::LoginIdentityProvider PlayFab::ServerModels::readLoginIdentityProviderFromValue(const TSharedPtr<FJsonValue>& value) { return readLoginIdentityProviderFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::LoginIdentityProvider PlayFab::ServerModels::readLoginIdentityProviderFromValue(const FString& value) { static TMap<FString, LoginIdentityProvider> _LoginIdentityProviderMap; if (_LoginIdentityProviderMap.Num() == 0) { // Auto-generate the map on the first use _LoginIdentityProviderMap.Add(TEXT("Unknown"), LoginIdentityProviderUnknown); _LoginIdentityProviderMap.Add(TEXT("PlayFab"), LoginIdentityProviderPlayFab); _LoginIdentityProviderMap.Add(TEXT("Custom"), LoginIdentityProviderCustom); _LoginIdentityProviderMap.Add(TEXT("GameCenter"), LoginIdentityProviderGameCenter); _LoginIdentityProviderMap.Add(TEXT("GooglePlay"), LoginIdentityProviderGooglePlay); _LoginIdentityProviderMap.Add(TEXT("Steam"), LoginIdentityProviderSteam); _LoginIdentityProviderMap.Add(TEXT("XBoxLive"), LoginIdentityProviderXBoxLive); _LoginIdentityProviderMap.Add(TEXT("PSN"), LoginIdentityProviderPSN); _LoginIdentityProviderMap.Add(TEXT("Kongregate"), LoginIdentityProviderKongregate); _LoginIdentityProviderMap.Add(TEXT("Facebook"), LoginIdentityProviderFacebook); _LoginIdentityProviderMap.Add(TEXT("IOSDevice"), LoginIdentityProviderIOSDevice); _LoginIdentityProviderMap.Add(TEXT("AndroidDevice"), LoginIdentityProviderAndroidDevice); _LoginIdentityProviderMap.Add(TEXT("Twitch"), LoginIdentityProviderTwitch); _LoginIdentityProviderMap.Add(TEXT("WindowsHello"), LoginIdentityProviderWindowsHello); _LoginIdentityProviderMap.Add(TEXT("GameServer"), LoginIdentityProviderGameServer); _LoginIdentityProviderMap.Add(TEXT("CustomServer"), LoginIdentityProviderCustomServer); _LoginIdentityProviderMap.Add(TEXT("NintendoSwitch"), LoginIdentityProviderNintendoSwitch); _LoginIdentityProviderMap.Add(TEXT("FacebookInstantGames"), LoginIdentityProviderFacebookInstantGames); _LoginIdentityProviderMap.Add(TEXT("OpenIdConnect"), LoginIdentityProviderOpenIdConnect); } if (!value.IsEmpty()) { auto output = _LoginIdentityProviderMap.Find(value); if (output != nullptr) return *output; } return LoginIdentityProviderUnknown; // Basically critical fail } PlayFab::ServerModels::FLinkedPlatformAccountModel::~FLinkedPlatformAccountModel() { } void PlayFab::ServerModels::FLinkedPlatformAccountModel::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Email.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Email")); writer->WriteValue(Email); } if (Platform.notNull()) { writer->WriteIdentifierPrefix(TEXT("Platform")); writeLoginIdentityProviderEnumJSON(Platform, writer); } if (PlatformUserId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlatformUserId")); writer->WriteValue(PlatformUserId); } if (Username.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Username")); writer->WriteValue(Username); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FLinkedPlatformAccountModel::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> EmailValue = obj->TryGetField(TEXT("Email")); if (EmailValue.IsValid() && !EmailValue->IsNull()) { FString TmpValue; if (EmailValue->TryGetString(TmpValue)) { Email = TmpValue; } } Platform = readLoginIdentityProviderFromValue(obj->TryGetField(TEXT("Platform"))); const TSharedPtr<FJsonValue> PlatformUserIdValue = obj->TryGetField(TEXT("PlatformUserId")); if (PlatformUserIdValue.IsValid() && !PlatformUserIdValue->IsNull()) { FString TmpValue; if (PlatformUserIdValue->TryGetString(TmpValue)) { PlatformUserId = TmpValue; } } const TSharedPtr<FJsonValue> UsernameValue = obj->TryGetField(TEXT("Username")); if (UsernameValue.IsValid() && !UsernameValue->IsNull()) { FString TmpValue; if (UsernameValue->TryGetString(TmpValue)) { Username = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FLocationModel::~FLocationModel() { } void PlayFab::ServerModels::FLocationModel::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (City.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("City")); writer->WriteValue(City); } if (pfContinentCode.notNull()) { writer->WriteIdentifierPrefix(TEXT("ContinentCode")); writeContinentCodeEnumJSON(pfContinentCode, writer); } if (pfCountryCode.notNull()) { writer->WriteIdentifierPrefix(TEXT("CountryCode")); writeCountryCodeEnumJSON(pfCountryCode, writer); } if (Latitude.notNull()) { writer->WriteIdentifierPrefix(TEXT("Latitude")); writer->WriteValue(Latitude); } if (Longitude.notNull()) { writer->WriteIdentifierPrefix(TEXT("Longitude")); writer->WriteValue(Longitude); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FLocationModel::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CityValue = obj->TryGetField(TEXT("City")); if (CityValue.IsValid() && !CityValue->IsNull()) { FString TmpValue; if (CityValue->TryGetString(TmpValue)) { City = TmpValue; } } pfContinentCode = readContinentCodeFromValue(obj->TryGetField(TEXT("ContinentCode"))); pfCountryCode = readCountryCodeFromValue(obj->TryGetField(TEXT("CountryCode"))); const TSharedPtr<FJsonValue> LatitudeValue = obj->TryGetField(TEXT("Latitude")); if (LatitudeValue.IsValid() && !LatitudeValue->IsNull()) { double TmpValue; if (LatitudeValue->TryGetNumber(TmpValue)) { Latitude = TmpValue; } } const TSharedPtr<FJsonValue> LongitudeValue = obj->TryGetField(TEXT("Longitude")); if (LongitudeValue.IsValid() && !LongitudeValue->IsNull()) { double TmpValue; if (LongitudeValue->TryGetNumber(TmpValue)) { Longitude = TmpValue; } } return HasSucceeded; } void PlayFab::ServerModels::writeSubscriptionProviderStatusEnumJSON(SubscriptionProviderStatus enumVal, JsonWriter& writer) { switch (enumVal) { case SubscriptionProviderStatusNoError: writer->WriteValue(TEXT("NoError")); break; case SubscriptionProviderStatusCancelled: writer->WriteValue(TEXT("Cancelled")); break; case SubscriptionProviderStatusUnknownError: writer->WriteValue(TEXT("UnknownError")); break; case SubscriptionProviderStatusBillingError: writer->WriteValue(TEXT("BillingError")); break; case SubscriptionProviderStatusProductUnavailable: writer->WriteValue(TEXT("ProductUnavailable")); break; case SubscriptionProviderStatusCustomerDidNotAcceptPriceChange: writer->WriteValue(TEXT("CustomerDidNotAcceptPriceChange")); break; case SubscriptionProviderStatusFreeTrial: writer->WriteValue(TEXT("FreeTrial")); break; case SubscriptionProviderStatusPaymentPending: writer->WriteValue(TEXT("PaymentPending")); break; } } ServerModels::SubscriptionProviderStatus PlayFab::ServerModels::readSubscriptionProviderStatusFromValue(const TSharedPtr<FJsonValue>& value) { return readSubscriptionProviderStatusFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::SubscriptionProviderStatus PlayFab::ServerModels::readSubscriptionProviderStatusFromValue(const FString& value) { static TMap<FString, SubscriptionProviderStatus> _SubscriptionProviderStatusMap; if (_SubscriptionProviderStatusMap.Num() == 0) { // Auto-generate the map on the first use _SubscriptionProviderStatusMap.Add(TEXT("NoError"), SubscriptionProviderStatusNoError); _SubscriptionProviderStatusMap.Add(TEXT("Cancelled"), SubscriptionProviderStatusCancelled); _SubscriptionProviderStatusMap.Add(TEXT("UnknownError"), SubscriptionProviderStatusUnknownError); _SubscriptionProviderStatusMap.Add(TEXT("BillingError"), SubscriptionProviderStatusBillingError); _SubscriptionProviderStatusMap.Add(TEXT("ProductUnavailable"), SubscriptionProviderStatusProductUnavailable); _SubscriptionProviderStatusMap.Add(TEXT("CustomerDidNotAcceptPriceChange"), SubscriptionProviderStatusCustomerDidNotAcceptPriceChange); _SubscriptionProviderStatusMap.Add(TEXT("FreeTrial"), SubscriptionProviderStatusFreeTrial); _SubscriptionProviderStatusMap.Add(TEXT("PaymentPending"), SubscriptionProviderStatusPaymentPending); } if (!value.IsEmpty()) { auto output = _SubscriptionProviderStatusMap.Find(value); if (output != nullptr) return *output; } return SubscriptionProviderStatusNoError; // Basically critical fail } PlayFab::ServerModels::FSubscriptionModel::~FSubscriptionModel() { } void PlayFab::ServerModels::FSubscriptionModel::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Expiration")); writeDatetime(Expiration, writer); writer->WriteIdentifierPrefix(TEXT("InitialSubscriptionTime")); writeDatetime(InitialSubscriptionTime, writer); writer->WriteIdentifierPrefix(TEXT("IsActive")); writer->WriteValue(IsActive); if (Status.notNull()) { writer->WriteIdentifierPrefix(TEXT("Status")); writeSubscriptionProviderStatusEnumJSON(Status, writer); } if (SubscriptionId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("SubscriptionId")); writer->WriteValue(SubscriptionId); } if (SubscriptionItemId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("SubscriptionItemId")); writer->WriteValue(SubscriptionItemId); } if (SubscriptionProvider.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("SubscriptionProvider")); writer->WriteValue(SubscriptionProvider); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSubscriptionModel::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ExpirationValue = obj->TryGetField(TEXT("Expiration")); if (ExpirationValue.IsValid()) Expiration = readDatetime(ExpirationValue); const TSharedPtr<FJsonValue> InitialSubscriptionTimeValue = obj->TryGetField(TEXT("InitialSubscriptionTime")); if (InitialSubscriptionTimeValue.IsValid()) InitialSubscriptionTime = readDatetime(InitialSubscriptionTimeValue); const TSharedPtr<FJsonValue> IsActiveValue = obj->TryGetField(TEXT("IsActive")); if (IsActiveValue.IsValid() && !IsActiveValue->IsNull()) { bool TmpValue; if (IsActiveValue->TryGetBool(TmpValue)) { IsActive = TmpValue; } } Status = readSubscriptionProviderStatusFromValue(obj->TryGetField(TEXT("Status"))); const TSharedPtr<FJsonValue> SubscriptionIdValue = obj->TryGetField(TEXT("SubscriptionId")); if (SubscriptionIdValue.IsValid() && !SubscriptionIdValue->IsNull()) { FString TmpValue; if (SubscriptionIdValue->TryGetString(TmpValue)) { SubscriptionId = TmpValue; } } const TSharedPtr<FJsonValue> SubscriptionItemIdValue = obj->TryGetField(TEXT("SubscriptionItemId")); if (SubscriptionItemIdValue.IsValid() && !SubscriptionItemIdValue->IsNull()) { FString TmpValue; if (SubscriptionItemIdValue->TryGetString(TmpValue)) { SubscriptionItemId = TmpValue; } } const TSharedPtr<FJsonValue> SubscriptionProviderValue = obj->TryGetField(TEXT("SubscriptionProvider")); if (SubscriptionProviderValue.IsValid() && !SubscriptionProviderValue->IsNull()) { FString TmpValue; if (SubscriptionProviderValue->TryGetString(TmpValue)) { SubscriptionProvider = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FMembershipModel::~FMembershipModel() { } void PlayFab::ServerModels::FMembershipModel::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("IsActive")); writer->WriteValue(IsActive); writer->WriteIdentifierPrefix(TEXT("MembershipExpiration")); writeDatetime(MembershipExpiration, writer); if (MembershipId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("MembershipId")); writer->WriteValue(MembershipId); } if (OverrideExpiration.notNull()) { writer->WriteIdentifierPrefix(TEXT("OverrideExpiration")); writeDatetime(OverrideExpiration, writer); } if (OverrideIsSet.notNull()) { writer->WriteIdentifierPrefix(TEXT("OverrideIsSet")); writer->WriteValue(OverrideIsSet); } if (Subscriptions.Num() != 0) { writer->WriteArrayStart(TEXT("Subscriptions")); for (const FSubscriptionModel& item : Subscriptions) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FMembershipModel::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> IsActiveValue = obj->TryGetField(TEXT("IsActive")); if (IsActiveValue.IsValid() && !IsActiveValue->IsNull()) { bool TmpValue; if (IsActiveValue->TryGetBool(TmpValue)) { IsActive = TmpValue; } } const TSharedPtr<FJsonValue> MembershipExpirationValue = obj->TryGetField(TEXT("MembershipExpiration")); if (MembershipExpirationValue.IsValid()) MembershipExpiration = readDatetime(MembershipExpirationValue); const TSharedPtr<FJsonValue> MembershipIdValue = obj->TryGetField(TEXT("MembershipId")); if (MembershipIdValue.IsValid() && !MembershipIdValue->IsNull()) { FString TmpValue; if (MembershipIdValue->TryGetString(TmpValue)) { MembershipId = TmpValue; } } const TSharedPtr<FJsonValue> OverrideExpirationValue = obj->TryGetField(TEXT("OverrideExpiration")); if (OverrideExpirationValue.IsValid()) OverrideExpiration = readDatetime(OverrideExpirationValue); const TSharedPtr<FJsonValue> OverrideIsSetValue = obj->TryGetField(TEXT("OverrideIsSet")); if (OverrideIsSetValue.IsValid() && !OverrideIsSetValue->IsNull()) { bool TmpValue; if (OverrideIsSetValue->TryGetBool(TmpValue)) { OverrideIsSet = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&SubscriptionsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Subscriptions")); for (int32 Idx = 0; Idx < SubscriptionsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = SubscriptionsArray[Idx]; Subscriptions.Add(FSubscriptionModel(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FPushNotificationRegistrationModel::~FPushNotificationRegistrationModel() { } void PlayFab::ServerModels::FPushNotificationRegistrationModel::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (NotificationEndpointARN.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("NotificationEndpointARN")); writer->WriteValue(NotificationEndpointARN); } if (Platform.notNull()) { writer->WriteIdentifierPrefix(TEXT("Platform")); writePushNotificationPlatformEnumJSON(Platform, writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FPushNotificationRegistrationModel::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> NotificationEndpointARNValue = obj->TryGetField(TEXT("NotificationEndpointARN")); if (NotificationEndpointARNValue.IsValid() && !NotificationEndpointARNValue->IsNull()) { FString TmpValue; if (NotificationEndpointARNValue->TryGetString(TmpValue)) { NotificationEndpointARN = TmpValue; } } Platform = readPushNotificationPlatformFromValue(obj->TryGetField(TEXT("Platform"))); return HasSucceeded; } PlayFab::ServerModels::FStatisticModel::~FStatisticModel() { } void PlayFab::ServerModels::FStatisticModel::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Name.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Name")); writer->WriteValue(Name); } writer->WriteIdentifierPrefix(TEXT("Value")); writer->WriteValue(Value); writer->WriteIdentifierPrefix(TEXT("Version")); writer->WriteValue(Version); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FStatisticModel::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> NameValue = obj->TryGetField(TEXT("Name")); if (NameValue.IsValid() && !NameValue->IsNull()) { FString TmpValue; if (NameValue->TryGetString(TmpValue)) { Name = TmpValue; } } const TSharedPtr<FJsonValue> ValueValue = obj->TryGetField(TEXT("Value")); if (ValueValue.IsValid() && !ValueValue->IsNull()) { int32 TmpValue; if (ValueValue->TryGetNumber(TmpValue)) { Value = TmpValue; } } const TSharedPtr<FJsonValue> VersionValue = obj->TryGetField(TEXT("Version")); if (VersionValue.IsValid() && !VersionValue->IsNull()) { int32 TmpValue; if (VersionValue->TryGetNumber(TmpValue)) { Version = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FTagModel::~FTagModel() { } void PlayFab::ServerModels::FTagModel::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (TagValue.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("TagValue")); writer->WriteValue(TagValue); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FTagModel::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> TagValueValue = obj->TryGetField(TEXT("TagValue")); if (TagValueValue.IsValid() && !TagValueValue->IsNull()) { FString TmpValue; if (TagValueValue->TryGetString(TmpValue)) { TagValue = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FValueToDateModel::~FValueToDateModel() { } void PlayFab::ServerModels::FValueToDateModel::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Currency.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Currency")); writer->WriteValue(Currency); } writer->WriteIdentifierPrefix(TEXT("TotalValue")); writer->WriteValue(static_cast<int64>(TotalValue)); if (TotalValueAsDecimal.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("TotalValueAsDecimal")); writer->WriteValue(TotalValueAsDecimal); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FValueToDateModel::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CurrencyValue = obj->TryGetField(TEXT("Currency")); if (CurrencyValue.IsValid() && !CurrencyValue->IsNull()) { FString TmpValue; if (CurrencyValue->TryGetString(TmpValue)) { Currency = TmpValue; } } const TSharedPtr<FJsonValue> TotalValueValue = obj->TryGetField(TEXT("TotalValue")); if (TotalValueValue.IsValid() && !TotalValueValue->IsNull()) { uint32 TmpValue; if (TotalValueValue->TryGetNumber(TmpValue)) { TotalValue = TmpValue; } } const TSharedPtr<FJsonValue> TotalValueAsDecimalValue = obj->TryGetField(TEXT("TotalValueAsDecimal")); if (TotalValueAsDecimalValue.IsValid() && !TotalValueAsDecimalValue->IsNull()) { FString TmpValue; if (TotalValueAsDecimalValue->TryGetString(TmpValue)) { TotalValueAsDecimal = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FPlayerProfileModel::~FPlayerProfileModel() { } void PlayFab::ServerModels::FPlayerProfileModel::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (AdCampaignAttributions.Num() != 0) { writer->WriteArrayStart(TEXT("AdCampaignAttributions")); for (const FAdCampaignAttributionModel& item : AdCampaignAttributions) item.writeJSON(writer); writer->WriteArrayEnd(); } if (AvatarUrl.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("AvatarUrl")); writer->WriteValue(AvatarUrl); } if (BannedUntil.notNull()) { writer->WriteIdentifierPrefix(TEXT("BannedUntil")); writeDatetime(BannedUntil, writer); } if (ContactEmailAddresses.Num() != 0) { writer->WriteArrayStart(TEXT("ContactEmailAddresses")); for (const FContactEmailInfoModel& item : ContactEmailAddresses) item.writeJSON(writer); writer->WriteArrayEnd(); } if (Created.notNull()) { writer->WriteIdentifierPrefix(TEXT("Created")); writeDatetime(Created, writer); } if (DisplayName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("DisplayName")); writer->WriteValue(DisplayName); } if (LastLogin.notNull()) { writer->WriteIdentifierPrefix(TEXT("LastLogin")); writeDatetime(LastLogin, writer); } if (LinkedAccounts.Num() != 0) { writer->WriteArrayStart(TEXT("LinkedAccounts")); for (const FLinkedPlatformAccountModel& item : LinkedAccounts) item.writeJSON(writer); writer->WriteArrayEnd(); } if (Locations.Num() != 0) { writer->WriteArrayStart(TEXT("Locations")); for (const FLocationModel& item : Locations) item.writeJSON(writer); writer->WriteArrayEnd(); } if (Memberships.Num() != 0) { writer->WriteArrayStart(TEXT("Memberships")); for (const FMembershipModel& item : Memberships) item.writeJSON(writer); writer->WriteArrayEnd(); } if (Origination.notNull()) { writer->WriteIdentifierPrefix(TEXT("Origination")); writeLoginIdentityProviderEnumJSON(Origination, writer); } if (PlayerId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayerId")); writer->WriteValue(PlayerId); } if (PublisherId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PublisherId")); writer->WriteValue(PublisherId); } if (PushNotificationRegistrations.Num() != 0) { writer->WriteArrayStart(TEXT("PushNotificationRegistrations")); for (const FPushNotificationRegistrationModel& item : PushNotificationRegistrations) item.writeJSON(writer); writer->WriteArrayEnd(); } if (Statistics.Num() != 0) { writer->WriteArrayStart(TEXT("Statistics")); for (const FStatisticModel& item : Statistics) item.writeJSON(writer); writer->WriteArrayEnd(); } if (Tags.Num() != 0) { writer->WriteArrayStart(TEXT("Tags")); for (const FTagModel& item : Tags) item.writeJSON(writer); writer->WriteArrayEnd(); } if (TitleId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("TitleId")); writer->WriteValue(TitleId); } if (TotalValueToDateInUSD.notNull()) { writer->WriteIdentifierPrefix(TEXT("TotalValueToDateInUSD")); writer->WriteValue(static_cast<int64>(TotalValueToDateInUSD)); } if (ValuesToDate.Num() != 0) { writer->WriteArrayStart(TEXT("ValuesToDate")); for (const FValueToDateModel& item : ValuesToDate) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FPlayerProfileModel::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&AdCampaignAttributionsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("AdCampaignAttributions")); for (int32 Idx = 0; Idx < AdCampaignAttributionsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = AdCampaignAttributionsArray[Idx]; AdCampaignAttributions.Add(FAdCampaignAttributionModel(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> AvatarUrlValue = obj->TryGetField(TEXT("AvatarUrl")); if (AvatarUrlValue.IsValid() && !AvatarUrlValue->IsNull()) { FString TmpValue; if (AvatarUrlValue->TryGetString(TmpValue)) { AvatarUrl = TmpValue; } } const TSharedPtr<FJsonValue> BannedUntilValue = obj->TryGetField(TEXT("BannedUntil")); if (BannedUntilValue.IsValid()) BannedUntil = readDatetime(BannedUntilValue); const TArray<TSharedPtr<FJsonValue>>&ContactEmailAddressesArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("ContactEmailAddresses")); for (int32 Idx = 0; Idx < ContactEmailAddressesArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = ContactEmailAddressesArray[Idx]; ContactEmailAddresses.Add(FContactEmailInfoModel(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> CreatedValue = obj->TryGetField(TEXT("Created")); if (CreatedValue.IsValid()) Created = readDatetime(CreatedValue); const TSharedPtr<FJsonValue> DisplayNameValue = obj->TryGetField(TEXT("DisplayName")); if (DisplayNameValue.IsValid() && !DisplayNameValue->IsNull()) { FString TmpValue; if (DisplayNameValue->TryGetString(TmpValue)) { DisplayName = TmpValue; } } const TSharedPtr<FJsonValue> LastLoginValue = obj->TryGetField(TEXT("LastLogin")); if (LastLoginValue.IsValid()) LastLogin = readDatetime(LastLoginValue); const TArray<TSharedPtr<FJsonValue>>&LinkedAccountsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("LinkedAccounts")); for (int32 Idx = 0; Idx < LinkedAccountsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = LinkedAccountsArray[Idx]; LinkedAccounts.Add(FLinkedPlatformAccountModel(CurrentItem->AsObject())); } const TArray<TSharedPtr<FJsonValue>>&LocationsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Locations")); for (int32 Idx = 0; Idx < LocationsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = LocationsArray[Idx]; Locations.Add(FLocationModel(CurrentItem->AsObject())); } const TArray<TSharedPtr<FJsonValue>>&MembershipsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Memberships")); for (int32 Idx = 0; Idx < MembershipsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = MembershipsArray[Idx]; Memberships.Add(FMembershipModel(CurrentItem->AsObject())); } Origination = readLoginIdentityProviderFromValue(obj->TryGetField(TEXT("Origination"))); const TSharedPtr<FJsonValue> PlayerIdValue = obj->TryGetField(TEXT("PlayerId")); if (PlayerIdValue.IsValid() && !PlayerIdValue->IsNull()) { FString TmpValue; if (PlayerIdValue->TryGetString(TmpValue)) { PlayerId = TmpValue; } } const TSharedPtr<FJsonValue> PublisherIdValue = obj->TryGetField(TEXT("PublisherId")); if (PublisherIdValue.IsValid() && !PublisherIdValue->IsNull()) { FString TmpValue; if (PublisherIdValue->TryGetString(TmpValue)) { PublisherId = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&PushNotificationRegistrationsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("PushNotificationRegistrations")); for (int32 Idx = 0; Idx < PushNotificationRegistrationsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = PushNotificationRegistrationsArray[Idx]; PushNotificationRegistrations.Add(FPushNotificationRegistrationModel(CurrentItem->AsObject())); } const TArray<TSharedPtr<FJsonValue>>&StatisticsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Statistics")); for (int32 Idx = 0; Idx < StatisticsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = StatisticsArray[Idx]; Statistics.Add(FStatisticModel(CurrentItem->AsObject())); } const TArray<TSharedPtr<FJsonValue>>&TagsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Tags")); for (int32 Idx = 0; Idx < TagsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = TagsArray[Idx]; Tags.Add(FTagModel(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> TitleIdValue = obj->TryGetField(TEXT("TitleId")); if (TitleIdValue.IsValid() && !TitleIdValue->IsNull()) { FString TmpValue; if (TitleIdValue->TryGetString(TmpValue)) { TitleId = TmpValue; } } const TSharedPtr<FJsonValue> TotalValueToDateInUSDValue = obj->TryGetField(TEXT("TotalValueToDateInUSD")); if (TotalValueToDateInUSDValue.IsValid() && !TotalValueToDateInUSDValue->IsNull()) { uint32 TmpValue; if (TotalValueToDateInUSDValue->TryGetNumber(TmpValue)) { TotalValueToDateInUSD = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&ValuesToDateArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("ValuesToDate")); for (int32 Idx = 0; Idx < ValuesToDateArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = ValuesToDateArray[Idx]; ValuesToDate.Add(FValueToDateModel(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FFriendInfo::~FFriendInfo() { //if (FacebookInfo != nullptr) delete FacebookInfo; //if (GameCenterInfo != nullptr) delete GameCenterInfo; //if (Profile != nullptr) delete Profile; //if (PSNInfo != nullptr) delete PSNInfo; //if (SteamInfo != nullptr) delete SteamInfo; //if (XboxInfo != nullptr) delete XboxInfo; } void PlayFab::ServerModels::FFriendInfo::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (FacebookInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("FacebookInfo")); FacebookInfo->writeJSON(writer); } if (FriendPlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("FriendPlayFabId")); writer->WriteValue(FriendPlayFabId); } if (GameCenterInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("GameCenterInfo")); GameCenterInfo->writeJSON(writer); } if (Profile.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Profile")); Profile->writeJSON(writer); } if (PSNInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("PSNInfo")); PSNInfo->writeJSON(writer); } if (SteamInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("SteamInfo")); SteamInfo->writeJSON(writer); } if (Tags.Num() != 0) { writer->WriteArrayStart(TEXT("Tags")); for (const FString& item : Tags) writer->WriteValue(item); writer->WriteArrayEnd(); } if (TitleDisplayName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("TitleDisplayName")); writer->WriteValue(TitleDisplayName); } if (Username.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Username")); writer->WriteValue(Username); } if (XboxInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("XboxInfo")); XboxInfo->writeJSON(writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FFriendInfo::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> FacebookInfoValue = obj->TryGetField(TEXT("FacebookInfo")); if (FacebookInfoValue.IsValid() && !FacebookInfoValue->IsNull()) { FacebookInfo = MakeShareable(new FUserFacebookInfo(FacebookInfoValue->AsObject())); } const TSharedPtr<FJsonValue> FriendPlayFabIdValue = obj->TryGetField(TEXT("FriendPlayFabId")); if (FriendPlayFabIdValue.IsValid() && !FriendPlayFabIdValue->IsNull()) { FString TmpValue; if (FriendPlayFabIdValue->TryGetString(TmpValue)) { FriendPlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> GameCenterInfoValue = obj->TryGetField(TEXT("GameCenterInfo")); if (GameCenterInfoValue.IsValid() && !GameCenterInfoValue->IsNull()) { GameCenterInfo = MakeShareable(new FUserGameCenterInfo(GameCenterInfoValue->AsObject())); } const TSharedPtr<FJsonValue> ProfileValue = obj->TryGetField(TEXT("Profile")); if (ProfileValue.IsValid() && !ProfileValue->IsNull()) { Profile = MakeShareable(new FPlayerProfileModel(ProfileValue->AsObject())); } const TSharedPtr<FJsonValue> PSNInfoValue = obj->TryGetField(TEXT("PSNInfo")); if (PSNInfoValue.IsValid() && !PSNInfoValue->IsNull()) { PSNInfo = MakeShareable(new FUserPsnInfo(PSNInfoValue->AsObject())); } const TSharedPtr<FJsonValue> SteamInfoValue = obj->TryGetField(TEXT("SteamInfo")); if (SteamInfoValue.IsValid() && !SteamInfoValue->IsNull()) { SteamInfo = MakeShareable(new FUserSteamInfo(SteamInfoValue->AsObject())); } obj->TryGetStringArrayField(TEXT("Tags"), Tags); const TSharedPtr<FJsonValue> TitleDisplayNameValue = obj->TryGetField(TEXT("TitleDisplayName")); if (TitleDisplayNameValue.IsValid() && !TitleDisplayNameValue->IsNull()) { FString TmpValue; if (TitleDisplayNameValue->TryGetString(TmpValue)) { TitleDisplayName = TmpValue; } } const TSharedPtr<FJsonValue> UsernameValue = obj->TryGetField(TEXT("Username")); if (UsernameValue.IsValid() && !UsernameValue->IsNull()) { FString TmpValue; if (UsernameValue->TryGetString(TmpValue)) { Username = TmpValue; } } const TSharedPtr<FJsonValue> XboxInfoValue = obj->TryGetField(TEXT("XboxInfo")); if (XboxInfoValue.IsValid() && !XboxInfoValue->IsNull()) { XboxInfo = MakeShareable(new FUserXboxInfo(XboxInfoValue->AsObject())); } return HasSucceeded; } void PlayFab::ServerModels::writeGameInstanceStateEnumJSON(GameInstanceState enumVal, JsonWriter& writer) { switch (enumVal) { case GameInstanceStateOpen: writer->WriteValue(TEXT("Open")); break; case GameInstanceStateClosed: writer->WriteValue(TEXT("Closed")); break; } } ServerModels::GameInstanceState PlayFab::ServerModels::readGameInstanceStateFromValue(const TSharedPtr<FJsonValue>& value) { return readGameInstanceStateFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::GameInstanceState PlayFab::ServerModels::readGameInstanceStateFromValue(const FString& value) { static TMap<FString, GameInstanceState> _GameInstanceStateMap; if (_GameInstanceStateMap.Num() == 0) { // Auto-generate the map on the first use _GameInstanceStateMap.Add(TEXT("Open"), GameInstanceStateOpen); _GameInstanceStateMap.Add(TEXT("Closed"), GameInstanceStateClosed); } if (!value.IsEmpty()) { auto output = _GameInstanceStateMap.Find(value); if (output != nullptr) return *output; } return GameInstanceStateOpen; // Basically critical fail } PlayFab::ServerModels::FGenericPlayFabIdPair::~FGenericPlayFabIdPair() { //if (GenericId != nullptr) delete GenericId; } void PlayFab::ServerModels::FGenericPlayFabIdPair::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (GenericId.IsValid()) { writer->WriteIdentifierPrefix(TEXT("GenericId")); GenericId->writeJSON(writer); } if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGenericPlayFabIdPair::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> GenericIdValue = obj->TryGetField(TEXT("GenericId")); if (GenericIdValue.IsValid() && !GenericIdValue->IsNull()) { GenericId = MakeShareable(new FGenericServiceId(GenericIdValue->AsObject())); } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetAllSegmentsRequest::~FGetAllSegmentsRequest() { } void PlayFab::ServerModels::FGetAllSegmentsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetAllSegmentsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FGetSegmentResult::~FGetSegmentResult() { } void PlayFab::ServerModels::FGetSegmentResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (ABTestParent.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ABTestParent")); writer->WriteValue(ABTestParent); } writer->WriteIdentifierPrefix(TEXT("Id")); writer->WriteValue(Id); if (Name.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Name")); writer->WriteValue(Name); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetSegmentResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ABTestParentValue = obj->TryGetField(TEXT("ABTestParent")); if (ABTestParentValue.IsValid() && !ABTestParentValue->IsNull()) { FString TmpValue; if (ABTestParentValue->TryGetString(TmpValue)) { ABTestParent = TmpValue; } } const TSharedPtr<FJsonValue> IdValue = obj->TryGetField(TEXT("Id")); if (IdValue.IsValid() && !IdValue->IsNull()) { FString TmpValue; if (IdValue->TryGetString(TmpValue)) { Id = TmpValue; } } const TSharedPtr<FJsonValue> NameValue = obj->TryGetField(TEXT("Name")); if (NameValue.IsValid() && !NameValue->IsNull()) { FString TmpValue; if (NameValue->TryGetString(TmpValue)) { Name = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetAllSegmentsResult::~FGetAllSegmentsResult() { } void PlayFab::ServerModels::FGetAllSegmentsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Segments.Num() != 0) { writer->WriteArrayStart(TEXT("Segments")); for (const FGetSegmentResult& item : Segments) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetAllSegmentsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&SegmentsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Segments")); for (int32 Idx = 0; Idx < SegmentsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = SegmentsArray[Idx]; Segments.Add(FGetSegmentResult(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetCatalogItemsRequest::~FGetCatalogItemsRequest() { } void PlayFab::ServerModels::FGetCatalogItemsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetCatalogItemsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetCatalogItemsResult::~FGetCatalogItemsResult() { } void PlayFab::ServerModels::FGetCatalogItemsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Catalog.Num() != 0) { writer->WriteArrayStart(TEXT("Catalog")); for (const FCatalogItem& item : Catalog) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetCatalogItemsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&CatalogArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Catalog")); for (int32 Idx = 0; Idx < CatalogArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = CatalogArray[Idx]; Catalog.Add(FCatalogItem(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetCharacterDataRequest::~FGetCharacterDataRequest() { } void PlayFab::ServerModels::FGetCharacterDataRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); if (IfChangedFromDataVersion.notNull()) { writer->WriteIdentifierPrefix(TEXT("IfChangedFromDataVersion")); writer->WriteValue(static_cast<int64>(IfChangedFromDataVersion)); } if (Keys.Num() != 0) { writer->WriteArrayStart(TEXT("Keys")); for (const FString& item : Keys) writer->WriteValue(item); writer->WriteArrayEnd(); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetCharacterDataRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> IfChangedFromDataVersionValue = obj->TryGetField(TEXT("IfChangedFromDataVersion")); if (IfChangedFromDataVersionValue.IsValid() && !IfChangedFromDataVersionValue->IsNull()) { uint32 TmpValue; if (IfChangedFromDataVersionValue->TryGetNumber(TmpValue)) { IfChangedFromDataVersion = TmpValue; } } obj->TryGetStringArrayField(TEXT("Keys"), Keys); const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } void PlayFab::ServerModels::writeUserDataPermissionEnumJSON(UserDataPermission enumVal, JsonWriter& writer) { switch (enumVal) { case UserDataPermissionPrivate: writer->WriteValue(TEXT("Private")); break; case UserDataPermissionPublic: writer->WriteValue(TEXT("Public")); break; } } ServerModels::UserDataPermission PlayFab::ServerModels::readUserDataPermissionFromValue(const TSharedPtr<FJsonValue>& value) { return readUserDataPermissionFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::UserDataPermission PlayFab::ServerModels::readUserDataPermissionFromValue(const FString& value) { static TMap<FString, UserDataPermission> _UserDataPermissionMap; if (_UserDataPermissionMap.Num() == 0) { // Auto-generate the map on the first use _UserDataPermissionMap.Add(TEXT("Private"), UserDataPermissionPrivate); _UserDataPermissionMap.Add(TEXT("Public"), UserDataPermissionPublic); } if (!value.IsEmpty()) { auto output = _UserDataPermissionMap.Find(value); if (output != nullptr) return *output; } return UserDataPermissionPrivate; // Basically critical fail } PlayFab::ServerModels::FUserDataRecord::~FUserDataRecord() { } void PlayFab::ServerModels::FUserDataRecord::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("LastUpdated")); writeDatetime(LastUpdated, writer); if (Permission.notNull()) { writer->WriteIdentifierPrefix(TEXT("Permission")); writeUserDataPermissionEnumJSON(Permission, writer); } if (Value.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Value")); writer->WriteValue(Value); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserDataRecord::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> LastUpdatedValue = obj->TryGetField(TEXT("LastUpdated")); if (LastUpdatedValue.IsValid()) LastUpdated = readDatetime(LastUpdatedValue); Permission = readUserDataPermissionFromValue(obj->TryGetField(TEXT("Permission"))); const TSharedPtr<FJsonValue> ValueValue = obj->TryGetField(TEXT("Value")); if (ValueValue.IsValid() && !ValueValue->IsNull()) { FString TmpValue; if (ValueValue->TryGetString(TmpValue)) { Value = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetCharacterDataResult::~FGetCharacterDataResult() { } void PlayFab::ServerModels::FGetCharacterDataResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } if (Data.Num() != 0) { writer->WriteObjectStart(TEXT("Data")); for (TMap<FString, FUserDataRecord>::TConstIterator It(Data); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteIdentifierPrefix(TEXT("DataVersion")); writer->WriteValue(static_cast<int64>(DataVersion)); if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetCharacterDataResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonObject>* DataObject; if (obj->TryGetObjectField(TEXT("Data"), DataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*DataObject)->Values); It; ++It) { Data.Add(It.Key(), FUserDataRecord(It.Value()->AsObject())); } } const TSharedPtr<FJsonValue> DataVersionValue = obj->TryGetField(TEXT("DataVersion")); if (DataVersionValue.IsValid() && !DataVersionValue->IsNull()) { uint32 TmpValue; if (DataVersionValue->TryGetNumber(TmpValue)) { DataVersion = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetCharacterInventoryRequest::~FGetCharacterInventoryRequest() { } void PlayFab::ServerModels::FGetCharacterInventoryRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetCharacterInventoryRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FVirtualCurrencyRechargeTime::~FVirtualCurrencyRechargeTime() { } void PlayFab::ServerModels::FVirtualCurrencyRechargeTime::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("RechargeMax")); writer->WriteValue(RechargeMax); writer->WriteIdentifierPrefix(TEXT("RechargeTime")); writeDatetime(RechargeTime, writer); writer->WriteIdentifierPrefix(TEXT("SecondsToRecharge")); writer->WriteValue(SecondsToRecharge); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FVirtualCurrencyRechargeTime::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> RechargeMaxValue = obj->TryGetField(TEXT("RechargeMax")); if (RechargeMaxValue.IsValid() && !RechargeMaxValue->IsNull()) { int32 TmpValue; if (RechargeMaxValue->TryGetNumber(TmpValue)) { RechargeMax = TmpValue; } } const TSharedPtr<FJsonValue> RechargeTimeValue = obj->TryGetField(TEXT("RechargeTime")); if (RechargeTimeValue.IsValid()) RechargeTime = readDatetime(RechargeTimeValue); const TSharedPtr<FJsonValue> SecondsToRechargeValue = obj->TryGetField(TEXT("SecondsToRecharge")); if (SecondsToRechargeValue.IsValid() && !SecondsToRechargeValue->IsNull()) { int32 TmpValue; if (SecondsToRechargeValue->TryGetNumber(TmpValue)) { SecondsToRecharge = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetCharacterInventoryResult::~FGetCharacterInventoryResult() { } void PlayFab::ServerModels::FGetCharacterInventoryResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } if (Inventory.Num() != 0) { writer->WriteArrayStart(TEXT("Inventory")); for (const FItemInstance& item : Inventory) item.writeJSON(writer); writer->WriteArrayEnd(); } if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } if (VirtualCurrency.Num() != 0) { writer->WriteObjectStart(TEXT("VirtualCurrency")); for (TMap<FString, int32>::TConstIterator It(VirtualCurrency); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (VirtualCurrencyRechargeTimes.Num() != 0) { writer->WriteObjectStart(TEXT("VirtualCurrencyRechargeTimes")); for (TMap<FString, FVirtualCurrencyRechargeTime>::TConstIterator It(VirtualCurrencyRechargeTimes); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetCharacterInventoryResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&InventoryArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Inventory")); for (int32 Idx = 0; Idx < InventoryArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = InventoryArray[Idx]; Inventory.Add(FItemInstance(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonObject>* VirtualCurrencyObject; if (obj->TryGetObjectField(TEXT("VirtualCurrency"), VirtualCurrencyObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*VirtualCurrencyObject)->Values); It; ++It) { int32 TmpValue; It.Value()->TryGetNumber(TmpValue); VirtualCurrency.Add(It.Key(), TmpValue); } } const TSharedPtr<FJsonObject>* VirtualCurrencyRechargeTimesObject; if (obj->TryGetObjectField(TEXT("VirtualCurrencyRechargeTimes"), VirtualCurrencyRechargeTimesObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*VirtualCurrencyRechargeTimesObject)->Values); It; ++It) { VirtualCurrencyRechargeTimes.Add(It.Key(), FVirtualCurrencyRechargeTime(It.Value()->AsObject())); } } return HasSucceeded; } PlayFab::ServerModels::FGetCharacterLeaderboardRequest::~FGetCharacterLeaderboardRequest() { } void PlayFab::ServerModels::FGetCharacterLeaderboardRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CharacterType.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterType")); writer->WriteValue(CharacterType); } writer->WriteIdentifierPrefix(TEXT("MaxResultsCount")); writer->WriteValue(MaxResultsCount); writer->WriteIdentifierPrefix(TEXT("StartPosition")); writer->WriteValue(StartPosition); writer->WriteIdentifierPrefix(TEXT("StatisticName")); writer->WriteValue(StatisticName); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetCharacterLeaderboardRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterTypeValue = obj->TryGetField(TEXT("CharacterType")); if (CharacterTypeValue.IsValid() && !CharacterTypeValue->IsNull()) { FString TmpValue; if (CharacterTypeValue->TryGetString(TmpValue)) { CharacterType = TmpValue; } } const TSharedPtr<FJsonValue> MaxResultsCountValue = obj->TryGetField(TEXT("MaxResultsCount")); if (MaxResultsCountValue.IsValid() && !MaxResultsCountValue->IsNull()) { int32 TmpValue; if (MaxResultsCountValue->TryGetNumber(TmpValue)) { MaxResultsCount = TmpValue; } } const TSharedPtr<FJsonValue> StartPositionValue = obj->TryGetField(TEXT("StartPosition")); if (StartPositionValue.IsValid() && !StartPositionValue->IsNull()) { int32 TmpValue; if (StartPositionValue->TryGetNumber(TmpValue)) { StartPosition = TmpValue; } } const TSharedPtr<FJsonValue> StatisticNameValue = obj->TryGetField(TEXT("StatisticName")); if (StatisticNameValue.IsValid() && !StatisticNameValue->IsNull()) { FString TmpValue; if (StatisticNameValue->TryGetString(TmpValue)) { StatisticName = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetCharacterLeaderboardResult::~FGetCharacterLeaderboardResult() { } void PlayFab::ServerModels::FGetCharacterLeaderboardResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Leaderboard.Num() != 0) { writer->WriteArrayStart(TEXT("Leaderboard")); for (const FCharacterLeaderboardEntry& item : Leaderboard) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetCharacterLeaderboardResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&LeaderboardArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Leaderboard")); for (int32 Idx = 0; Idx < LeaderboardArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = LeaderboardArray[Idx]; Leaderboard.Add(FCharacterLeaderboardEntry(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetCharacterStatisticsRequest::~FGetCharacterStatisticsRequest() { } void PlayFab::ServerModels::FGetCharacterStatisticsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetCharacterStatisticsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetCharacterStatisticsResult::~FGetCharacterStatisticsResult() { } void PlayFab::ServerModels::FGetCharacterStatisticsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } if (CharacterStatistics.Num() != 0) { writer->WriteObjectStart(TEXT("CharacterStatistics")); for (TMap<FString, int32>::TConstIterator It(CharacterStatistics); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetCharacterStatisticsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonObject>* CharacterStatisticsObject; if (obj->TryGetObjectField(TEXT("CharacterStatistics"), CharacterStatisticsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*CharacterStatisticsObject)->Values); It; ++It) { int32 TmpValue; It.Value()->TryGetNumber(TmpValue); CharacterStatistics.Add(It.Key(), TmpValue); } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetContentDownloadUrlRequest::~FGetContentDownloadUrlRequest() { } void PlayFab::ServerModels::FGetContentDownloadUrlRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (HttpMethod.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("HttpMethod")); writer->WriteValue(HttpMethod); } writer->WriteIdentifierPrefix(TEXT("Key")); writer->WriteValue(Key); if (ThruCDN.notNull()) { writer->WriteIdentifierPrefix(TEXT("ThruCDN")); writer->WriteValue(ThruCDN); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetContentDownloadUrlRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> HttpMethodValue = obj->TryGetField(TEXT("HttpMethod")); if (HttpMethodValue.IsValid() && !HttpMethodValue->IsNull()) { FString TmpValue; if (HttpMethodValue->TryGetString(TmpValue)) { HttpMethod = TmpValue; } } const TSharedPtr<FJsonValue> KeyValue = obj->TryGetField(TEXT("Key")); if (KeyValue.IsValid() && !KeyValue->IsNull()) { FString TmpValue; if (KeyValue->TryGetString(TmpValue)) { Key = TmpValue; } } const TSharedPtr<FJsonValue> ThruCDNValue = obj->TryGetField(TEXT("ThruCDN")); if (ThruCDNValue.IsValid() && !ThruCDNValue->IsNull()) { bool TmpValue; if (ThruCDNValue->TryGetBool(TmpValue)) { ThruCDN = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetContentDownloadUrlResult::~FGetContentDownloadUrlResult() { } void PlayFab::ServerModels::FGetContentDownloadUrlResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (URL.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("URL")); writer->WriteValue(URL); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetContentDownloadUrlResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> URLValue = obj->TryGetField(TEXT("URL")); if (URLValue.IsValid() && !URLValue->IsNull()) { FString TmpValue; if (URLValue->TryGetString(TmpValue)) { URL = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FPlayerProfileViewConstraints::~FPlayerProfileViewConstraints() { } void PlayFab::ServerModels::FPlayerProfileViewConstraints::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("ShowAvatarUrl")); writer->WriteValue(ShowAvatarUrl); writer->WriteIdentifierPrefix(TEXT("ShowBannedUntil")); writer->WriteValue(ShowBannedUntil); writer->WriteIdentifierPrefix(TEXT("ShowCampaignAttributions")); writer->WriteValue(ShowCampaignAttributions); writer->WriteIdentifierPrefix(TEXT("ShowContactEmailAddresses")); writer->WriteValue(ShowContactEmailAddresses); writer->WriteIdentifierPrefix(TEXT("ShowCreated")); writer->WriteValue(ShowCreated); writer->WriteIdentifierPrefix(TEXT("ShowDisplayName")); writer->WriteValue(ShowDisplayName); writer->WriteIdentifierPrefix(TEXT("ShowLastLogin")); writer->WriteValue(ShowLastLogin); writer->WriteIdentifierPrefix(TEXT("ShowLinkedAccounts")); writer->WriteValue(ShowLinkedAccounts); writer->WriteIdentifierPrefix(TEXT("ShowLocations")); writer->WriteValue(ShowLocations); writer->WriteIdentifierPrefix(TEXT("ShowMemberships")); writer->WriteValue(ShowMemberships); writer->WriteIdentifierPrefix(TEXT("ShowOrigination")); writer->WriteValue(ShowOrigination); writer->WriteIdentifierPrefix(TEXT("ShowPushNotificationRegistrations")); writer->WriteValue(ShowPushNotificationRegistrations); writer->WriteIdentifierPrefix(TEXT("ShowStatistics")); writer->WriteValue(ShowStatistics); writer->WriteIdentifierPrefix(TEXT("ShowTags")); writer->WriteValue(ShowTags); writer->WriteIdentifierPrefix(TEXT("ShowTotalValueToDateInUsd")); writer->WriteValue(ShowTotalValueToDateInUsd); writer->WriteIdentifierPrefix(TEXT("ShowValuesToDate")); writer->WriteValue(ShowValuesToDate); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FPlayerProfileViewConstraints::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ShowAvatarUrlValue = obj->TryGetField(TEXT("ShowAvatarUrl")); if (ShowAvatarUrlValue.IsValid() && !ShowAvatarUrlValue->IsNull()) { bool TmpValue; if (ShowAvatarUrlValue->TryGetBool(TmpValue)) { ShowAvatarUrl = TmpValue; } } const TSharedPtr<FJsonValue> ShowBannedUntilValue = obj->TryGetField(TEXT("ShowBannedUntil")); if (ShowBannedUntilValue.IsValid() && !ShowBannedUntilValue->IsNull()) { bool TmpValue; if (ShowBannedUntilValue->TryGetBool(TmpValue)) { ShowBannedUntil = TmpValue; } } const TSharedPtr<FJsonValue> ShowCampaignAttributionsValue = obj->TryGetField(TEXT("ShowCampaignAttributions")); if (ShowCampaignAttributionsValue.IsValid() && !ShowCampaignAttributionsValue->IsNull()) { bool TmpValue; if (ShowCampaignAttributionsValue->TryGetBool(TmpValue)) { ShowCampaignAttributions = TmpValue; } } const TSharedPtr<FJsonValue> ShowContactEmailAddressesValue = obj->TryGetField(TEXT("ShowContactEmailAddresses")); if (ShowContactEmailAddressesValue.IsValid() && !ShowContactEmailAddressesValue->IsNull()) { bool TmpValue; if (ShowContactEmailAddressesValue->TryGetBool(TmpValue)) { ShowContactEmailAddresses = TmpValue; } } const TSharedPtr<FJsonValue> ShowCreatedValue = obj->TryGetField(TEXT("ShowCreated")); if (ShowCreatedValue.IsValid() && !ShowCreatedValue->IsNull()) { bool TmpValue; if (ShowCreatedValue->TryGetBool(TmpValue)) { ShowCreated = TmpValue; } } const TSharedPtr<FJsonValue> ShowDisplayNameValue = obj->TryGetField(TEXT("ShowDisplayName")); if (ShowDisplayNameValue.IsValid() && !ShowDisplayNameValue->IsNull()) { bool TmpValue; if (ShowDisplayNameValue->TryGetBool(TmpValue)) { ShowDisplayName = TmpValue; } } const TSharedPtr<FJsonValue> ShowLastLoginValue = obj->TryGetField(TEXT("ShowLastLogin")); if (ShowLastLoginValue.IsValid() && !ShowLastLoginValue->IsNull()) { bool TmpValue; if (ShowLastLoginValue->TryGetBool(TmpValue)) { ShowLastLogin = TmpValue; } } const TSharedPtr<FJsonValue> ShowLinkedAccountsValue = obj->TryGetField(TEXT("ShowLinkedAccounts")); if (ShowLinkedAccountsValue.IsValid() && !ShowLinkedAccountsValue->IsNull()) { bool TmpValue; if (ShowLinkedAccountsValue->TryGetBool(TmpValue)) { ShowLinkedAccounts = TmpValue; } } const TSharedPtr<FJsonValue> ShowLocationsValue = obj->TryGetField(TEXT("ShowLocations")); if (ShowLocationsValue.IsValid() && !ShowLocationsValue->IsNull()) { bool TmpValue; if (ShowLocationsValue->TryGetBool(TmpValue)) { ShowLocations = TmpValue; } } const TSharedPtr<FJsonValue> ShowMembershipsValue = obj->TryGetField(TEXT("ShowMemberships")); if (ShowMembershipsValue.IsValid() && !ShowMembershipsValue->IsNull()) { bool TmpValue; if (ShowMembershipsValue->TryGetBool(TmpValue)) { ShowMemberships = TmpValue; } } const TSharedPtr<FJsonValue> ShowOriginationValue = obj->TryGetField(TEXT("ShowOrigination")); if (ShowOriginationValue.IsValid() && !ShowOriginationValue->IsNull()) { bool TmpValue; if (ShowOriginationValue->TryGetBool(TmpValue)) { ShowOrigination = TmpValue; } } const TSharedPtr<FJsonValue> ShowPushNotificationRegistrationsValue = obj->TryGetField(TEXT("ShowPushNotificationRegistrations")); if (ShowPushNotificationRegistrationsValue.IsValid() && !ShowPushNotificationRegistrationsValue->IsNull()) { bool TmpValue; if (ShowPushNotificationRegistrationsValue->TryGetBool(TmpValue)) { ShowPushNotificationRegistrations = TmpValue; } } const TSharedPtr<FJsonValue> ShowStatisticsValue = obj->TryGetField(TEXT("ShowStatistics")); if (ShowStatisticsValue.IsValid() && !ShowStatisticsValue->IsNull()) { bool TmpValue; if (ShowStatisticsValue->TryGetBool(TmpValue)) { ShowStatistics = TmpValue; } } const TSharedPtr<FJsonValue> ShowTagsValue = obj->TryGetField(TEXT("ShowTags")); if (ShowTagsValue.IsValid() && !ShowTagsValue->IsNull()) { bool TmpValue; if (ShowTagsValue->TryGetBool(TmpValue)) { ShowTags = TmpValue; } } const TSharedPtr<FJsonValue> ShowTotalValueToDateInUsdValue = obj->TryGetField(TEXT("ShowTotalValueToDateInUsd")); if (ShowTotalValueToDateInUsdValue.IsValid() && !ShowTotalValueToDateInUsdValue->IsNull()) { bool TmpValue; if (ShowTotalValueToDateInUsdValue->TryGetBool(TmpValue)) { ShowTotalValueToDateInUsd = TmpValue; } } const TSharedPtr<FJsonValue> ShowValuesToDateValue = obj->TryGetField(TEXT("ShowValuesToDate")); if (ShowValuesToDateValue.IsValid() && !ShowValuesToDateValue->IsNull()) { bool TmpValue; if (ShowValuesToDateValue->TryGetBool(TmpValue)) { ShowValuesToDate = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetFriendLeaderboardRequest::~FGetFriendLeaderboardRequest() { //if (ProfileConstraints != nullptr) delete ProfileConstraints; } void PlayFab::ServerModels::FGetFriendLeaderboardRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (IncludeFacebookFriends.notNull()) { writer->WriteIdentifierPrefix(TEXT("IncludeFacebookFriends")); writer->WriteValue(IncludeFacebookFriends); } if (IncludeSteamFriends.notNull()) { writer->WriteIdentifierPrefix(TEXT("IncludeSteamFriends")); writer->WriteValue(IncludeSteamFriends); } writer->WriteIdentifierPrefix(TEXT("MaxResultsCount")); writer->WriteValue(MaxResultsCount); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); if (ProfileConstraints.IsValid()) { writer->WriteIdentifierPrefix(TEXT("ProfileConstraints")); ProfileConstraints->writeJSON(writer); } writer->WriteIdentifierPrefix(TEXT("StartPosition")); writer->WriteValue(StartPosition); writer->WriteIdentifierPrefix(TEXT("StatisticName")); writer->WriteValue(StatisticName); if (UseSpecificVersion.notNull()) { writer->WriteIdentifierPrefix(TEXT("UseSpecificVersion")); writer->WriteValue(UseSpecificVersion); } if (Version.notNull()) { writer->WriteIdentifierPrefix(TEXT("Version")); writer->WriteValue(Version); } if (XboxToken.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("XboxToken")); writer->WriteValue(XboxToken); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetFriendLeaderboardRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> IncludeFacebookFriendsValue = obj->TryGetField(TEXT("IncludeFacebookFriends")); if (IncludeFacebookFriendsValue.IsValid() && !IncludeFacebookFriendsValue->IsNull()) { bool TmpValue; if (IncludeFacebookFriendsValue->TryGetBool(TmpValue)) { IncludeFacebookFriends = TmpValue; } } const TSharedPtr<FJsonValue> IncludeSteamFriendsValue = obj->TryGetField(TEXT("IncludeSteamFriends")); if (IncludeSteamFriendsValue.IsValid() && !IncludeSteamFriendsValue->IsNull()) { bool TmpValue; if (IncludeSteamFriendsValue->TryGetBool(TmpValue)) { IncludeSteamFriends = TmpValue; } } const TSharedPtr<FJsonValue> MaxResultsCountValue = obj->TryGetField(TEXT("MaxResultsCount")); if (MaxResultsCountValue.IsValid() && !MaxResultsCountValue->IsNull()) { int32 TmpValue; if (MaxResultsCountValue->TryGetNumber(TmpValue)) { MaxResultsCount = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> ProfileConstraintsValue = obj->TryGetField(TEXT("ProfileConstraints")); if (ProfileConstraintsValue.IsValid() && !ProfileConstraintsValue->IsNull()) { ProfileConstraints = MakeShareable(new FPlayerProfileViewConstraints(ProfileConstraintsValue->AsObject())); } const TSharedPtr<FJsonValue> StartPositionValue = obj->TryGetField(TEXT("StartPosition")); if (StartPositionValue.IsValid() && !StartPositionValue->IsNull()) { int32 TmpValue; if (StartPositionValue->TryGetNumber(TmpValue)) { StartPosition = TmpValue; } } const TSharedPtr<FJsonValue> StatisticNameValue = obj->TryGetField(TEXT("StatisticName")); if (StatisticNameValue.IsValid() && !StatisticNameValue->IsNull()) { FString TmpValue; if (StatisticNameValue->TryGetString(TmpValue)) { StatisticName = TmpValue; } } const TSharedPtr<FJsonValue> UseSpecificVersionValue = obj->TryGetField(TEXT("UseSpecificVersion")); if (UseSpecificVersionValue.IsValid() && !UseSpecificVersionValue->IsNull()) { bool TmpValue; if (UseSpecificVersionValue->TryGetBool(TmpValue)) { UseSpecificVersion = TmpValue; } } const TSharedPtr<FJsonValue> VersionValue = obj->TryGetField(TEXT("Version")); if (VersionValue.IsValid() && !VersionValue->IsNull()) { int32 TmpValue; if (VersionValue->TryGetNumber(TmpValue)) { Version = TmpValue; } } const TSharedPtr<FJsonValue> XboxTokenValue = obj->TryGetField(TEXT("XboxToken")); if (XboxTokenValue.IsValid() && !XboxTokenValue->IsNull()) { FString TmpValue; if (XboxTokenValue->TryGetString(TmpValue)) { XboxToken = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetFriendsListRequest::~FGetFriendsListRequest() { //if (ProfileConstraints != nullptr) delete ProfileConstraints; } void PlayFab::ServerModels::FGetFriendsListRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (IncludeFacebookFriends.notNull()) { writer->WriteIdentifierPrefix(TEXT("IncludeFacebookFriends")); writer->WriteValue(IncludeFacebookFriends); } if (IncludeSteamFriends.notNull()) { writer->WriteIdentifierPrefix(TEXT("IncludeSteamFriends")); writer->WriteValue(IncludeSteamFriends); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); if (ProfileConstraints.IsValid()) { writer->WriteIdentifierPrefix(TEXT("ProfileConstraints")); ProfileConstraints->writeJSON(writer); } if (XboxToken.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("XboxToken")); writer->WriteValue(XboxToken); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetFriendsListRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> IncludeFacebookFriendsValue = obj->TryGetField(TEXT("IncludeFacebookFriends")); if (IncludeFacebookFriendsValue.IsValid() && !IncludeFacebookFriendsValue->IsNull()) { bool TmpValue; if (IncludeFacebookFriendsValue->TryGetBool(TmpValue)) { IncludeFacebookFriends = TmpValue; } } const TSharedPtr<FJsonValue> IncludeSteamFriendsValue = obj->TryGetField(TEXT("IncludeSteamFriends")); if (IncludeSteamFriendsValue.IsValid() && !IncludeSteamFriendsValue->IsNull()) { bool TmpValue; if (IncludeSteamFriendsValue->TryGetBool(TmpValue)) { IncludeSteamFriends = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> ProfileConstraintsValue = obj->TryGetField(TEXT("ProfileConstraints")); if (ProfileConstraintsValue.IsValid() && !ProfileConstraintsValue->IsNull()) { ProfileConstraints = MakeShareable(new FPlayerProfileViewConstraints(ProfileConstraintsValue->AsObject())); } const TSharedPtr<FJsonValue> XboxTokenValue = obj->TryGetField(TEXT("XboxToken")); if (XboxTokenValue.IsValid() && !XboxTokenValue->IsNull()) { FString TmpValue; if (XboxTokenValue->TryGetString(TmpValue)) { XboxToken = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetFriendsListResult::~FGetFriendsListResult() { } void PlayFab::ServerModels::FGetFriendsListResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Friends.Num() != 0) { writer->WriteArrayStart(TEXT("Friends")); for (const FFriendInfo& item : Friends) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetFriendsListResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&FriendsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Friends")); for (int32 Idx = 0; Idx < FriendsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = FriendsArray[Idx]; Friends.Add(FFriendInfo(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetLeaderboardAroundCharacterRequest::~FGetLeaderboardAroundCharacterRequest() { } void PlayFab::ServerModels::FGetLeaderboardAroundCharacterRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); if (CharacterType.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterType")); writer->WriteValue(CharacterType); } writer->WriteIdentifierPrefix(TEXT("MaxResultsCount")); writer->WriteValue(MaxResultsCount); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("StatisticName")); writer->WriteValue(StatisticName); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetLeaderboardAroundCharacterRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> CharacterTypeValue = obj->TryGetField(TEXT("CharacterType")); if (CharacterTypeValue.IsValid() && !CharacterTypeValue->IsNull()) { FString TmpValue; if (CharacterTypeValue->TryGetString(TmpValue)) { CharacterType = TmpValue; } } const TSharedPtr<FJsonValue> MaxResultsCountValue = obj->TryGetField(TEXT("MaxResultsCount")); if (MaxResultsCountValue.IsValid() && !MaxResultsCountValue->IsNull()) { int32 TmpValue; if (MaxResultsCountValue->TryGetNumber(TmpValue)) { MaxResultsCount = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> StatisticNameValue = obj->TryGetField(TEXT("StatisticName")); if (StatisticNameValue.IsValid() && !StatisticNameValue->IsNull()) { FString TmpValue; if (StatisticNameValue->TryGetString(TmpValue)) { StatisticName = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetLeaderboardAroundCharacterResult::~FGetLeaderboardAroundCharacterResult() { } void PlayFab::ServerModels::FGetLeaderboardAroundCharacterResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Leaderboard.Num() != 0) { writer->WriteArrayStart(TEXT("Leaderboard")); for (const FCharacterLeaderboardEntry& item : Leaderboard) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetLeaderboardAroundCharacterResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&LeaderboardArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Leaderboard")); for (int32 Idx = 0; Idx < LeaderboardArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = LeaderboardArray[Idx]; Leaderboard.Add(FCharacterLeaderboardEntry(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetLeaderboardAroundUserRequest::~FGetLeaderboardAroundUserRequest() { //if (ProfileConstraints != nullptr) delete ProfileConstraints; } void PlayFab::ServerModels::FGetLeaderboardAroundUserRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("MaxResultsCount")); writer->WriteValue(MaxResultsCount); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); if (ProfileConstraints.IsValid()) { writer->WriteIdentifierPrefix(TEXT("ProfileConstraints")); ProfileConstraints->writeJSON(writer); } writer->WriteIdentifierPrefix(TEXT("StatisticName")); writer->WriteValue(StatisticName); if (UseSpecificVersion.notNull()) { writer->WriteIdentifierPrefix(TEXT("UseSpecificVersion")); writer->WriteValue(UseSpecificVersion); } if (Version.notNull()) { writer->WriteIdentifierPrefix(TEXT("Version")); writer->WriteValue(Version); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetLeaderboardAroundUserRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> MaxResultsCountValue = obj->TryGetField(TEXT("MaxResultsCount")); if (MaxResultsCountValue.IsValid() && !MaxResultsCountValue->IsNull()) { int32 TmpValue; if (MaxResultsCountValue->TryGetNumber(TmpValue)) { MaxResultsCount = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> ProfileConstraintsValue = obj->TryGetField(TEXT("ProfileConstraints")); if (ProfileConstraintsValue.IsValid() && !ProfileConstraintsValue->IsNull()) { ProfileConstraints = MakeShareable(new FPlayerProfileViewConstraints(ProfileConstraintsValue->AsObject())); } const TSharedPtr<FJsonValue> StatisticNameValue = obj->TryGetField(TEXT("StatisticName")); if (StatisticNameValue.IsValid() && !StatisticNameValue->IsNull()) { FString TmpValue; if (StatisticNameValue->TryGetString(TmpValue)) { StatisticName = TmpValue; } } const TSharedPtr<FJsonValue> UseSpecificVersionValue = obj->TryGetField(TEXT("UseSpecificVersion")); if (UseSpecificVersionValue.IsValid() && !UseSpecificVersionValue->IsNull()) { bool TmpValue; if (UseSpecificVersionValue->TryGetBool(TmpValue)) { UseSpecificVersion = TmpValue; } } const TSharedPtr<FJsonValue> VersionValue = obj->TryGetField(TEXT("Version")); if (VersionValue.IsValid() && !VersionValue->IsNull()) { int32 TmpValue; if (VersionValue->TryGetNumber(TmpValue)) { Version = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FPlayerLeaderboardEntry::~FPlayerLeaderboardEntry() { //if (Profile != nullptr) delete Profile; } void PlayFab::ServerModels::FPlayerLeaderboardEntry::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (DisplayName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("DisplayName")); writer->WriteValue(DisplayName); } if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } writer->WriteIdentifierPrefix(TEXT("Position")); writer->WriteValue(Position); if (Profile.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Profile")); Profile->writeJSON(writer); } writer->WriteIdentifierPrefix(TEXT("StatValue")); writer->WriteValue(StatValue); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FPlayerLeaderboardEntry::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> DisplayNameValue = obj->TryGetField(TEXT("DisplayName")); if (DisplayNameValue.IsValid() && !DisplayNameValue->IsNull()) { FString TmpValue; if (DisplayNameValue->TryGetString(TmpValue)) { DisplayName = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> PositionValue = obj->TryGetField(TEXT("Position")); if (PositionValue.IsValid() && !PositionValue->IsNull()) { int32 TmpValue; if (PositionValue->TryGetNumber(TmpValue)) { Position = TmpValue; } } const TSharedPtr<FJsonValue> ProfileValue = obj->TryGetField(TEXT("Profile")); if (ProfileValue.IsValid() && !ProfileValue->IsNull()) { Profile = MakeShareable(new FPlayerProfileModel(ProfileValue->AsObject())); } const TSharedPtr<FJsonValue> StatValueValue = obj->TryGetField(TEXT("StatValue")); if (StatValueValue.IsValid() && !StatValueValue->IsNull()) { int32 TmpValue; if (StatValueValue->TryGetNumber(TmpValue)) { StatValue = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetLeaderboardAroundUserResult::~FGetLeaderboardAroundUserResult() { } void PlayFab::ServerModels::FGetLeaderboardAroundUserResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Leaderboard.Num() != 0) { writer->WriteArrayStart(TEXT("Leaderboard")); for (const FPlayerLeaderboardEntry& item : Leaderboard) item.writeJSON(writer); writer->WriteArrayEnd(); } if (NextReset.notNull()) { writer->WriteIdentifierPrefix(TEXT("NextReset")); writeDatetime(NextReset, writer); } writer->WriteIdentifierPrefix(TEXT("Version")); writer->WriteValue(Version); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetLeaderboardAroundUserResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&LeaderboardArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Leaderboard")); for (int32 Idx = 0; Idx < LeaderboardArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = LeaderboardArray[Idx]; Leaderboard.Add(FPlayerLeaderboardEntry(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> NextResetValue = obj->TryGetField(TEXT("NextReset")); if (NextResetValue.IsValid()) NextReset = readDatetime(NextResetValue); const TSharedPtr<FJsonValue> VersionValue = obj->TryGetField(TEXT("Version")); if (VersionValue.IsValid() && !VersionValue->IsNull()) { int32 TmpValue; if (VersionValue->TryGetNumber(TmpValue)) { Version = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetLeaderboardForUsersCharactersRequest::~FGetLeaderboardForUsersCharactersRequest() { } void PlayFab::ServerModels::FGetLeaderboardForUsersCharactersRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("MaxResultsCount")); writer->WriteValue(MaxResultsCount); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("StatisticName")); writer->WriteValue(StatisticName); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetLeaderboardForUsersCharactersRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> MaxResultsCountValue = obj->TryGetField(TEXT("MaxResultsCount")); if (MaxResultsCountValue.IsValid() && !MaxResultsCountValue->IsNull()) { int32 TmpValue; if (MaxResultsCountValue->TryGetNumber(TmpValue)) { MaxResultsCount = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> StatisticNameValue = obj->TryGetField(TEXT("StatisticName")); if (StatisticNameValue.IsValid() && !StatisticNameValue->IsNull()) { FString TmpValue; if (StatisticNameValue->TryGetString(TmpValue)) { StatisticName = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetLeaderboardForUsersCharactersResult::~FGetLeaderboardForUsersCharactersResult() { } void PlayFab::ServerModels::FGetLeaderboardForUsersCharactersResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Leaderboard.Num() != 0) { writer->WriteArrayStart(TEXT("Leaderboard")); for (const FCharacterLeaderboardEntry& item : Leaderboard) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetLeaderboardForUsersCharactersResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&LeaderboardArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Leaderboard")); for (int32 Idx = 0; Idx < LeaderboardArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = LeaderboardArray[Idx]; Leaderboard.Add(FCharacterLeaderboardEntry(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetLeaderboardRequest::~FGetLeaderboardRequest() { //if (ProfileConstraints != nullptr) delete ProfileConstraints; } void PlayFab::ServerModels::FGetLeaderboardRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("MaxResultsCount")); writer->WriteValue(MaxResultsCount); if (ProfileConstraints.IsValid()) { writer->WriteIdentifierPrefix(TEXT("ProfileConstraints")); ProfileConstraints->writeJSON(writer); } writer->WriteIdentifierPrefix(TEXT("StartPosition")); writer->WriteValue(StartPosition); writer->WriteIdentifierPrefix(TEXT("StatisticName")); writer->WriteValue(StatisticName); if (UseSpecificVersion.notNull()) { writer->WriteIdentifierPrefix(TEXT("UseSpecificVersion")); writer->WriteValue(UseSpecificVersion); } if (Version.notNull()) { writer->WriteIdentifierPrefix(TEXT("Version")); writer->WriteValue(Version); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetLeaderboardRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> MaxResultsCountValue = obj->TryGetField(TEXT("MaxResultsCount")); if (MaxResultsCountValue.IsValid() && !MaxResultsCountValue->IsNull()) { int32 TmpValue; if (MaxResultsCountValue->TryGetNumber(TmpValue)) { MaxResultsCount = TmpValue; } } const TSharedPtr<FJsonValue> ProfileConstraintsValue = obj->TryGetField(TEXT("ProfileConstraints")); if (ProfileConstraintsValue.IsValid() && !ProfileConstraintsValue->IsNull()) { ProfileConstraints = MakeShareable(new FPlayerProfileViewConstraints(ProfileConstraintsValue->AsObject())); } const TSharedPtr<FJsonValue> StartPositionValue = obj->TryGetField(TEXT("StartPosition")); if (StartPositionValue.IsValid() && !StartPositionValue->IsNull()) { int32 TmpValue; if (StartPositionValue->TryGetNumber(TmpValue)) { StartPosition = TmpValue; } } const TSharedPtr<FJsonValue> StatisticNameValue = obj->TryGetField(TEXT("StatisticName")); if (StatisticNameValue.IsValid() && !StatisticNameValue->IsNull()) { FString TmpValue; if (StatisticNameValue->TryGetString(TmpValue)) { StatisticName = TmpValue; } } const TSharedPtr<FJsonValue> UseSpecificVersionValue = obj->TryGetField(TEXT("UseSpecificVersion")); if (UseSpecificVersionValue.IsValid() && !UseSpecificVersionValue->IsNull()) { bool TmpValue; if (UseSpecificVersionValue->TryGetBool(TmpValue)) { UseSpecificVersion = TmpValue; } } const TSharedPtr<FJsonValue> VersionValue = obj->TryGetField(TEXT("Version")); if (VersionValue.IsValid() && !VersionValue->IsNull()) { int32 TmpValue; if (VersionValue->TryGetNumber(TmpValue)) { Version = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetLeaderboardResult::~FGetLeaderboardResult() { } void PlayFab::ServerModels::FGetLeaderboardResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Leaderboard.Num() != 0) { writer->WriteArrayStart(TEXT("Leaderboard")); for (const FPlayerLeaderboardEntry& item : Leaderboard) item.writeJSON(writer); writer->WriteArrayEnd(); } if (NextReset.notNull()) { writer->WriteIdentifierPrefix(TEXT("NextReset")); writeDatetime(NextReset, writer); } writer->WriteIdentifierPrefix(TEXT("Version")); writer->WriteValue(Version); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetLeaderboardResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&LeaderboardArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Leaderboard")); for (int32 Idx = 0; Idx < LeaderboardArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = LeaderboardArray[Idx]; Leaderboard.Add(FPlayerLeaderboardEntry(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> NextResetValue = obj->TryGetField(TEXT("NextReset")); if (NextResetValue.IsValid()) NextReset = readDatetime(NextResetValue); const TSharedPtr<FJsonValue> VersionValue = obj->TryGetField(TEXT("Version")); if (VersionValue.IsValid() && !VersionValue->IsNull()) { int32 TmpValue; if (VersionValue->TryGetNumber(TmpValue)) { Version = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetPlayerCombinedInfoRequestParams::~FGetPlayerCombinedInfoRequestParams() { //if (ProfileConstraints != nullptr) delete ProfileConstraints; } void PlayFab::ServerModels::FGetPlayerCombinedInfoRequestParams::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("GetCharacterInventories")); writer->WriteValue(GetCharacterInventories); writer->WriteIdentifierPrefix(TEXT("GetCharacterList")); writer->WriteValue(GetCharacterList); writer->WriteIdentifierPrefix(TEXT("GetPlayerProfile")); writer->WriteValue(GetPlayerProfile); writer->WriteIdentifierPrefix(TEXT("GetPlayerStatistics")); writer->WriteValue(GetPlayerStatistics); writer->WriteIdentifierPrefix(TEXT("GetTitleData")); writer->WriteValue(GetTitleData); writer->WriteIdentifierPrefix(TEXT("GetUserAccountInfo")); writer->WriteValue(GetUserAccountInfo); writer->WriteIdentifierPrefix(TEXT("GetUserData")); writer->WriteValue(GetUserData); writer->WriteIdentifierPrefix(TEXT("GetUserInventory")); writer->WriteValue(GetUserInventory); writer->WriteIdentifierPrefix(TEXT("GetUserReadOnlyData")); writer->WriteValue(GetUserReadOnlyData); writer->WriteIdentifierPrefix(TEXT("GetUserVirtualCurrency")); writer->WriteValue(GetUserVirtualCurrency); if (PlayerStatisticNames.Num() != 0) { writer->WriteArrayStart(TEXT("PlayerStatisticNames")); for (const FString& item : PlayerStatisticNames) writer->WriteValue(item); writer->WriteArrayEnd(); } if (ProfileConstraints.IsValid()) { writer->WriteIdentifierPrefix(TEXT("ProfileConstraints")); ProfileConstraints->writeJSON(writer); } if (TitleDataKeys.Num() != 0) { writer->WriteArrayStart(TEXT("TitleDataKeys")); for (const FString& item : TitleDataKeys) writer->WriteValue(item); writer->WriteArrayEnd(); } if (UserDataKeys.Num() != 0) { writer->WriteArrayStart(TEXT("UserDataKeys")); for (const FString& item : UserDataKeys) writer->WriteValue(item); writer->WriteArrayEnd(); } if (UserReadOnlyDataKeys.Num() != 0) { writer->WriteArrayStart(TEXT("UserReadOnlyDataKeys")); for (const FString& item : UserReadOnlyDataKeys) writer->WriteValue(item); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayerCombinedInfoRequestParams::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> GetCharacterInventoriesValue = obj->TryGetField(TEXT("GetCharacterInventories")); if (GetCharacterInventoriesValue.IsValid() && !GetCharacterInventoriesValue->IsNull()) { bool TmpValue; if (GetCharacterInventoriesValue->TryGetBool(TmpValue)) { GetCharacterInventories = TmpValue; } } const TSharedPtr<FJsonValue> GetCharacterListValue = obj->TryGetField(TEXT("GetCharacterList")); if (GetCharacterListValue.IsValid() && !GetCharacterListValue->IsNull()) { bool TmpValue; if (GetCharacterListValue->TryGetBool(TmpValue)) { GetCharacterList = TmpValue; } } const TSharedPtr<FJsonValue> GetPlayerProfileValue = obj->TryGetField(TEXT("GetPlayerProfile")); if (GetPlayerProfileValue.IsValid() && !GetPlayerProfileValue->IsNull()) { bool TmpValue; if (GetPlayerProfileValue->TryGetBool(TmpValue)) { GetPlayerProfile = TmpValue; } } const TSharedPtr<FJsonValue> GetPlayerStatisticsValue = obj->TryGetField(TEXT("GetPlayerStatistics")); if (GetPlayerStatisticsValue.IsValid() && !GetPlayerStatisticsValue->IsNull()) { bool TmpValue; if (GetPlayerStatisticsValue->TryGetBool(TmpValue)) { GetPlayerStatistics = TmpValue; } } const TSharedPtr<FJsonValue> GetTitleDataValue = obj->TryGetField(TEXT("GetTitleData")); if (GetTitleDataValue.IsValid() && !GetTitleDataValue->IsNull()) { bool TmpValue; if (GetTitleDataValue->TryGetBool(TmpValue)) { GetTitleData = TmpValue; } } const TSharedPtr<FJsonValue> GetUserAccountInfoValue = obj->TryGetField(TEXT("GetUserAccountInfo")); if (GetUserAccountInfoValue.IsValid() && !GetUserAccountInfoValue->IsNull()) { bool TmpValue; if (GetUserAccountInfoValue->TryGetBool(TmpValue)) { GetUserAccountInfo = TmpValue; } } const TSharedPtr<FJsonValue> GetUserDataValue = obj->TryGetField(TEXT("GetUserData")); if (GetUserDataValue.IsValid() && !GetUserDataValue->IsNull()) { bool TmpValue; if (GetUserDataValue->TryGetBool(TmpValue)) { GetUserData = TmpValue; } } const TSharedPtr<FJsonValue> GetUserInventoryValue = obj->TryGetField(TEXT("GetUserInventory")); if (GetUserInventoryValue.IsValid() && !GetUserInventoryValue->IsNull()) { bool TmpValue; if (GetUserInventoryValue->TryGetBool(TmpValue)) { GetUserInventory = TmpValue; } } const TSharedPtr<FJsonValue> GetUserReadOnlyDataValue = obj->TryGetField(TEXT("GetUserReadOnlyData")); if (GetUserReadOnlyDataValue.IsValid() && !GetUserReadOnlyDataValue->IsNull()) { bool TmpValue; if (GetUserReadOnlyDataValue->TryGetBool(TmpValue)) { GetUserReadOnlyData = TmpValue; } } const TSharedPtr<FJsonValue> GetUserVirtualCurrencyValue = obj->TryGetField(TEXT("GetUserVirtualCurrency")); if (GetUserVirtualCurrencyValue.IsValid() && !GetUserVirtualCurrencyValue->IsNull()) { bool TmpValue; if (GetUserVirtualCurrencyValue->TryGetBool(TmpValue)) { GetUserVirtualCurrency = TmpValue; } } obj->TryGetStringArrayField(TEXT("PlayerStatisticNames"), PlayerStatisticNames); const TSharedPtr<FJsonValue> ProfileConstraintsValue = obj->TryGetField(TEXT("ProfileConstraints")); if (ProfileConstraintsValue.IsValid() && !ProfileConstraintsValue->IsNull()) { ProfileConstraints = MakeShareable(new FPlayerProfileViewConstraints(ProfileConstraintsValue->AsObject())); } obj->TryGetStringArrayField(TEXT("TitleDataKeys"), TitleDataKeys); obj->TryGetStringArrayField(TEXT("UserDataKeys"), UserDataKeys); obj->TryGetStringArrayField(TEXT("UserReadOnlyDataKeys"), UserReadOnlyDataKeys); return HasSucceeded; } PlayFab::ServerModels::FGetPlayerCombinedInfoRequest::~FGetPlayerCombinedInfoRequest() { } void PlayFab::ServerModels::FGetPlayerCombinedInfoRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("InfoRequestParameters")); InfoRequestParameters.writeJSON(writer); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayerCombinedInfoRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> InfoRequestParametersValue = obj->TryGetField(TEXT("InfoRequestParameters")); if (InfoRequestParametersValue.IsValid() && !InfoRequestParametersValue->IsNull()) { InfoRequestParameters = FGetPlayerCombinedInfoRequestParams(InfoRequestParametersValue->AsObject()); } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FStatisticValue::~FStatisticValue() { } void PlayFab::ServerModels::FStatisticValue::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (StatisticName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("StatisticName")); writer->WriteValue(StatisticName); } writer->WriteIdentifierPrefix(TEXT("Value")); writer->WriteValue(Value); writer->WriteIdentifierPrefix(TEXT("Version")); writer->WriteValue(static_cast<int64>(Version)); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FStatisticValue::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> StatisticNameValue = obj->TryGetField(TEXT("StatisticName")); if (StatisticNameValue.IsValid() && !StatisticNameValue->IsNull()) { FString TmpValue; if (StatisticNameValue->TryGetString(TmpValue)) { StatisticName = TmpValue; } } const TSharedPtr<FJsonValue> ValueValue = obj->TryGetField(TEXT("Value")); if (ValueValue.IsValid() && !ValueValue->IsNull()) { int32 TmpValue; if (ValueValue->TryGetNumber(TmpValue)) { Value = TmpValue; } } const TSharedPtr<FJsonValue> VersionValue = obj->TryGetField(TEXT("Version")); if (VersionValue.IsValid() && !VersionValue->IsNull()) { uint32 TmpValue; if (VersionValue->TryGetNumber(TmpValue)) { Version = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetPlayerCombinedInfoResultPayload::~FGetPlayerCombinedInfoResultPayload() { //if (AccountInfo != nullptr) delete AccountInfo; //if (PlayerProfile != nullptr) delete PlayerProfile; } void PlayFab::ServerModels::FGetPlayerCombinedInfoResultPayload::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (AccountInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("AccountInfo")); AccountInfo->writeJSON(writer); } if (CharacterInventories.Num() != 0) { writer->WriteArrayStart(TEXT("CharacterInventories")); for (const FCharacterInventory& item : CharacterInventories) item.writeJSON(writer); writer->WriteArrayEnd(); } if (CharacterList.Num() != 0) { writer->WriteArrayStart(TEXT("CharacterList")); for (const FCharacterResult& item : CharacterList) item.writeJSON(writer); writer->WriteArrayEnd(); } if (PlayerProfile.IsValid()) { writer->WriteIdentifierPrefix(TEXT("PlayerProfile")); PlayerProfile->writeJSON(writer); } if (PlayerStatistics.Num() != 0) { writer->WriteArrayStart(TEXT("PlayerStatistics")); for (const FStatisticValue& item : PlayerStatistics) item.writeJSON(writer); writer->WriteArrayEnd(); } if (TitleData.Num() != 0) { writer->WriteObjectStart(TEXT("TitleData")); for (TMap<FString, FString>::TConstIterator It(TitleData); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (UserData.Num() != 0) { writer->WriteObjectStart(TEXT("UserData")); for (TMap<FString, FUserDataRecord>::TConstIterator It(UserData); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteIdentifierPrefix(TEXT("UserDataVersion")); writer->WriteValue(static_cast<int64>(UserDataVersion)); if (UserInventory.Num() != 0) { writer->WriteArrayStart(TEXT("UserInventory")); for (const FItemInstance& item : UserInventory) item.writeJSON(writer); writer->WriteArrayEnd(); } if (UserReadOnlyData.Num() != 0) { writer->WriteObjectStart(TEXT("UserReadOnlyData")); for (TMap<FString, FUserDataRecord>::TConstIterator It(UserReadOnlyData); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteIdentifierPrefix(TEXT("UserReadOnlyDataVersion")); writer->WriteValue(static_cast<int64>(UserReadOnlyDataVersion)); if (UserVirtualCurrency.Num() != 0) { writer->WriteObjectStart(TEXT("UserVirtualCurrency")); for (TMap<FString, int32>::TConstIterator It(UserVirtualCurrency); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (UserVirtualCurrencyRechargeTimes.Num() != 0) { writer->WriteObjectStart(TEXT("UserVirtualCurrencyRechargeTimes")); for (TMap<FString, FVirtualCurrencyRechargeTime>::TConstIterator It(UserVirtualCurrencyRechargeTimes); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayerCombinedInfoResultPayload::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AccountInfoValue = obj->TryGetField(TEXT("AccountInfo")); if (AccountInfoValue.IsValid() && !AccountInfoValue->IsNull()) { AccountInfo = MakeShareable(new FUserAccountInfo(AccountInfoValue->AsObject())); } const TArray<TSharedPtr<FJsonValue>>&CharacterInventoriesArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("CharacterInventories")); for (int32 Idx = 0; Idx < CharacterInventoriesArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = CharacterInventoriesArray[Idx]; CharacterInventories.Add(FCharacterInventory(CurrentItem->AsObject())); } const TArray<TSharedPtr<FJsonValue>>&CharacterListArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("CharacterList")); for (int32 Idx = 0; Idx < CharacterListArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = CharacterListArray[Idx]; CharacterList.Add(FCharacterResult(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> PlayerProfileValue = obj->TryGetField(TEXT("PlayerProfile")); if (PlayerProfileValue.IsValid() && !PlayerProfileValue->IsNull()) { PlayerProfile = MakeShareable(new FPlayerProfileModel(PlayerProfileValue->AsObject())); } const TArray<TSharedPtr<FJsonValue>>&PlayerStatisticsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("PlayerStatistics")); for (int32 Idx = 0; Idx < PlayerStatisticsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = PlayerStatisticsArray[Idx]; PlayerStatistics.Add(FStatisticValue(CurrentItem->AsObject())); } const TSharedPtr<FJsonObject>* TitleDataObject; if (obj->TryGetObjectField(TEXT("TitleData"), TitleDataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*TitleDataObject)->Values); It; ++It) { TitleData.Add(It.Key(), It.Value()->AsString()); } } const TSharedPtr<FJsonObject>* UserDataObject; if (obj->TryGetObjectField(TEXT("UserData"), UserDataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*UserDataObject)->Values); It; ++It) { UserData.Add(It.Key(), FUserDataRecord(It.Value()->AsObject())); } } const TSharedPtr<FJsonValue> UserDataVersionValue = obj->TryGetField(TEXT("UserDataVersion")); if (UserDataVersionValue.IsValid() && !UserDataVersionValue->IsNull()) { uint32 TmpValue; if (UserDataVersionValue->TryGetNumber(TmpValue)) { UserDataVersion = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&UserInventoryArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("UserInventory")); for (int32 Idx = 0; Idx < UserInventoryArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = UserInventoryArray[Idx]; UserInventory.Add(FItemInstance(CurrentItem->AsObject())); } const TSharedPtr<FJsonObject>* UserReadOnlyDataObject; if (obj->TryGetObjectField(TEXT("UserReadOnlyData"), UserReadOnlyDataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*UserReadOnlyDataObject)->Values); It; ++It) { UserReadOnlyData.Add(It.Key(), FUserDataRecord(It.Value()->AsObject())); } } const TSharedPtr<FJsonValue> UserReadOnlyDataVersionValue = obj->TryGetField(TEXT("UserReadOnlyDataVersion")); if (UserReadOnlyDataVersionValue.IsValid() && !UserReadOnlyDataVersionValue->IsNull()) { uint32 TmpValue; if (UserReadOnlyDataVersionValue->TryGetNumber(TmpValue)) { UserReadOnlyDataVersion = TmpValue; } } const TSharedPtr<FJsonObject>* UserVirtualCurrencyObject; if (obj->TryGetObjectField(TEXT("UserVirtualCurrency"), UserVirtualCurrencyObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*UserVirtualCurrencyObject)->Values); It; ++It) { int32 TmpValue; It.Value()->TryGetNumber(TmpValue); UserVirtualCurrency.Add(It.Key(), TmpValue); } } const TSharedPtr<FJsonObject>* UserVirtualCurrencyRechargeTimesObject; if (obj->TryGetObjectField(TEXT("UserVirtualCurrencyRechargeTimes"), UserVirtualCurrencyRechargeTimesObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*UserVirtualCurrencyRechargeTimesObject)->Values); It; ++It) { UserVirtualCurrencyRechargeTimes.Add(It.Key(), FVirtualCurrencyRechargeTime(It.Value()->AsObject())); } } return HasSucceeded; } PlayFab::ServerModels::FGetPlayerCombinedInfoResult::~FGetPlayerCombinedInfoResult() { //if (InfoResultPayload != nullptr) delete InfoResultPayload; } void PlayFab::ServerModels::FGetPlayerCombinedInfoResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (InfoResultPayload.IsValid()) { writer->WriteIdentifierPrefix(TEXT("InfoResultPayload")); InfoResultPayload->writeJSON(writer); } if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayerCombinedInfoResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> InfoResultPayloadValue = obj->TryGetField(TEXT("InfoResultPayload")); if (InfoResultPayloadValue.IsValid() && !InfoResultPayloadValue->IsNull()) { InfoResultPayload = MakeShareable(new FGetPlayerCombinedInfoResultPayload(InfoResultPayloadValue->AsObject())); } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetPlayerProfileRequest::~FGetPlayerProfileRequest() { //if (ProfileConstraints != nullptr) delete ProfileConstraints; } void PlayFab::ServerModels::FGetPlayerProfileRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); if (ProfileConstraints.IsValid()) { writer->WriteIdentifierPrefix(TEXT("ProfileConstraints")); ProfileConstraints->writeJSON(writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayerProfileRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> ProfileConstraintsValue = obj->TryGetField(TEXT("ProfileConstraints")); if (ProfileConstraintsValue.IsValid() && !ProfileConstraintsValue->IsNull()) { ProfileConstraints = MakeShareable(new FPlayerProfileViewConstraints(ProfileConstraintsValue->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetPlayerProfileResult::~FGetPlayerProfileResult() { //if (PlayerProfile != nullptr) delete PlayerProfile; } void PlayFab::ServerModels::FGetPlayerProfileResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (PlayerProfile.IsValid()) { writer->WriteIdentifierPrefix(TEXT("PlayerProfile")); PlayerProfile->writeJSON(writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayerProfileResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayerProfileValue = obj->TryGetField(TEXT("PlayerProfile")); if (PlayerProfileValue.IsValid() && !PlayerProfileValue->IsNull()) { PlayerProfile = MakeShareable(new FPlayerProfileModel(PlayerProfileValue->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetPlayerSegmentsResult::~FGetPlayerSegmentsResult() { } void PlayFab::ServerModels::FGetPlayerSegmentsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Segments.Num() != 0) { writer->WriteArrayStart(TEXT("Segments")); for (const FGetSegmentResult& item : Segments) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayerSegmentsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&SegmentsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Segments")); for (int32 Idx = 0; Idx < SegmentsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = SegmentsArray[Idx]; Segments.Add(FGetSegmentResult(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetPlayersInSegmentRequest::~FGetPlayersInSegmentRequest() { } void PlayFab::ServerModels::FGetPlayersInSegmentRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (ContinuationToken.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ContinuationToken")); writer->WriteValue(ContinuationToken); } if (MaxBatchSize.notNull()) { writer->WriteIdentifierPrefix(TEXT("MaxBatchSize")); writer->WriteValue(static_cast<int64>(MaxBatchSize)); } if (SecondsToLive.notNull()) { writer->WriteIdentifierPrefix(TEXT("SecondsToLive")); writer->WriteValue(static_cast<int64>(SecondsToLive)); } writer->WriteIdentifierPrefix(TEXT("SegmentId")); writer->WriteValue(SegmentId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayersInSegmentRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ContinuationTokenValue = obj->TryGetField(TEXT("ContinuationToken")); if (ContinuationTokenValue.IsValid() && !ContinuationTokenValue->IsNull()) { FString TmpValue; if (ContinuationTokenValue->TryGetString(TmpValue)) { ContinuationToken = TmpValue; } } const TSharedPtr<FJsonValue> MaxBatchSizeValue = obj->TryGetField(TEXT("MaxBatchSize")); if (MaxBatchSizeValue.IsValid() && !MaxBatchSizeValue->IsNull()) { uint32 TmpValue; if (MaxBatchSizeValue->TryGetNumber(TmpValue)) { MaxBatchSize = TmpValue; } } const TSharedPtr<FJsonValue> SecondsToLiveValue = obj->TryGetField(TEXT("SecondsToLive")); if (SecondsToLiveValue.IsValid() && !SecondsToLiveValue->IsNull()) { uint32 TmpValue; if (SecondsToLiveValue->TryGetNumber(TmpValue)) { SecondsToLive = TmpValue; } } const TSharedPtr<FJsonValue> SegmentIdValue = obj->TryGetField(TEXT("SegmentId")); if (SegmentIdValue.IsValid() && !SegmentIdValue->IsNull()) { FString TmpValue; if (SegmentIdValue->TryGetString(TmpValue)) { SegmentId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FPlayerLinkedAccount::~FPlayerLinkedAccount() { } void PlayFab::ServerModels::FPlayerLinkedAccount::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Email.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Email")); writer->WriteValue(Email); } if (Platform.notNull()) { writer->WriteIdentifierPrefix(TEXT("Platform")); writeLoginIdentityProviderEnumJSON(Platform, writer); } if (PlatformUserId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlatformUserId")); writer->WriteValue(PlatformUserId); } if (Username.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Username")); writer->WriteValue(Username); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FPlayerLinkedAccount::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> EmailValue = obj->TryGetField(TEXT("Email")); if (EmailValue.IsValid() && !EmailValue->IsNull()) { FString TmpValue; if (EmailValue->TryGetString(TmpValue)) { Email = TmpValue; } } Platform = readLoginIdentityProviderFromValue(obj->TryGetField(TEXT("Platform"))); const TSharedPtr<FJsonValue> PlatformUserIdValue = obj->TryGetField(TEXT("PlatformUserId")); if (PlatformUserIdValue.IsValid() && !PlatformUserIdValue->IsNull()) { FString TmpValue; if (PlatformUserIdValue->TryGetString(TmpValue)) { PlatformUserId = TmpValue; } } const TSharedPtr<FJsonValue> UsernameValue = obj->TryGetField(TEXT("Username")); if (UsernameValue.IsValid() && !UsernameValue->IsNull()) { FString TmpValue; if (UsernameValue->TryGetString(TmpValue)) { Username = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FPlayerLocation::~FPlayerLocation() { } void PlayFab::ServerModels::FPlayerLocation::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (City.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("City")); writer->WriteValue(City); } writer->WriteIdentifierPrefix(TEXT("ContinentCode")); writeContinentCodeEnumJSON(pfContinentCode, writer); writer->WriteIdentifierPrefix(TEXT("CountryCode")); writeCountryCodeEnumJSON(pfCountryCode, writer); if (Latitude.notNull()) { writer->WriteIdentifierPrefix(TEXT("Latitude")); writer->WriteValue(Latitude); } if (Longitude.notNull()) { writer->WriteIdentifierPrefix(TEXT("Longitude")); writer->WriteValue(Longitude); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FPlayerLocation::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CityValue = obj->TryGetField(TEXT("City")); if (CityValue.IsValid() && !CityValue->IsNull()) { FString TmpValue; if (CityValue->TryGetString(TmpValue)) { City = TmpValue; } } pfContinentCode = readContinentCodeFromValue(obj->TryGetField(TEXT("ContinentCode"))); pfCountryCode = readCountryCodeFromValue(obj->TryGetField(TEXT("CountryCode"))); const TSharedPtr<FJsonValue> LatitudeValue = obj->TryGetField(TEXT("Latitude")); if (LatitudeValue.IsValid() && !LatitudeValue->IsNull()) { double TmpValue; if (LatitudeValue->TryGetNumber(TmpValue)) { Latitude = TmpValue; } } const TSharedPtr<FJsonValue> LongitudeValue = obj->TryGetField(TEXT("Longitude")); if (LongitudeValue.IsValid() && !LongitudeValue->IsNull()) { double TmpValue; if (LongitudeValue->TryGetNumber(TmpValue)) { Longitude = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FPlayerStatistic::~FPlayerStatistic() { } void PlayFab::ServerModels::FPlayerStatistic::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Id.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Id")); writer->WriteValue(Id); } if (Name.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Name")); writer->WriteValue(Name); } writer->WriteIdentifierPrefix(TEXT("StatisticValue")); writer->WriteValue(StatisticValue); writer->WriteIdentifierPrefix(TEXT("StatisticVersion")); writer->WriteValue(StatisticVersion); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FPlayerStatistic::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> IdValue = obj->TryGetField(TEXT("Id")); if (IdValue.IsValid() && !IdValue->IsNull()) { FString TmpValue; if (IdValue->TryGetString(TmpValue)) { Id = TmpValue; } } const TSharedPtr<FJsonValue> NameValue = obj->TryGetField(TEXT("Name")); if (NameValue.IsValid() && !NameValue->IsNull()) { FString TmpValue; if (NameValue->TryGetString(TmpValue)) { Name = TmpValue; } } const TSharedPtr<FJsonValue> StatisticValueValue = obj->TryGetField(TEXT("StatisticValue")); if (StatisticValueValue.IsValid() && !StatisticValueValue->IsNull()) { int32 TmpValue; if (StatisticValueValue->TryGetNumber(TmpValue)) { StatisticValue = TmpValue; } } const TSharedPtr<FJsonValue> StatisticVersionValue = obj->TryGetField(TEXT("StatisticVersion")); if (StatisticVersionValue.IsValid() && !StatisticVersionValue->IsNull()) { int32 TmpValue; if (StatisticVersionValue->TryGetNumber(TmpValue)) { StatisticVersion = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FPushNotificationRegistration::~FPushNotificationRegistration() { } void PlayFab::ServerModels::FPushNotificationRegistration::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (NotificationEndpointARN.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("NotificationEndpointARN")); writer->WriteValue(NotificationEndpointARN); } if (Platform.notNull()) { writer->WriteIdentifierPrefix(TEXT("Platform")); writePushNotificationPlatformEnumJSON(Platform, writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FPushNotificationRegistration::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> NotificationEndpointARNValue = obj->TryGetField(TEXT("NotificationEndpointARN")); if (NotificationEndpointARNValue.IsValid() && !NotificationEndpointARNValue->IsNull()) { FString TmpValue; if (NotificationEndpointARNValue->TryGetString(TmpValue)) { NotificationEndpointARN = TmpValue; } } Platform = readPushNotificationPlatformFromValue(obj->TryGetField(TEXT("Platform"))); return HasSucceeded; } PlayFab::ServerModels::FPlayerProfile::~FPlayerProfile() { } void PlayFab::ServerModels::FPlayerProfile::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (AdCampaignAttributions.Num() != 0) { writer->WriteArrayStart(TEXT("AdCampaignAttributions")); for (const FAdCampaignAttribution& item : AdCampaignAttributions) item.writeJSON(writer); writer->WriteArrayEnd(); } if (AvatarUrl.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("AvatarUrl")); writer->WriteValue(AvatarUrl); } if (BannedUntil.notNull()) { writer->WriteIdentifierPrefix(TEXT("BannedUntil")); writeDatetime(BannedUntil, writer); } if (ContactEmailAddresses.Num() != 0) { writer->WriteArrayStart(TEXT("ContactEmailAddresses")); for (const FContactEmailInfo& item : ContactEmailAddresses) item.writeJSON(writer); writer->WriteArrayEnd(); } if (Created.notNull()) { writer->WriteIdentifierPrefix(TEXT("Created")); writeDatetime(Created, writer); } if (DisplayName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("DisplayName")); writer->WriteValue(DisplayName); } if (LastLogin.notNull()) { writer->WriteIdentifierPrefix(TEXT("LastLogin")); writeDatetime(LastLogin, writer); } if (LinkedAccounts.Num() != 0) { writer->WriteArrayStart(TEXT("LinkedAccounts")); for (const FPlayerLinkedAccount& item : LinkedAccounts) item.writeJSON(writer); writer->WriteArrayEnd(); } if (Locations.Num() != 0) { writer->WriteObjectStart(TEXT("Locations")); for (TMap<FString, FPlayerLocation>::TConstIterator It(Locations); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } if (Origination.notNull()) { writer->WriteIdentifierPrefix(TEXT("Origination")); writeLoginIdentityProviderEnumJSON(Origination, writer); } if (PlayerId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayerId")); writer->WriteValue(PlayerId); } if (PlayerStatistics.Num() != 0) { writer->WriteArrayStart(TEXT("PlayerStatistics")); for (const FPlayerStatistic& item : PlayerStatistics) item.writeJSON(writer); writer->WriteArrayEnd(); } if (PublisherId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PublisherId")); writer->WriteValue(PublisherId); } if (PushNotificationRegistrations.Num() != 0) { writer->WriteArrayStart(TEXT("PushNotificationRegistrations")); for (const FPushNotificationRegistration& item : PushNotificationRegistrations) item.writeJSON(writer); writer->WriteArrayEnd(); } if (Statistics.Num() != 0) { writer->WriteObjectStart(TEXT("Statistics")); for (TMap<FString, int32>::TConstIterator It(Statistics); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (Tags.Num() != 0) { writer->WriteArrayStart(TEXT("Tags")); for (const FString& item : Tags) writer->WriteValue(item); writer->WriteArrayEnd(); } if (TitleId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("TitleId")); writer->WriteValue(TitleId); } if (TotalValueToDateInUSD.notNull()) { writer->WriteIdentifierPrefix(TEXT("TotalValueToDateInUSD")); writer->WriteValue(static_cast<int64>(TotalValueToDateInUSD)); } if (ValuesToDate.Num() != 0) { writer->WriteObjectStart(TEXT("ValuesToDate")); for (TMap<FString, uint32>::TConstIterator It(ValuesToDate); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue(static_cast<int64>((*It).Value)); } writer->WriteObjectEnd(); } if (VirtualCurrencyBalances.Num() != 0) { writer->WriteObjectStart(TEXT("VirtualCurrencyBalances")); for (TMap<FString, int32>::TConstIterator It(VirtualCurrencyBalances); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FPlayerProfile::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&AdCampaignAttributionsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("AdCampaignAttributions")); for (int32 Idx = 0; Idx < AdCampaignAttributionsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = AdCampaignAttributionsArray[Idx]; AdCampaignAttributions.Add(FAdCampaignAttribution(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> AvatarUrlValue = obj->TryGetField(TEXT("AvatarUrl")); if (AvatarUrlValue.IsValid() && !AvatarUrlValue->IsNull()) { FString TmpValue; if (AvatarUrlValue->TryGetString(TmpValue)) { AvatarUrl = TmpValue; } } const TSharedPtr<FJsonValue> BannedUntilValue = obj->TryGetField(TEXT("BannedUntil")); if (BannedUntilValue.IsValid()) BannedUntil = readDatetime(BannedUntilValue); const TArray<TSharedPtr<FJsonValue>>&ContactEmailAddressesArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("ContactEmailAddresses")); for (int32 Idx = 0; Idx < ContactEmailAddressesArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = ContactEmailAddressesArray[Idx]; ContactEmailAddresses.Add(FContactEmailInfo(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> CreatedValue = obj->TryGetField(TEXT("Created")); if (CreatedValue.IsValid()) Created = readDatetime(CreatedValue); const TSharedPtr<FJsonValue> DisplayNameValue = obj->TryGetField(TEXT("DisplayName")); if (DisplayNameValue.IsValid() && !DisplayNameValue->IsNull()) { FString TmpValue; if (DisplayNameValue->TryGetString(TmpValue)) { DisplayName = TmpValue; } } const TSharedPtr<FJsonValue> LastLoginValue = obj->TryGetField(TEXT("LastLogin")); if (LastLoginValue.IsValid()) LastLogin = readDatetime(LastLoginValue); const TArray<TSharedPtr<FJsonValue>>&LinkedAccountsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("LinkedAccounts")); for (int32 Idx = 0; Idx < LinkedAccountsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = LinkedAccountsArray[Idx]; LinkedAccounts.Add(FPlayerLinkedAccount(CurrentItem->AsObject())); } const TSharedPtr<FJsonObject>* LocationsObject; if (obj->TryGetObjectField(TEXT("Locations"), LocationsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*LocationsObject)->Values); It; ++It) { Locations.Add(It.Key(), FPlayerLocation(It.Value()->AsObject())); } } Origination = readLoginIdentityProviderFromValue(obj->TryGetField(TEXT("Origination"))); const TSharedPtr<FJsonValue> PlayerIdValue = obj->TryGetField(TEXT("PlayerId")); if (PlayerIdValue.IsValid() && !PlayerIdValue->IsNull()) { FString TmpValue; if (PlayerIdValue->TryGetString(TmpValue)) { PlayerId = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&PlayerStatisticsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("PlayerStatistics")); for (int32 Idx = 0; Idx < PlayerStatisticsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = PlayerStatisticsArray[Idx]; PlayerStatistics.Add(FPlayerStatistic(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> PublisherIdValue = obj->TryGetField(TEXT("PublisherId")); if (PublisherIdValue.IsValid() && !PublisherIdValue->IsNull()) { FString TmpValue; if (PublisherIdValue->TryGetString(TmpValue)) { PublisherId = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&PushNotificationRegistrationsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("PushNotificationRegistrations")); for (int32 Idx = 0; Idx < PushNotificationRegistrationsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = PushNotificationRegistrationsArray[Idx]; PushNotificationRegistrations.Add(FPushNotificationRegistration(CurrentItem->AsObject())); } const TSharedPtr<FJsonObject>* StatisticsObject; if (obj->TryGetObjectField(TEXT("Statistics"), StatisticsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*StatisticsObject)->Values); It; ++It) { int32 TmpValue; It.Value()->TryGetNumber(TmpValue); Statistics.Add(It.Key(), TmpValue); } } obj->TryGetStringArrayField(TEXT("Tags"), Tags); const TSharedPtr<FJsonValue> TitleIdValue = obj->TryGetField(TEXT("TitleId")); if (TitleIdValue.IsValid() && !TitleIdValue->IsNull()) { FString TmpValue; if (TitleIdValue->TryGetString(TmpValue)) { TitleId = TmpValue; } } const TSharedPtr<FJsonValue> TotalValueToDateInUSDValue = obj->TryGetField(TEXT("TotalValueToDateInUSD")); if (TotalValueToDateInUSDValue.IsValid() && !TotalValueToDateInUSDValue->IsNull()) { uint32 TmpValue; if (TotalValueToDateInUSDValue->TryGetNumber(TmpValue)) { TotalValueToDateInUSD = TmpValue; } } const TSharedPtr<FJsonObject>* ValuesToDateObject; if (obj->TryGetObjectField(TEXT("ValuesToDate"), ValuesToDateObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*ValuesToDateObject)->Values); It; ++It) { uint32 TmpValue; It.Value()->TryGetNumber(TmpValue); ValuesToDate.Add(It.Key(), TmpValue); } } const TSharedPtr<FJsonObject>* VirtualCurrencyBalancesObject; if (obj->TryGetObjectField(TEXT("VirtualCurrencyBalances"), VirtualCurrencyBalancesObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*VirtualCurrencyBalancesObject)->Values); It; ++It) { int32 TmpValue; It.Value()->TryGetNumber(TmpValue); VirtualCurrencyBalances.Add(It.Key(), TmpValue); } } return HasSucceeded; } PlayFab::ServerModels::FGetPlayersInSegmentResult::~FGetPlayersInSegmentResult() { } void PlayFab::ServerModels::FGetPlayersInSegmentResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (ContinuationToken.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ContinuationToken")); writer->WriteValue(ContinuationToken); } if (PlayerProfiles.Num() != 0) { writer->WriteArrayStart(TEXT("PlayerProfiles")); for (const FPlayerProfile& item : PlayerProfiles) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteIdentifierPrefix(TEXT("ProfilesInSegment")); writer->WriteValue(ProfilesInSegment); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayersInSegmentResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ContinuationTokenValue = obj->TryGetField(TEXT("ContinuationToken")); if (ContinuationTokenValue.IsValid() && !ContinuationTokenValue->IsNull()) { FString TmpValue; if (ContinuationTokenValue->TryGetString(TmpValue)) { ContinuationToken = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&PlayerProfilesArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("PlayerProfiles")); for (int32 Idx = 0; Idx < PlayerProfilesArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = PlayerProfilesArray[Idx]; PlayerProfiles.Add(FPlayerProfile(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> ProfilesInSegmentValue = obj->TryGetField(TEXT("ProfilesInSegment")); if (ProfilesInSegmentValue.IsValid() && !ProfilesInSegmentValue->IsNull()) { int32 TmpValue; if (ProfilesInSegmentValue->TryGetNumber(TmpValue)) { ProfilesInSegment = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetPlayersSegmentsRequest::~FGetPlayersSegmentsRequest() { } void PlayFab::ServerModels::FGetPlayersSegmentsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayersSegmentsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FStatisticNameVersion::~FStatisticNameVersion() { } void PlayFab::ServerModels::FStatisticNameVersion::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("StatisticName")); writer->WriteValue(StatisticName); writer->WriteIdentifierPrefix(TEXT("Version")); writer->WriteValue(static_cast<int64>(Version)); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FStatisticNameVersion::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> StatisticNameValue = obj->TryGetField(TEXT("StatisticName")); if (StatisticNameValue.IsValid() && !StatisticNameValue->IsNull()) { FString TmpValue; if (StatisticNameValue->TryGetString(TmpValue)) { StatisticName = TmpValue; } } const TSharedPtr<FJsonValue> VersionValue = obj->TryGetField(TEXT("Version")); if (VersionValue.IsValid() && !VersionValue->IsNull()) { uint32 TmpValue; if (VersionValue->TryGetNumber(TmpValue)) { Version = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetPlayerStatisticsRequest::~FGetPlayerStatisticsRequest() { } void PlayFab::ServerModels::FGetPlayerStatisticsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); if (StatisticNames.Num() != 0) { writer->WriteArrayStart(TEXT("StatisticNames")); for (const FString& item : StatisticNames) writer->WriteValue(item); writer->WriteArrayEnd(); } if (StatisticNameVersions.Num() != 0) { writer->WriteArrayStart(TEXT("StatisticNameVersions")); for (const FStatisticNameVersion& item : StatisticNameVersions) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayerStatisticsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } obj->TryGetStringArrayField(TEXT("StatisticNames"), StatisticNames); const TArray<TSharedPtr<FJsonValue>>&StatisticNameVersionsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("StatisticNameVersions")); for (int32 Idx = 0; Idx < StatisticNameVersionsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = StatisticNameVersionsArray[Idx]; StatisticNameVersions.Add(FStatisticNameVersion(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetPlayerStatisticsResult::~FGetPlayerStatisticsResult() { } void PlayFab::ServerModels::FGetPlayerStatisticsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } if (Statistics.Num() != 0) { writer->WriteArrayStart(TEXT("Statistics")); for (const FStatisticValue& item : Statistics) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayerStatisticsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&StatisticsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Statistics")); for (int32 Idx = 0; Idx < StatisticsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = StatisticsArray[Idx]; Statistics.Add(FStatisticValue(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetPlayerStatisticVersionsRequest::~FGetPlayerStatisticVersionsRequest() { } void PlayFab::ServerModels::FGetPlayerStatisticVersionsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (StatisticName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("StatisticName")); writer->WriteValue(StatisticName); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayerStatisticVersionsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> StatisticNameValue = obj->TryGetField(TEXT("StatisticName")); if (StatisticNameValue.IsValid() && !StatisticNameValue->IsNull()) { FString TmpValue; if (StatisticNameValue->TryGetString(TmpValue)) { StatisticName = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FPlayerStatisticVersion::~FPlayerStatisticVersion() { } void PlayFab::ServerModels::FPlayerStatisticVersion::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("ActivationTime")); writeDatetime(ActivationTime, writer); if (DeactivationTime.notNull()) { writer->WriteIdentifierPrefix(TEXT("DeactivationTime")); writeDatetime(DeactivationTime, writer); } if (ScheduledActivationTime.notNull()) { writer->WriteIdentifierPrefix(TEXT("ScheduledActivationTime")); writeDatetime(ScheduledActivationTime, writer); } if (ScheduledDeactivationTime.notNull()) { writer->WriteIdentifierPrefix(TEXT("ScheduledDeactivationTime")); writeDatetime(ScheduledDeactivationTime, writer); } if (StatisticName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("StatisticName")); writer->WriteValue(StatisticName); } writer->WriteIdentifierPrefix(TEXT("Version")); writer->WriteValue(static_cast<int64>(Version)); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FPlayerStatisticVersion::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ActivationTimeValue = obj->TryGetField(TEXT("ActivationTime")); if (ActivationTimeValue.IsValid()) ActivationTime = readDatetime(ActivationTimeValue); const TSharedPtr<FJsonValue> DeactivationTimeValue = obj->TryGetField(TEXT("DeactivationTime")); if (DeactivationTimeValue.IsValid()) DeactivationTime = readDatetime(DeactivationTimeValue); const TSharedPtr<FJsonValue> ScheduledActivationTimeValue = obj->TryGetField(TEXT("ScheduledActivationTime")); if (ScheduledActivationTimeValue.IsValid()) ScheduledActivationTime = readDatetime(ScheduledActivationTimeValue); const TSharedPtr<FJsonValue> ScheduledDeactivationTimeValue = obj->TryGetField(TEXT("ScheduledDeactivationTime")); if (ScheduledDeactivationTimeValue.IsValid()) ScheduledDeactivationTime = readDatetime(ScheduledDeactivationTimeValue); const TSharedPtr<FJsonValue> StatisticNameValue = obj->TryGetField(TEXT("StatisticName")); if (StatisticNameValue.IsValid() && !StatisticNameValue->IsNull()) { FString TmpValue; if (StatisticNameValue->TryGetString(TmpValue)) { StatisticName = TmpValue; } } const TSharedPtr<FJsonValue> VersionValue = obj->TryGetField(TEXT("Version")); if (VersionValue.IsValid() && !VersionValue->IsNull()) { uint32 TmpValue; if (VersionValue->TryGetNumber(TmpValue)) { Version = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetPlayerStatisticVersionsResult::~FGetPlayerStatisticVersionsResult() { } void PlayFab::ServerModels::FGetPlayerStatisticVersionsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (StatisticVersions.Num() != 0) { writer->WriteArrayStart(TEXT("StatisticVersions")); for (const FPlayerStatisticVersion& item : StatisticVersions) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayerStatisticVersionsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&StatisticVersionsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("StatisticVersions")); for (int32 Idx = 0; Idx < StatisticVersionsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = StatisticVersionsArray[Idx]; StatisticVersions.Add(FPlayerStatisticVersion(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetPlayerTagsRequest::~FGetPlayerTagsRequest() { } void PlayFab::ServerModels::FGetPlayerTagsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Namespace.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Namespace")); writer->WriteValue(Namespace); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayerTagsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> NamespaceValue = obj->TryGetField(TEXT("Namespace")); if (NamespaceValue.IsValid() && !NamespaceValue->IsNull()) { FString TmpValue; if (NamespaceValue->TryGetString(TmpValue)) { Namespace = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetPlayerTagsResult::~FGetPlayerTagsResult() { } void PlayFab::ServerModels::FGetPlayerTagsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteArrayStart(TEXT("Tags")); for (const FString& item : Tags) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayerTagsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } HasSucceeded &= obj->TryGetStringArrayField(TEXT("Tags"), Tags); return HasSucceeded; } PlayFab::ServerModels::FGetPlayFabIDsFromFacebookIDsRequest::~FGetPlayFabIDsFromFacebookIDsRequest() { } void PlayFab::ServerModels::FGetPlayFabIDsFromFacebookIDsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteArrayStart(TEXT("FacebookIDs")); for (const FString& item : FacebookIDs) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayFabIDsFromFacebookIDsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; HasSucceeded &= obj->TryGetStringArrayField(TEXT("FacebookIDs"), FacebookIDs); return HasSucceeded; } PlayFab::ServerModels::FGetPlayFabIDsFromFacebookIDsResult::~FGetPlayFabIDsFromFacebookIDsResult() { } void PlayFab::ServerModels::FGetPlayFabIDsFromFacebookIDsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteArrayStart(TEXT("Data")); for (const FFacebookPlayFabIdPair& item : Data) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayFabIDsFromFacebookIDsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&DataArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Data")); for (int32 Idx = 0; Idx < DataArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = DataArray[Idx]; Data.Add(FFacebookPlayFabIdPair(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetPlayFabIDsFromFacebookInstantGamesIdsRequest::~FGetPlayFabIDsFromFacebookInstantGamesIdsRequest() { } void PlayFab::ServerModels::FGetPlayFabIDsFromFacebookInstantGamesIdsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteArrayStart(TEXT("FacebookInstantGamesIds")); for (const FString& item : FacebookInstantGamesIds) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayFabIDsFromFacebookInstantGamesIdsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; HasSucceeded &= obj->TryGetStringArrayField(TEXT("FacebookInstantGamesIds"), FacebookInstantGamesIds); return HasSucceeded; } PlayFab::ServerModels::FGetPlayFabIDsFromFacebookInstantGamesIdsResult::~FGetPlayFabIDsFromFacebookInstantGamesIdsResult() { } void PlayFab::ServerModels::FGetPlayFabIDsFromFacebookInstantGamesIdsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteArrayStart(TEXT("Data")); for (const FFacebookInstantGamesPlayFabIdPair& item : Data) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayFabIDsFromFacebookInstantGamesIdsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&DataArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Data")); for (int32 Idx = 0; Idx < DataArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = DataArray[Idx]; Data.Add(FFacebookInstantGamesPlayFabIdPair(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetPlayFabIDsFromGenericIDsRequest::~FGetPlayFabIDsFromGenericIDsRequest() { } void PlayFab::ServerModels::FGetPlayFabIDsFromGenericIDsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteArrayStart(TEXT("GenericIDs")); for (const FGenericServiceId& item : GenericIDs) item.writeJSON(writer); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayFabIDsFromGenericIDsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&GenericIDsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("GenericIDs")); for (int32 Idx = 0; Idx < GenericIDsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = GenericIDsArray[Idx]; GenericIDs.Add(FGenericServiceId(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetPlayFabIDsFromGenericIDsResult::~FGetPlayFabIDsFromGenericIDsResult() { } void PlayFab::ServerModels::FGetPlayFabIDsFromGenericIDsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteArrayStart(TEXT("Data")); for (const FGenericPlayFabIdPair& item : Data) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayFabIDsFromGenericIDsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&DataArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Data")); for (int32 Idx = 0; Idx < DataArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = DataArray[Idx]; Data.Add(FGenericPlayFabIdPair(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetPlayFabIDsFromNintendoSwitchDeviceIdsRequest::~FGetPlayFabIDsFromNintendoSwitchDeviceIdsRequest() { } void PlayFab::ServerModels::FGetPlayFabIDsFromNintendoSwitchDeviceIdsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteArrayStart(TEXT("NintendoSwitchDeviceIds")); for (const FString& item : NintendoSwitchDeviceIds) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayFabIDsFromNintendoSwitchDeviceIdsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; HasSucceeded &= obj->TryGetStringArrayField(TEXT("NintendoSwitchDeviceIds"), NintendoSwitchDeviceIds); return HasSucceeded; } PlayFab::ServerModels::FNintendoSwitchPlayFabIdPair::~FNintendoSwitchPlayFabIdPair() { } void PlayFab::ServerModels::FNintendoSwitchPlayFabIdPair::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (NintendoSwitchDeviceId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("NintendoSwitchDeviceId")); writer->WriteValue(NintendoSwitchDeviceId); } if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FNintendoSwitchPlayFabIdPair::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> NintendoSwitchDeviceIdValue = obj->TryGetField(TEXT("NintendoSwitchDeviceId")); if (NintendoSwitchDeviceIdValue.IsValid() && !NintendoSwitchDeviceIdValue->IsNull()) { FString TmpValue; if (NintendoSwitchDeviceIdValue->TryGetString(TmpValue)) { NintendoSwitchDeviceId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetPlayFabIDsFromNintendoSwitchDeviceIdsResult::~FGetPlayFabIDsFromNintendoSwitchDeviceIdsResult() { } void PlayFab::ServerModels::FGetPlayFabIDsFromNintendoSwitchDeviceIdsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteArrayStart(TEXT("Data")); for (const FNintendoSwitchPlayFabIdPair& item : Data) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayFabIDsFromNintendoSwitchDeviceIdsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&DataArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Data")); for (int32 Idx = 0; Idx < DataArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = DataArray[Idx]; Data.Add(FNintendoSwitchPlayFabIdPair(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetPlayFabIDsFromPSNAccountIDsRequest::~FGetPlayFabIDsFromPSNAccountIDsRequest() { } void PlayFab::ServerModels::FGetPlayFabIDsFromPSNAccountIDsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (IssuerId.notNull()) { writer->WriteIdentifierPrefix(TEXT("IssuerId")); writer->WriteValue(IssuerId); } writer->WriteArrayStart(TEXT("PSNAccountIDs")); for (const FString& item : PSNAccountIDs) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayFabIDsFromPSNAccountIDsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> IssuerIdValue = obj->TryGetField(TEXT("IssuerId")); if (IssuerIdValue.IsValid() && !IssuerIdValue->IsNull()) { int32 TmpValue; if (IssuerIdValue->TryGetNumber(TmpValue)) { IssuerId = TmpValue; } } HasSucceeded &= obj->TryGetStringArrayField(TEXT("PSNAccountIDs"), PSNAccountIDs); return HasSucceeded; } PlayFab::ServerModels::FPSNAccountPlayFabIdPair::~FPSNAccountPlayFabIdPair() { } void PlayFab::ServerModels::FPSNAccountPlayFabIdPair::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } if (PSNAccountId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PSNAccountId")); writer->WriteValue(PSNAccountId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FPSNAccountPlayFabIdPair::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> PSNAccountIdValue = obj->TryGetField(TEXT("PSNAccountId")); if (PSNAccountIdValue.IsValid() && !PSNAccountIdValue->IsNull()) { FString TmpValue; if (PSNAccountIdValue->TryGetString(TmpValue)) { PSNAccountId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetPlayFabIDsFromPSNAccountIDsResult::~FGetPlayFabIDsFromPSNAccountIDsResult() { } void PlayFab::ServerModels::FGetPlayFabIDsFromPSNAccountIDsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteArrayStart(TEXT("Data")); for (const FPSNAccountPlayFabIdPair& item : Data) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayFabIDsFromPSNAccountIDsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&DataArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Data")); for (int32 Idx = 0; Idx < DataArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = DataArray[Idx]; Data.Add(FPSNAccountPlayFabIdPair(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetPlayFabIDsFromSteamIDsRequest::~FGetPlayFabIDsFromSteamIDsRequest() { } void PlayFab::ServerModels::FGetPlayFabIDsFromSteamIDsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (SteamStringIDs.Num() != 0) { writer->WriteArrayStart(TEXT("SteamStringIDs")); for (const FString& item : SteamStringIDs) writer->WriteValue(item); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayFabIDsFromSteamIDsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; obj->TryGetStringArrayField(TEXT("SteamStringIDs"), SteamStringIDs); return HasSucceeded; } PlayFab::ServerModels::FSteamPlayFabIdPair::~FSteamPlayFabIdPair() { } void PlayFab::ServerModels::FSteamPlayFabIdPair::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } if (SteamStringId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("SteamStringId")); writer->WriteValue(SteamStringId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSteamPlayFabIdPair::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> SteamStringIdValue = obj->TryGetField(TEXT("SteamStringId")); if (SteamStringIdValue.IsValid() && !SteamStringIdValue->IsNull()) { FString TmpValue; if (SteamStringIdValue->TryGetString(TmpValue)) { SteamStringId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetPlayFabIDsFromSteamIDsResult::~FGetPlayFabIDsFromSteamIDsResult() { } void PlayFab::ServerModels::FGetPlayFabIDsFromSteamIDsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteArrayStart(TEXT("Data")); for (const FSteamPlayFabIdPair& item : Data) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayFabIDsFromSteamIDsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&DataArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Data")); for (int32 Idx = 0; Idx < DataArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = DataArray[Idx]; Data.Add(FSteamPlayFabIdPair(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetPlayFabIDsFromXboxLiveIDsRequest::~FGetPlayFabIDsFromXboxLiveIDsRequest() { } void PlayFab::ServerModels::FGetPlayFabIDsFromXboxLiveIDsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Sandbox.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Sandbox")); writer->WriteValue(Sandbox); } writer->WriteArrayStart(TEXT("XboxLiveAccountIDs")); for (const FString& item : XboxLiveAccountIDs) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayFabIDsFromXboxLiveIDsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> SandboxValue = obj->TryGetField(TEXT("Sandbox")); if (SandboxValue.IsValid() && !SandboxValue->IsNull()) { FString TmpValue; if (SandboxValue->TryGetString(TmpValue)) { Sandbox = TmpValue; } } HasSucceeded &= obj->TryGetStringArrayField(TEXT("XboxLiveAccountIDs"), XboxLiveAccountIDs); return HasSucceeded; } PlayFab::ServerModels::FXboxLiveAccountPlayFabIdPair::~FXboxLiveAccountPlayFabIdPair() { } void PlayFab::ServerModels::FXboxLiveAccountPlayFabIdPair::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } if (XboxLiveAccountId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("XboxLiveAccountId")); writer->WriteValue(XboxLiveAccountId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FXboxLiveAccountPlayFabIdPair::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> XboxLiveAccountIdValue = obj->TryGetField(TEXT("XboxLiveAccountId")); if (XboxLiveAccountIdValue.IsValid() && !XboxLiveAccountIdValue->IsNull()) { FString TmpValue; if (XboxLiveAccountIdValue->TryGetString(TmpValue)) { XboxLiveAccountId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetPlayFabIDsFromXboxLiveIDsResult::~FGetPlayFabIDsFromXboxLiveIDsResult() { } void PlayFab::ServerModels::FGetPlayFabIDsFromXboxLiveIDsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteArrayStart(TEXT("Data")); for (const FXboxLiveAccountPlayFabIdPair& item : Data) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPlayFabIDsFromXboxLiveIDsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&DataArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Data")); for (int32 Idx = 0; Idx < DataArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = DataArray[Idx]; Data.Add(FXboxLiveAccountPlayFabIdPair(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetPublisherDataRequest::~FGetPublisherDataRequest() { } void PlayFab::ServerModels::FGetPublisherDataRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteArrayStart(TEXT("Keys")); for (const FString& item : Keys) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPublisherDataRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; HasSucceeded &= obj->TryGetStringArrayField(TEXT("Keys"), Keys); return HasSucceeded; } PlayFab::ServerModels::FGetPublisherDataResult::~FGetPublisherDataResult() { } void PlayFab::ServerModels::FGetPublisherDataResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteObjectStart(TEXT("Data")); for (TMap<FString, FString>::TConstIterator It(Data); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetPublisherDataResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* DataObject; if (obj->TryGetObjectField(TEXT("Data"), DataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*DataObject)->Values); It; ++It) { Data.Add(It.Key(), It.Value()->AsString()); } } return HasSucceeded; } PlayFab::ServerModels::FGetRandomResultTablesRequest::~FGetRandomResultTablesRequest() { } void PlayFab::ServerModels::FGetRandomResultTablesRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } writer->WriteArrayStart(TEXT("TableIDs")); for (const FString& item : TableIDs) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetRandomResultTablesRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } HasSucceeded &= obj->TryGetStringArrayField(TEXT("TableIDs"), TableIDs); return HasSucceeded; } void PlayFab::ServerModels::writeResultTableNodeTypeEnumJSON(ResultTableNodeType enumVal, JsonWriter& writer) { switch (enumVal) { case ResultTableNodeTypeItemId: writer->WriteValue(TEXT("ItemId")); break; case ResultTableNodeTypeTableId: writer->WriteValue(TEXT("TableId")); break; } } ServerModels::ResultTableNodeType PlayFab::ServerModels::readResultTableNodeTypeFromValue(const TSharedPtr<FJsonValue>& value) { return readResultTableNodeTypeFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::ResultTableNodeType PlayFab::ServerModels::readResultTableNodeTypeFromValue(const FString& value) { static TMap<FString, ResultTableNodeType> _ResultTableNodeTypeMap; if (_ResultTableNodeTypeMap.Num() == 0) { // Auto-generate the map on the first use _ResultTableNodeTypeMap.Add(TEXT("ItemId"), ResultTableNodeTypeItemId); _ResultTableNodeTypeMap.Add(TEXT("TableId"), ResultTableNodeTypeTableId); } if (!value.IsEmpty()) { auto output = _ResultTableNodeTypeMap.Find(value); if (output != nullptr) return *output; } return ResultTableNodeTypeItemId; // Basically critical fail } PlayFab::ServerModels::FResultTableNode::~FResultTableNode() { } void PlayFab::ServerModels::FResultTableNode::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("ResultItem")); writer->WriteValue(ResultItem); writer->WriteIdentifierPrefix(TEXT("ResultItemType")); writeResultTableNodeTypeEnumJSON(ResultItemType, writer); writer->WriteIdentifierPrefix(TEXT("Weight")); writer->WriteValue(Weight); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FResultTableNode::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ResultItemValue = obj->TryGetField(TEXT("ResultItem")); if (ResultItemValue.IsValid() && !ResultItemValue->IsNull()) { FString TmpValue; if (ResultItemValue->TryGetString(TmpValue)) { ResultItem = TmpValue; } } ResultItemType = readResultTableNodeTypeFromValue(obj->TryGetField(TEXT("ResultItemType"))); const TSharedPtr<FJsonValue> WeightValue = obj->TryGetField(TEXT("Weight")); if (WeightValue.IsValid() && !WeightValue->IsNull()) { int32 TmpValue; if (WeightValue->TryGetNumber(TmpValue)) { Weight = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FRandomResultTableListing::~FRandomResultTableListing() { } void PlayFab::ServerModels::FRandomResultTableListing::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } writer->WriteArrayStart(TEXT("Nodes")); for (const FResultTableNode& item : Nodes) item.writeJSON(writer); writer->WriteArrayEnd(); writer->WriteIdentifierPrefix(TEXT("TableId")); writer->WriteValue(TableId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRandomResultTableListing::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&NodesArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Nodes")); for (int32 Idx = 0; Idx < NodesArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = NodesArray[Idx]; Nodes.Add(FResultTableNode(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> TableIdValue = obj->TryGetField(TEXT("TableId")); if (TableIdValue.IsValid() && !TableIdValue->IsNull()) { FString TmpValue; if (TableIdValue->TryGetString(TmpValue)) { TableId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetRandomResultTablesResult::~FGetRandomResultTablesResult() { } void PlayFab::ServerModels::FGetRandomResultTablesResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Tables.Num() != 0) { writer->WriteObjectStart(TEXT("Tables")); for (TMap<FString, FRandomResultTableListing>::TConstIterator It(Tables); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetRandomResultTablesResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* TablesObject; if (obj->TryGetObjectField(TEXT("Tables"), TablesObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*TablesObject)->Values); It; ++It) { Tables.Add(It.Key(), FRandomResultTableListing(It.Value()->AsObject())); } } return HasSucceeded; } PlayFab::ServerModels::FGetServerCustomIDsFromPlayFabIDsRequest::~FGetServerCustomIDsFromPlayFabIDsRequest() { } void PlayFab::ServerModels::FGetServerCustomIDsFromPlayFabIDsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteArrayStart(TEXT("PlayFabIDs")); for (const FString& item : PlayFabIDs) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetServerCustomIDsFromPlayFabIDsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; HasSucceeded &= obj->TryGetStringArrayField(TEXT("PlayFabIDs"), PlayFabIDs); return HasSucceeded; } PlayFab::ServerModels::FServerCustomIDPlayFabIDPair::~FServerCustomIDPlayFabIDPair() { } void PlayFab::ServerModels::FServerCustomIDPlayFabIDPair::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } if (ServerCustomId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ServerCustomId")); writer->WriteValue(ServerCustomId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FServerCustomIDPlayFabIDPair::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> ServerCustomIdValue = obj->TryGetField(TEXT("ServerCustomId")); if (ServerCustomIdValue.IsValid() && !ServerCustomIdValue->IsNull()) { FString TmpValue; if (ServerCustomIdValue->TryGetString(TmpValue)) { ServerCustomId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetServerCustomIDsFromPlayFabIDsResult::~FGetServerCustomIDsFromPlayFabIDsResult() { } void PlayFab::ServerModels::FGetServerCustomIDsFromPlayFabIDsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteArrayStart(TEXT("Data")); for (const FServerCustomIDPlayFabIDPair& item : Data) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetServerCustomIDsFromPlayFabIDsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&DataArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Data")); for (int32 Idx = 0; Idx < DataArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = DataArray[Idx]; Data.Add(FServerCustomIDPlayFabIDPair(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetSharedGroupDataRequest::~FGetSharedGroupDataRequest() { } void PlayFab::ServerModels::FGetSharedGroupDataRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (GetMembers.notNull()) { writer->WriteIdentifierPrefix(TEXT("GetMembers")); writer->WriteValue(GetMembers); } if (Keys.Num() != 0) { writer->WriteArrayStart(TEXT("Keys")); for (const FString& item : Keys) writer->WriteValue(item); writer->WriteArrayEnd(); } writer->WriteIdentifierPrefix(TEXT("SharedGroupId")); writer->WriteValue(SharedGroupId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetSharedGroupDataRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> GetMembersValue = obj->TryGetField(TEXT("GetMembers")); if (GetMembersValue.IsValid() && !GetMembersValue->IsNull()) { bool TmpValue; if (GetMembersValue->TryGetBool(TmpValue)) { GetMembers = TmpValue; } } obj->TryGetStringArrayField(TEXT("Keys"), Keys); const TSharedPtr<FJsonValue> SharedGroupIdValue = obj->TryGetField(TEXT("SharedGroupId")); if (SharedGroupIdValue.IsValid() && !SharedGroupIdValue->IsNull()) { FString TmpValue; if (SharedGroupIdValue->TryGetString(TmpValue)) { SharedGroupId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FSharedGroupDataRecord::~FSharedGroupDataRecord() { } void PlayFab::ServerModels::FSharedGroupDataRecord::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("LastUpdated")); writeDatetime(LastUpdated, writer); if (LastUpdatedBy.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("LastUpdatedBy")); writer->WriteValue(LastUpdatedBy); } if (Permission.notNull()) { writer->WriteIdentifierPrefix(TEXT("Permission")); writeUserDataPermissionEnumJSON(Permission, writer); } if (Value.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Value")); writer->WriteValue(Value); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSharedGroupDataRecord::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> LastUpdatedValue = obj->TryGetField(TEXT("LastUpdated")); if (LastUpdatedValue.IsValid()) LastUpdated = readDatetime(LastUpdatedValue); const TSharedPtr<FJsonValue> LastUpdatedByValue = obj->TryGetField(TEXT("LastUpdatedBy")); if (LastUpdatedByValue.IsValid() && !LastUpdatedByValue->IsNull()) { FString TmpValue; if (LastUpdatedByValue->TryGetString(TmpValue)) { LastUpdatedBy = TmpValue; } } Permission = readUserDataPermissionFromValue(obj->TryGetField(TEXT("Permission"))); const TSharedPtr<FJsonValue> ValueValue = obj->TryGetField(TEXT("Value")); if (ValueValue.IsValid() && !ValueValue->IsNull()) { FString TmpValue; if (ValueValue->TryGetString(TmpValue)) { Value = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetSharedGroupDataResult::~FGetSharedGroupDataResult() { } void PlayFab::ServerModels::FGetSharedGroupDataResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteObjectStart(TEXT("Data")); for (TMap<FString, FSharedGroupDataRecord>::TConstIterator It(Data); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } if (Members.Num() != 0) { writer->WriteArrayStart(TEXT("Members")); for (const FString& item : Members) writer->WriteValue(item); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetSharedGroupDataResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* DataObject; if (obj->TryGetObjectField(TEXT("Data"), DataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*DataObject)->Values); It; ++It) { Data.Add(It.Key(), FSharedGroupDataRecord(It.Value()->AsObject())); } } obj->TryGetStringArrayField(TEXT("Members"), Members); return HasSucceeded; } PlayFab::ServerModels::FStoreMarketingModel::~FStoreMarketingModel() { } void PlayFab::ServerModels::FStoreMarketingModel::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Description.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Description")); writer->WriteValue(Description); } if (DisplayName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("DisplayName")); writer->WriteValue(DisplayName); } if (Metadata.notNull()) { writer->WriteIdentifierPrefix(TEXT("Metadata")); Metadata.writeJSON(writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FStoreMarketingModel::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> DescriptionValue = obj->TryGetField(TEXT("Description")); if (DescriptionValue.IsValid() && !DescriptionValue->IsNull()) { FString TmpValue; if (DescriptionValue->TryGetString(TmpValue)) { Description = TmpValue; } } const TSharedPtr<FJsonValue> DisplayNameValue = obj->TryGetField(TEXT("DisplayName")); if (DisplayNameValue.IsValid() && !DisplayNameValue->IsNull()) { FString TmpValue; if (DisplayNameValue->TryGetString(TmpValue)) { DisplayName = TmpValue; } } const TSharedPtr<FJsonValue> MetadataValue = obj->TryGetField(TEXT("Metadata")); if (MetadataValue.IsValid() && !MetadataValue->IsNull()) { Metadata = FJsonKeeper(MetadataValue); } return HasSucceeded; } void PlayFab::ServerModels::writeSourceTypeEnumJSON(SourceType enumVal, JsonWriter& writer) { switch (enumVal) { case SourceTypeAdmin: writer->WriteValue(TEXT("Admin")); break; case SourceTypeBackEnd: writer->WriteValue(TEXT("BackEnd")); break; case SourceTypeGameClient: writer->WriteValue(TEXT("GameClient")); break; case SourceTypeGameServer: writer->WriteValue(TEXT("GameServer")); break; case SourceTypePartner: writer->WriteValue(TEXT("Partner")); break; case SourceTypeCustom: writer->WriteValue(TEXT("Custom")); break; case SourceTypeAPI: writer->WriteValue(TEXT("API")); break; } } ServerModels::SourceType PlayFab::ServerModels::readSourceTypeFromValue(const TSharedPtr<FJsonValue>& value) { return readSourceTypeFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::SourceType PlayFab::ServerModels::readSourceTypeFromValue(const FString& value) { static TMap<FString, SourceType> _SourceTypeMap; if (_SourceTypeMap.Num() == 0) { // Auto-generate the map on the first use _SourceTypeMap.Add(TEXT("Admin"), SourceTypeAdmin); _SourceTypeMap.Add(TEXT("BackEnd"), SourceTypeBackEnd); _SourceTypeMap.Add(TEXT("GameClient"), SourceTypeGameClient); _SourceTypeMap.Add(TEXT("GameServer"), SourceTypeGameServer); _SourceTypeMap.Add(TEXT("Partner"), SourceTypePartner); _SourceTypeMap.Add(TEXT("Custom"), SourceTypeCustom); _SourceTypeMap.Add(TEXT("API"), SourceTypeAPI); } if (!value.IsEmpty()) { auto output = _SourceTypeMap.Find(value); if (output != nullptr) return *output; } return SourceTypeAdmin; // Basically critical fail } PlayFab::ServerModels::FStoreItem::~FStoreItem() { } void PlayFab::ServerModels::FStoreItem::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CustomData.notNull()) { writer->WriteIdentifierPrefix(TEXT("CustomData")); CustomData.writeJSON(writer); } if (DisplayPosition.notNull()) { writer->WriteIdentifierPrefix(TEXT("DisplayPosition")); writer->WriteValue(static_cast<int64>(DisplayPosition)); } writer->WriteIdentifierPrefix(TEXT("ItemId")); writer->WriteValue(ItemId); if (RealCurrencyPrices.Num() != 0) { writer->WriteObjectStart(TEXT("RealCurrencyPrices")); for (TMap<FString, uint32>::TConstIterator It(RealCurrencyPrices); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue(static_cast<int64>((*It).Value)); } writer->WriteObjectEnd(); } if (VirtualCurrencyPrices.Num() != 0) { writer->WriteObjectStart(TEXT("VirtualCurrencyPrices")); for (TMap<FString, uint32>::TConstIterator It(VirtualCurrencyPrices); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue(static_cast<int64>((*It).Value)); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FStoreItem::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CustomDataValue = obj->TryGetField(TEXT("CustomData")); if (CustomDataValue.IsValid() && !CustomDataValue->IsNull()) { CustomData = FJsonKeeper(CustomDataValue); } const TSharedPtr<FJsonValue> DisplayPositionValue = obj->TryGetField(TEXT("DisplayPosition")); if (DisplayPositionValue.IsValid() && !DisplayPositionValue->IsNull()) { uint32 TmpValue; if (DisplayPositionValue->TryGetNumber(TmpValue)) { DisplayPosition = TmpValue; } } const TSharedPtr<FJsonValue> ItemIdValue = obj->TryGetField(TEXT("ItemId")); if (ItemIdValue.IsValid() && !ItemIdValue->IsNull()) { FString TmpValue; if (ItemIdValue->TryGetString(TmpValue)) { ItemId = TmpValue; } } const TSharedPtr<FJsonObject>* RealCurrencyPricesObject; if (obj->TryGetObjectField(TEXT("RealCurrencyPrices"), RealCurrencyPricesObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*RealCurrencyPricesObject)->Values); It; ++It) { uint32 TmpValue; It.Value()->TryGetNumber(TmpValue); RealCurrencyPrices.Add(It.Key(), TmpValue); } } const TSharedPtr<FJsonObject>* VirtualCurrencyPricesObject; if (obj->TryGetObjectField(TEXT("VirtualCurrencyPrices"), VirtualCurrencyPricesObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*VirtualCurrencyPricesObject)->Values); It; ++It) { uint32 TmpValue; It.Value()->TryGetNumber(TmpValue); VirtualCurrencyPrices.Add(It.Key(), TmpValue); } } return HasSucceeded; } PlayFab::ServerModels::FGetStoreItemsResult::~FGetStoreItemsResult() { //if (MarketingData != nullptr) delete MarketingData; } void PlayFab::ServerModels::FGetStoreItemsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } if (MarketingData.IsValid()) { writer->WriteIdentifierPrefix(TEXT("MarketingData")); MarketingData->writeJSON(writer); } if (Source.notNull()) { writer->WriteIdentifierPrefix(TEXT("Source")); writeSourceTypeEnumJSON(Source, writer); } if (Store.Num() != 0) { writer->WriteArrayStart(TEXT("Store")); for (const FStoreItem& item : Store) item.writeJSON(writer); writer->WriteArrayEnd(); } if (StoreId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("StoreId")); writer->WriteValue(StoreId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetStoreItemsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } const TSharedPtr<FJsonValue> MarketingDataValue = obj->TryGetField(TEXT("MarketingData")); if (MarketingDataValue.IsValid() && !MarketingDataValue->IsNull()) { MarketingData = MakeShareable(new FStoreMarketingModel(MarketingDataValue->AsObject())); } Source = readSourceTypeFromValue(obj->TryGetField(TEXT("Source"))); const TArray<TSharedPtr<FJsonValue>>&StoreArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Store")); for (int32 Idx = 0; Idx < StoreArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = StoreArray[Idx]; Store.Add(FStoreItem(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> StoreIdValue = obj->TryGetField(TEXT("StoreId")); if (StoreIdValue.IsValid() && !StoreIdValue->IsNull()) { FString TmpValue; if (StoreIdValue->TryGetString(TmpValue)) { StoreId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetStoreItemsServerRequest::~FGetStoreItemsServerRequest() { } void PlayFab::ServerModels::FGetStoreItemsServerRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } writer->WriteIdentifierPrefix(TEXT("StoreId")); writer->WriteValue(StoreId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetStoreItemsServerRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> StoreIdValue = obj->TryGetField(TEXT("StoreId")); if (StoreIdValue.IsValid() && !StoreIdValue->IsNull()) { FString TmpValue; if (StoreIdValue->TryGetString(TmpValue)) { StoreId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetTimeRequest::~FGetTimeRequest() { } void PlayFab::ServerModels::FGetTimeRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetTimeRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FGetTimeResult::~FGetTimeResult() { } void PlayFab::ServerModels::FGetTimeResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Time")); writeDatetime(Time, writer); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetTimeResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> TimeValue = obj->TryGetField(TEXT("Time")); if (TimeValue.IsValid()) Time = readDatetime(TimeValue); return HasSucceeded; } PlayFab::ServerModels::FGetTitleDataRequest::~FGetTitleDataRequest() { } void PlayFab::ServerModels::FGetTitleDataRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Keys.Num() != 0) { writer->WriteArrayStart(TEXT("Keys")); for (const FString& item : Keys) writer->WriteValue(item); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetTitleDataRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; obj->TryGetStringArrayField(TEXT("Keys"), Keys); return HasSucceeded; } PlayFab::ServerModels::FGetTitleDataResult::~FGetTitleDataResult() { } void PlayFab::ServerModels::FGetTitleDataResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteObjectStart(TEXT("Data")); for (TMap<FString, FString>::TConstIterator It(Data); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetTitleDataResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* DataObject; if (obj->TryGetObjectField(TEXT("Data"), DataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*DataObject)->Values); It; ++It) { Data.Add(It.Key(), It.Value()->AsString()); } } return HasSucceeded; } PlayFab::ServerModels::FGetTitleNewsRequest::~FGetTitleNewsRequest() { } void PlayFab::ServerModels::FGetTitleNewsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Count.notNull()) { writer->WriteIdentifierPrefix(TEXT("Count")); writer->WriteValue(Count); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetTitleNewsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CountValue = obj->TryGetField(TEXT("Count")); if (CountValue.IsValid() && !CountValue->IsNull()) { int32 TmpValue; if (CountValue->TryGetNumber(TmpValue)) { Count = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FTitleNewsItem::~FTitleNewsItem() { } void PlayFab::ServerModels::FTitleNewsItem::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Body.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Body")); writer->WriteValue(Body); } if (NewsId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("NewsId")); writer->WriteValue(NewsId); } writer->WriteIdentifierPrefix(TEXT("Timestamp")); writeDatetime(Timestamp, writer); if (Title.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Title")); writer->WriteValue(Title); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FTitleNewsItem::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> BodyValue = obj->TryGetField(TEXT("Body")); if (BodyValue.IsValid() && !BodyValue->IsNull()) { FString TmpValue; if (BodyValue->TryGetString(TmpValue)) { Body = TmpValue; } } const TSharedPtr<FJsonValue> NewsIdValue = obj->TryGetField(TEXT("NewsId")); if (NewsIdValue.IsValid() && !NewsIdValue->IsNull()) { FString TmpValue; if (NewsIdValue->TryGetString(TmpValue)) { NewsId = TmpValue; } } const TSharedPtr<FJsonValue> TimestampValue = obj->TryGetField(TEXT("Timestamp")); if (TimestampValue.IsValid()) Timestamp = readDatetime(TimestampValue); const TSharedPtr<FJsonValue> TitleValue = obj->TryGetField(TEXT("Title")); if (TitleValue.IsValid() && !TitleValue->IsNull()) { FString TmpValue; if (TitleValue->TryGetString(TmpValue)) { Title = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetTitleNewsResult::~FGetTitleNewsResult() { } void PlayFab::ServerModels::FGetTitleNewsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (News.Num() != 0) { writer->WriteArrayStart(TEXT("News")); for (const FTitleNewsItem& item : News) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetTitleNewsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&NewsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("News")); for (int32 Idx = 0; Idx < NewsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = NewsArray[Idx]; News.Add(FTitleNewsItem(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetUserAccountInfoRequest::~FGetUserAccountInfoRequest() { } void PlayFab::ServerModels::FGetUserAccountInfoRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetUserAccountInfoRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetUserAccountInfoResult::~FGetUserAccountInfoResult() { //if (UserInfo != nullptr) delete UserInfo; } void PlayFab::ServerModels::FGetUserAccountInfoResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (UserInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("UserInfo")); UserInfo->writeJSON(writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetUserAccountInfoResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> UserInfoValue = obj->TryGetField(TEXT("UserInfo")); if (UserInfoValue.IsValid() && !UserInfoValue->IsNull()) { UserInfo = MakeShareable(new FUserAccountInfo(UserInfoValue->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetUserBansRequest::~FGetUserBansRequest() { } void PlayFab::ServerModels::FGetUserBansRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetUserBansRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetUserBansResult::~FGetUserBansResult() { } void PlayFab::ServerModels::FGetUserBansResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (BanData.Num() != 0) { writer->WriteArrayStart(TEXT("BanData")); for (const FBanInfo& item : BanData) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetUserBansResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&BanDataArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("BanData")); for (int32 Idx = 0; Idx < BanDataArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = BanDataArray[Idx]; BanData.Add(FBanInfo(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGetUserDataRequest::~FGetUserDataRequest() { } void PlayFab::ServerModels::FGetUserDataRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (IfChangedFromDataVersion.notNull()) { writer->WriteIdentifierPrefix(TEXT("IfChangedFromDataVersion")); writer->WriteValue(static_cast<int64>(IfChangedFromDataVersion)); } if (Keys.Num() != 0) { writer->WriteArrayStart(TEXT("Keys")); for (const FString& item : Keys) writer->WriteValue(item); writer->WriteArrayEnd(); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetUserDataRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> IfChangedFromDataVersionValue = obj->TryGetField(TEXT("IfChangedFromDataVersion")); if (IfChangedFromDataVersionValue.IsValid() && !IfChangedFromDataVersionValue->IsNull()) { uint32 TmpValue; if (IfChangedFromDataVersionValue->TryGetNumber(TmpValue)) { IfChangedFromDataVersion = TmpValue; } } obj->TryGetStringArrayField(TEXT("Keys"), Keys); const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetUserDataResult::~FGetUserDataResult() { } void PlayFab::ServerModels::FGetUserDataResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteObjectStart(TEXT("Data")); for (TMap<FString, FUserDataRecord>::TConstIterator It(Data); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteIdentifierPrefix(TEXT("DataVersion")); writer->WriteValue(static_cast<int64>(DataVersion)); if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetUserDataResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* DataObject; if (obj->TryGetObjectField(TEXT("Data"), DataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*DataObject)->Values); It; ++It) { Data.Add(It.Key(), FUserDataRecord(It.Value()->AsObject())); } } const TSharedPtr<FJsonValue> DataVersionValue = obj->TryGetField(TEXT("DataVersion")); if (DataVersionValue.IsValid() && !DataVersionValue->IsNull()) { uint32 TmpValue; if (DataVersionValue->TryGetNumber(TmpValue)) { DataVersion = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetUserInventoryRequest::~FGetUserInventoryRequest() { } void PlayFab::ServerModels::FGetUserInventoryRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetUserInventoryRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGetUserInventoryResult::~FGetUserInventoryResult() { } void PlayFab::ServerModels::FGetUserInventoryResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Inventory.Num() != 0) { writer->WriteArrayStart(TEXT("Inventory")); for (const FItemInstance& item : Inventory) item.writeJSON(writer); writer->WriteArrayEnd(); } if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } if (VirtualCurrency.Num() != 0) { writer->WriteObjectStart(TEXT("VirtualCurrency")); for (TMap<FString, int32>::TConstIterator It(VirtualCurrency); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (VirtualCurrencyRechargeTimes.Num() != 0) { writer->WriteObjectStart(TEXT("VirtualCurrencyRechargeTimes")); for (TMap<FString, FVirtualCurrencyRechargeTime>::TConstIterator It(VirtualCurrencyRechargeTimes); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGetUserInventoryResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&InventoryArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Inventory")); for (int32 Idx = 0; Idx < InventoryArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = InventoryArray[Idx]; Inventory.Add(FItemInstance(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonObject>* VirtualCurrencyObject; if (obj->TryGetObjectField(TEXT("VirtualCurrency"), VirtualCurrencyObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*VirtualCurrencyObject)->Values); It; ++It) { int32 TmpValue; It.Value()->TryGetNumber(TmpValue); VirtualCurrency.Add(It.Key(), TmpValue); } } const TSharedPtr<FJsonObject>* VirtualCurrencyRechargeTimesObject; if (obj->TryGetObjectField(TEXT("VirtualCurrencyRechargeTimes"), VirtualCurrencyRechargeTimesObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*VirtualCurrencyRechargeTimesObject)->Values); It; ++It) { VirtualCurrencyRechargeTimes.Add(It.Key(), FVirtualCurrencyRechargeTime(It.Value()->AsObject())); } } return HasSucceeded; } PlayFab::ServerModels::FGrantCharacterToUserRequest::~FGrantCharacterToUserRequest() { } void PlayFab::ServerModels::FGrantCharacterToUserRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("CharacterName")); writer->WriteValue(CharacterName); writer->WriteIdentifierPrefix(TEXT("CharacterType")); writer->WriteValue(CharacterType); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGrantCharacterToUserRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterNameValue = obj->TryGetField(TEXT("CharacterName")); if (CharacterNameValue.IsValid() && !CharacterNameValue->IsNull()) { FString TmpValue; if (CharacterNameValue->TryGetString(TmpValue)) { CharacterName = TmpValue; } } const TSharedPtr<FJsonValue> CharacterTypeValue = obj->TryGetField(TEXT("CharacterType")); if (CharacterTypeValue.IsValid() && !CharacterTypeValue->IsNull()) { FString TmpValue; if (CharacterTypeValue->TryGetString(TmpValue)) { CharacterType = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGrantCharacterToUserResult::~FGrantCharacterToUserResult() { } void PlayFab::ServerModels::FGrantCharacterToUserResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGrantCharacterToUserResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGrantedItemInstance::~FGrantedItemInstance() { } void PlayFab::ServerModels::FGrantedItemInstance::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Annotation.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Annotation")); writer->WriteValue(Annotation); } if (BundleContents.Num() != 0) { writer->WriteArrayStart(TEXT("BundleContents")); for (const FString& item : BundleContents) writer->WriteValue(item); writer->WriteArrayEnd(); } if (BundleParent.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("BundleParent")); writer->WriteValue(BundleParent); } if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } if (CustomData.Num() != 0) { writer->WriteObjectStart(TEXT("CustomData")); for (TMap<FString, FString>::TConstIterator It(CustomData); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (DisplayName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("DisplayName")); writer->WriteValue(DisplayName); } if (Expiration.notNull()) { writer->WriteIdentifierPrefix(TEXT("Expiration")); writeDatetime(Expiration, writer); } if (ItemClass.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ItemClass")); writer->WriteValue(ItemClass); } if (ItemId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ItemId")); writer->WriteValue(ItemId); } if (ItemInstanceId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ItemInstanceId")); writer->WriteValue(ItemInstanceId); } if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } if (PurchaseDate.notNull()) { writer->WriteIdentifierPrefix(TEXT("PurchaseDate")); writeDatetime(PurchaseDate, writer); } if (RemainingUses.notNull()) { writer->WriteIdentifierPrefix(TEXT("RemainingUses")); writer->WriteValue(RemainingUses); } writer->WriteIdentifierPrefix(TEXT("Result")); writer->WriteValue(Result); if (UnitCurrency.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("UnitCurrency")); writer->WriteValue(UnitCurrency); } writer->WriteIdentifierPrefix(TEXT("UnitPrice")); writer->WriteValue(static_cast<int64>(UnitPrice)); if (UsesIncrementedBy.notNull()) { writer->WriteIdentifierPrefix(TEXT("UsesIncrementedBy")); writer->WriteValue(UsesIncrementedBy); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGrantedItemInstance::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AnnotationValue = obj->TryGetField(TEXT("Annotation")); if (AnnotationValue.IsValid() && !AnnotationValue->IsNull()) { FString TmpValue; if (AnnotationValue->TryGetString(TmpValue)) { Annotation = TmpValue; } } obj->TryGetStringArrayField(TEXT("BundleContents"), BundleContents); const TSharedPtr<FJsonValue> BundleParentValue = obj->TryGetField(TEXT("BundleParent")); if (BundleParentValue.IsValid() && !BundleParentValue->IsNull()) { FString TmpValue; if (BundleParentValue->TryGetString(TmpValue)) { BundleParent = TmpValue; } } const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonObject>* CustomDataObject; if (obj->TryGetObjectField(TEXT("CustomData"), CustomDataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*CustomDataObject)->Values); It; ++It) { CustomData.Add(It.Key(), It.Value()->AsString()); } } const TSharedPtr<FJsonValue> DisplayNameValue = obj->TryGetField(TEXT("DisplayName")); if (DisplayNameValue.IsValid() && !DisplayNameValue->IsNull()) { FString TmpValue; if (DisplayNameValue->TryGetString(TmpValue)) { DisplayName = TmpValue; } } const TSharedPtr<FJsonValue> ExpirationValue = obj->TryGetField(TEXT("Expiration")); if (ExpirationValue.IsValid()) Expiration = readDatetime(ExpirationValue); const TSharedPtr<FJsonValue> ItemClassValue = obj->TryGetField(TEXT("ItemClass")); if (ItemClassValue.IsValid() && !ItemClassValue->IsNull()) { FString TmpValue; if (ItemClassValue->TryGetString(TmpValue)) { ItemClass = TmpValue; } } const TSharedPtr<FJsonValue> ItemIdValue = obj->TryGetField(TEXT("ItemId")); if (ItemIdValue.IsValid() && !ItemIdValue->IsNull()) { FString TmpValue; if (ItemIdValue->TryGetString(TmpValue)) { ItemId = TmpValue; } } const TSharedPtr<FJsonValue> ItemInstanceIdValue = obj->TryGetField(TEXT("ItemInstanceId")); if (ItemInstanceIdValue.IsValid() && !ItemInstanceIdValue->IsNull()) { FString TmpValue; if (ItemInstanceIdValue->TryGetString(TmpValue)) { ItemInstanceId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> PurchaseDateValue = obj->TryGetField(TEXT("PurchaseDate")); if (PurchaseDateValue.IsValid()) PurchaseDate = readDatetime(PurchaseDateValue); const TSharedPtr<FJsonValue> RemainingUsesValue = obj->TryGetField(TEXT("RemainingUses")); if (RemainingUsesValue.IsValid() && !RemainingUsesValue->IsNull()) { int32 TmpValue; if (RemainingUsesValue->TryGetNumber(TmpValue)) { RemainingUses = TmpValue; } } const TSharedPtr<FJsonValue> ResultValue = obj->TryGetField(TEXT("Result")); if (ResultValue.IsValid() && !ResultValue->IsNull()) { bool TmpValue; if (ResultValue->TryGetBool(TmpValue)) { Result = TmpValue; } } const TSharedPtr<FJsonValue> UnitCurrencyValue = obj->TryGetField(TEXT("UnitCurrency")); if (UnitCurrencyValue.IsValid() && !UnitCurrencyValue->IsNull()) { FString TmpValue; if (UnitCurrencyValue->TryGetString(TmpValue)) { UnitCurrency = TmpValue; } } const TSharedPtr<FJsonValue> UnitPriceValue = obj->TryGetField(TEXT("UnitPrice")); if (UnitPriceValue.IsValid() && !UnitPriceValue->IsNull()) { uint32 TmpValue; if (UnitPriceValue->TryGetNumber(TmpValue)) { UnitPrice = TmpValue; } } const TSharedPtr<FJsonValue> UsesIncrementedByValue = obj->TryGetField(TEXT("UsesIncrementedBy")); if (UsesIncrementedByValue.IsValid() && !UsesIncrementedByValue->IsNull()) { int32 TmpValue; if (UsesIncrementedByValue->TryGetNumber(TmpValue)) { UsesIncrementedBy = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGrantItemsToCharacterRequest::~FGrantItemsToCharacterRequest() { } void PlayFab::ServerModels::FGrantItemsToCharacterRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Annotation.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Annotation")); writer->WriteValue(Annotation); } if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); if (ItemIds.Num() != 0) { writer->WriteArrayStart(TEXT("ItemIds")); for (const FString& item : ItemIds) writer->WriteValue(item); writer->WriteArrayEnd(); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGrantItemsToCharacterRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AnnotationValue = obj->TryGetField(TEXT("Annotation")); if (AnnotationValue.IsValid() && !AnnotationValue->IsNull()) { FString TmpValue; if (AnnotationValue->TryGetString(TmpValue)) { Annotation = TmpValue; } } const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } obj->TryGetStringArrayField(TEXT("ItemIds"), ItemIds); const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGrantItemsToCharacterResult::~FGrantItemsToCharacterResult() { } void PlayFab::ServerModels::FGrantItemsToCharacterResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (ItemGrantResults.Num() != 0) { writer->WriteArrayStart(TEXT("ItemGrantResults")); for (const FGrantedItemInstance& item : ItemGrantResults) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGrantItemsToCharacterResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&ItemGrantResultsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("ItemGrantResults")); for (int32 Idx = 0; Idx < ItemGrantResultsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = ItemGrantResultsArray[Idx]; ItemGrantResults.Add(FGrantedItemInstance(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGrantItemsToUserRequest::~FGrantItemsToUserRequest() { } void PlayFab::ServerModels::FGrantItemsToUserRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Annotation.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Annotation")); writer->WriteValue(Annotation); } if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } writer->WriteArrayStart(TEXT("ItemIds")); for (const FString& item : ItemIds) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGrantItemsToUserRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AnnotationValue = obj->TryGetField(TEXT("Annotation")); if (AnnotationValue.IsValid() && !AnnotationValue->IsNull()) { FString TmpValue; if (AnnotationValue->TryGetString(TmpValue)) { Annotation = TmpValue; } } const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } HasSucceeded &= obj->TryGetStringArrayField(TEXT("ItemIds"), ItemIds); const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGrantItemsToUserResult::~FGrantItemsToUserResult() { } void PlayFab::ServerModels::FGrantItemsToUserResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (ItemGrantResults.Num() != 0) { writer->WriteArrayStart(TEXT("ItemGrantResults")); for (const FGrantedItemInstance& item : ItemGrantResults) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGrantItemsToUserResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&ItemGrantResultsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("ItemGrantResults")); for (int32 Idx = 0; Idx < ItemGrantResultsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = ItemGrantResultsArray[Idx]; ItemGrantResults.Add(FGrantedItemInstance(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FItemGrant::~FItemGrant() { } void PlayFab::ServerModels::FItemGrant::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Annotation.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Annotation")); writer->WriteValue(Annotation); } if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } if (Data.Num() != 0) { writer->WriteObjectStart(TEXT("Data")); for (TMap<FString, FString>::TConstIterator It(Data); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } writer->WriteIdentifierPrefix(TEXT("ItemId")); writer->WriteValue(ItemId); if (KeysToRemove.Num() != 0) { writer->WriteArrayStart(TEXT("KeysToRemove")); for (const FString& item : KeysToRemove) writer->WriteValue(item); writer->WriteArrayEnd(); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FItemGrant::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AnnotationValue = obj->TryGetField(TEXT("Annotation")); if (AnnotationValue.IsValid() && !AnnotationValue->IsNull()) { FString TmpValue; if (AnnotationValue->TryGetString(TmpValue)) { Annotation = TmpValue; } } const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonObject>* DataObject; if (obj->TryGetObjectField(TEXT("Data"), DataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*DataObject)->Values); It; ++It) { Data.Add(It.Key(), It.Value()->AsString()); } } const TSharedPtr<FJsonValue> ItemIdValue = obj->TryGetField(TEXT("ItemId")); if (ItemIdValue.IsValid() && !ItemIdValue->IsNull()) { FString TmpValue; if (ItemIdValue->TryGetString(TmpValue)) { ItemId = TmpValue; } } obj->TryGetStringArrayField(TEXT("KeysToRemove"), KeysToRemove); const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FGrantItemsToUsersRequest::~FGrantItemsToUsersRequest() { } void PlayFab::ServerModels::FGrantItemsToUsersRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } writer->WriteArrayStart(TEXT("ItemGrants")); for (const FItemGrant& item : ItemGrants) item.writeJSON(writer); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGrantItemsToUsersRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&ItemGrantsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("ItemGrants")); for (int32 Idx = 0; Idx < ItemGrantsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = ItemGrantsArray[Idx]; ItemGrants.Add(FItemGrant(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FGrantItemsToUsersResult::~FGrantItemsToUsersResult() { } void PlayFab::ServerModels::FGrantItemsToUsersResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (ItemGrantResults.Num() != 0) { writer->WriteArrayStart(TEXT("ItemGrantResults")); for (const FGrantedItemInstance& item : ItemGrantResults) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FGrantItemsToUsersResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&ItemGrantResultsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("ItemGrantResults")); for (int32 Idx = 0; Idx < ItemGrantResultsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = ItemGrantResultsArray[Idx]; ItemGrantResults.Add(FGrantedItemInstance(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FLinkServerCustomIdRequest::~FLinkServerCustomIdRequest() { } void PlayFab::ServerModels::FLinkServerCustomIdRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (ForceLink.notNull()) { writer->WriteIdentifierPrefix(TEXT("ForceLink")); writer->WriteValue(ForceLink); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("ServerCustomId")); writer->WriteValue(ServerCustomId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FLinkServerCustomIdRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ForceLinkValue = obj->TryGetField(TEXT("ForceLink")); if (ForceLinkValue.IsValid() && !ForceLinkValue->IsNull()) { bool TmpValue; if (ForceLinkValue->TryGetBool(TmpValue)) { ForceLink = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> ServerCustomIdValue = obj->TryGetField(TEXT("ServerCustomId")); if (ServerCustomIdValue.IsValid() && !ServerCustomIdValue->IsNull()) { FString TmpValue; if (ServerCustomIdValue->TryGetString(TmpValue)) { ServerCustomId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FLinkServerCustomIdResult::~FLinkServerCustomIdResult() { } void PlayFab::ServerModels::FLinkServerCustomIdResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FLinkServerCustomIdResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FLinkXboxAccountRequest::~FLinkXboxAccountRequest() { } void PlayFab::ServerModels::FLinkXboxAccountRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (ForceLink.notNull()) { writer->WriteIdentifierPrefix(TEXT("ForceLink")); writer->WriteValue(ForceLink); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("XboxToken")); writer->WriteValue(XboxToken); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FLinkXboxAccountRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ForceLinkValue = obj->TryGetField(TEXT("ForceLink")); if (ForceLinkValue.IsValid() && !ForceLinkValue->IsNull()) { bool TmpValue; if (ForceLinkValue->TryGetBool(TmpValue)) { ForceLink = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> XboxTokenValue = obj->TryGetField(TEXT("XboxToken")); if (XboxTokenValue.IsValid() && !XboxTokenValue->IsNull()) { FString TmpValue; if (XboxTokenValue->TryGetString(TmpValue)) { XboxToken = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FLinkXboxAccountResult::~FLinkXboxAccountResult() { } void PlayFab::ServerModels::FLinkXboxAccountResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FLinkXboxAccountResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FListUsersCharactersRequest::~FListUsersCharactersRequest() { } void PlayFab::ServerModels::FListUsersCharactersRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FListUsersCharactersRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FListUsersCharactersResult::~FListUsersCharactersResult() { } void PlayFab::ServerModels::FListUsersCharactersResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Characters.Num() != 0) { writer->WriteArrayStart(TEXT("Characters")); for (const FCharacterResult& item : Characters) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FListUsersCharactersResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&CharactersArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Characters")); for (int32 Idx = 0; Idx < CharactersArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = CharactersArray[Idx]; Characters.Add(FCharacterResult(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FLocalizedPushNotificationProperties::~FLocalizedPushNotificationProperties() { } void PlayFab::ServerModels::FLocalizedPushNotificationProperties::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Message.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Message")); writer->WriteValue(Message); } if (Subject.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Subject")); writer->WriteValue(Subject); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FLocalizedPushNotificationProperties::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> MessageValue = obj->TryGetField(TEXT("Message")); if (MessageValue.IsValid() && !MessageValue->IsNull()) { FString TmpValue; if (MessageValue->TryGetString(TmpValue)) { Message = TmpValue; } } const TSharedPtr<FJsonValue> SubjectValue = obj->TryGetField(TEXT("Subject")); if (SubjectValue.IsValid() && !SubjectValue->IsNull()) { FString TmpValue; if (SubjectValue->TryGetString(TmpValue)) { Subject = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FLoginWithServerCustomIdRequest::~FLoginWithServerCustomIdRequest() { //if (InfoRequestParameters != nullptr) delete InfoRequestParameters; } void PlayFab::ServerModels::FLoginWithServerCustomIdRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CreateAccount.notNull()) { writer->WriteIdentifierPrefix(TEXT("CreateAccount")); writer->WriteValue(CreateAccount); } if (InfoRequestParameters.IsValid()) { writer->WriteIdentifierPrefix(TEXT("InfoRequestParameters")); InfoRequestParameters->writeJSON(writer); } if (PlayerSecret.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayerSecret")); writer->WriteValue(PlayerSecret); } if (ServerCustomId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ServerCustomId")); writer->WriteValue(ServerCustomId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FLoginWithServerCustomIdRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CreateAccountValue = obj->TryGetField(TEXT("CreateAccount")); if (CreateAccountValue.IsValid() && !CreateAccountValue->IsNull()) { bool TmpValue; if (CreateAccountValue->TryGetBool(TmpValue)) { CreateAccount = TmpValue; } } const TSharedPtr<FJsonValue> InfoRequestParametersValue = obj->TryGetField(TEXT("InfoRequestParameters")); if (InfoRequestParametersValue.IsValid() && !InfoRequestParametersValue->IsNull()) { InfoRequestParameters = MakeShareable(new FGetPlayerCombinedInfoRequestParams(InfoRequestParametersValue->AsObject())); } const TSharedPtr<FJsonValue> PlayerSecretValue = obj->TryGetField(TEXT("PlayerSecret")); if (PlayerSecretValue.IsValid() && !PlayerSecretValue->IsNull()) { FString TmpValue; if (PlayerSecretValue->TryGetString(TmpValue)) { PlayerSecret = TmpValue; } } const TSharedPtr<FJsonValue> ServerCustomIdValue = obj->TryGetField(TEXT("ServerCustomId")); if (ServerCustomIdValue.IsValid() && !ServerCustomIdValue->IsNull()) { FString TmpValue; if (ServerCustomIdValue->TryGetString(TmpValue)) { ServerCustomId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FLoginWithXboxIdRequest::~FLoginWithXboxIdRequest() { //if (InfoRequestParameters != nullptr) delete InfoRequestParameters; } void PlayFab::ServerModels::FLoginWithXboxIdRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CreateAccount.notNull()) { writer->WriteIdentifierPrefix(TEXT("CreateAccount")); writer->WriteValue(CreateAccount); } if (InfoRequestParameters.IsValid()) { writer->WriteIdentifierPrefix(TEXT("InfoRequestParameters")); InfoRequestParameters->writeJSON(writer); } writer->WriteIdentifierPrefix(TEXT("Sandbox")); writer->WriteValue(Sandbox); writer->WriteIdentifierPrefix(TEXT("XboxId")); writer->WriteValue(XboxId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FLoginWithXboxIdRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CreateAccountValue = obj->TryGetField(TEXT("CreateAccount")); if (CreateAccountValue.IsValid() && !CreateAccountValue->IsNull()) { bool TmpValue; if (CreateAccountValue->TryGetBool(TmpValue)) { CreateAccount = TmpValue; } } const TSharedPtr<FJsonValue> InfoRequestParametersValue = obj->TryGetField(TEXT("InfoRequestParameters")); if (InfoRequestParametersValue.IsValid() && !InfoRequestParametersValue->IsNull()) { InfoRequestParameters = MakeShareable(new FGetPlayerCombinedInfoRequestParams(InfoRequestParametersValue->AsObject())); } const TSharedPtr<FJsonValue> SandboxValue = obj->TryGetField(TEXT("Sandbox")); if (SandboxValue.IsValid() && !SandboxValue->IsNull()) { FString TmpValue; if (SandboxValue->TryGetString(TmpValue)) { Sandbox = TmpValue; } } const TSharedPtr<FJsonValue> XboxIdValue = obj->TryGetField(TEXT("XboxId")); if (XboxIdValue.IsValid() && !XboxIdValue->IsNull()) { FString TmpValue; if (XboxIdValue->TryGetString(TmpValue)) { XboxId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FLoginWithXboxRequest::~FLoginWithXboxRequest() { //if (InfoRequestParameters != nullptr) delete InfoRequestParameters; } void PlayFab::ServerModels::FLoginWithXboxRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CreateAccount.notNull()) { writer->WriteIdentifierPrefix(TEXT("CreateAccount")); writer->WriteValue(CreateAccount); } if (InfoRequestParameters.IsValid()) { writer->WriteIdentifierPrefix(TEXT("InfoRequestParameters")); InfoRequestParameters->writeJSON(writer); } writer->WriteIdentifierPrefix(TEXT("XboxToken")); writer->WriteValue(XboxToken); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FLoginWithXboxRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CreateAccountValue = obj->TryGetField(TEXT("CreateAccount")); if (CreateAccountValue.IsValid() && !CreateAccountValue->IsNull()) { bool TmpValue; if (CreateAccountValue->TryGetBool(TmpValue)) { CreateAccount = TmpValue; } } const TSharedPtr<FJsonValue> InfoRequestParametersValue = obj->TryGetField(TEXT("InfoRequestParameters")); if (InfoRequestParametersValue.IsValid() && !InfoRequestParametersValue->IsNull()) { InfoRequestParameters = MakeShareable(new FGetPlayerCombinedInfoRequestParams(InfoRequestParametersValue->AsObject())); } const TSharedPtr<FJsonValue> XboxTokenValue = obj->TryGetField(TEXT("XboxToken")); if (XboxTokenValue.IsValid() && !XboxTokenValue->IsNull()) { FString TmpValue; if (XboxTokenValue->TryGetString(TmpValue)) { XboxToken = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FModifyCharacterVirtualCurrencyResult::~FModifyCharacterVirtualCurrencyResult() { } void PlayFab::ServerModels::FModifyCharacterVirtualCurrencyResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Balance")); writer->WriteValue(Balance); if (VirtualCurrency.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("VirtualCurrency")); writer->WriteValue(VirtualCurrency); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FModifyCharacterVirtualCurrencyResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> BalanceValue = obj->TryGetField(TEXT("Balance")); if (BalanceValue.IsValid() && !BalanceValue->IsNull()) { int32 TmpValue; if (BalanceValue->TryGetNumber(TmpValue)) { Balance = TmpValue; } } const TSharedPtr<FJsonValue> VirtualCurrencyValue = obj->TryGetField(TEXT("VirtualCurrency")); if (VirtualCurrencyValue.IsValid() && !VirtualCurrencyValue->IsNull()) { FString TmpValue; if (VirtualCurrencyValue->TryGetString(TmpValue)) { VirtualCurrency = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FModifyItemUsesRequest::~FModifyItemUsesRequest() { } void PlayFab::ServerModels::FModifyItemUsesRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("ItemInstanceId")); writer->WriteValue(ItemInstanceId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("UsesToAdd")); writer->WriteValue(UsesToAdd); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FModifyItemUsesRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ItemInstanceIdValue = obj->TryGetField(TEXT("ItemInstanceId")); if (ItemInstanceIdValue.IsValid() && !ItemInstanceIdValue->IsNull()) { FString TmpValue; if (ItemInstanceIdValue->TryGetString(TmpValue)) { ItemInstanceId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> UsesToAddValue = obj->TryGetField(TEXT("UsesToAdd")); if (UsesToAddValue.IsValid() && !UsesToAddValue->IsNull()) { int32 TmpValue; if (UsesToAddValue->TryGetNumber(TmpValue)) { UsesToAdd = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FModifyItemUsesResult::~FModifyItemUsesResult() { } void PlayFab::ServerModels::FModifyItemUsesResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (ItemInstanceId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ItemInstanceId")); writer->WriteValue(ItemInstanceId); } writer->WriteIdentifierPrefix(TEXT("RemainingUses")); writer->WriteValue(RemainingUses); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FModifyItemUsesResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ItemInstanceIdValue = obj->TryGetField(TEXT("ItemInstanceId")); if (ItemInstanceIdValue.IsValid() && !ItemInstanceIdValue->IsNull()) { FString TmpValue; if (ItemInstanceIdValue->TryGetString(TmpValue)) { ItemInstanceId = TmpValue; } } const TSharedPtr<FJsonValue> RemainingUsesValue = obj->TryGetField(TEXT("RemainingUses")); if (RemainingUsesValue.IsValid() && !RemainingUsesValue->IsNull()) { int32 TmpValue; if (RemainingUsesValue->TryGetNumber(TmpValue)) { RemainingUses = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FModifyUserVirtualCurrencyResult::~FModifyUserVirtualCurrencyResult() { } void PlayFab::ServerModels::FModifyUserVirtualCurrencyResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Balance")); writer->WriteValue(Balance); writer->WriteIdentifierPrefix(TEXT("BalanceChange")); writer->WriteValue(BalanceChange); if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } if (VirtualCurrency.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("VirtualCurrency")); writer->WriteValue(VirtualCurrency); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FModifyUserVirtualCurrencyResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> BalanceValue = obj->TryGetField(TEXT("Balance")); if (BalanceValue.IsValid() && !BalanceValue->IsNull()) { int32 TmpValue; if (BalanceValue->TryGetNumber(TmpValue)) { Balance = TmpValue; } } const TSharedPtr<FJsonValue> BalanceChangeValue = obj->TryGetField(TEXT("BalanceChange")); if (BalanceChangeValue.IsValid() && !BalanceChangeValue->IsNull()) { int32 TmpValue; if (BalanceChangeValue->TryGetNumber(TmpValue)) { BalanceChange = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> VirtualCurrencyValue = obj->TryGetField(TEXT("VirtualCurrency")); if (VirtualCurrencyValue.IsValid() && !VirtualCurrencyValue->IsNull()) { FString TmpValue; if (VirtualCurrencyValue->TryGetString(TmpValue)) { VirtualCurrency = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FMoveItemToCharacterFromCharacterRequest::~FMoveItemToCharacterFromCharacterRequest() { } void PlayFab::ServerModels::FMoveItemToCharacterFromCharacterRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("GivingCharacterId")); writer->WriteValue(GivingCharacterId); writer->WriteIdentifierPrefix(TEXT("ItemInstanceId")); writer->WriteValue(ItemInstanceId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("ReceivingCharacterId")); writer->WriteValue(ReceivingCharacterId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FMoveItemToCharacterFromCharacterRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> GivingCharacterIdValue = obj->TryGetField(TEXT("GivingCharacterId")); if (GivingCharacterIdValue.IsValid() && !GivingCharacterIdValue->IsNull()) { FString TmpValue; if (GivingCharacterIdValue->TryGetString(TmpValue)) { GivingCharacterId = TmpValue; } } const TSharedPtr<FJsonValue> ItemInstanceIdValue = obj->TryGetField(TEXT("ItemInstanceId")); if (ItemInstanceIdValue.IsValid() && !ItemInstanceIdValue->IsNull()) { FString TmpValue; if (ItemInstanceIdValue->TryGetString(TmpValue)) { ItemInstanceId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> ReceivingCharacterIdValue = obj->TryGetField(TEXT("ReceivingCharacterId")); if (ReceivingCharacterIdValue.IsValid() && !ReceivingCharacterIdValue->IsNull()) { FString TmpValue; if (ReceivingCharacterIdValue->TryGetString(TmpValue)) { ReceivingCharacterId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FMoveItemToCharacterFromCharacterResult::~FMoveItemToCharacterFromCharacterResult() { } void PlayFab::ServerModels::FMoveItemToCharacterFromCharacterResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FMoveItemToCharacterFromCharacterResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FMoveItemToCharacterFromUserRequest::~FMoveItemToCharacterFromUserRequest() { } void PlayFab::ServerModels::FMoveItemToCharacterFromUserRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); writer->WriteIdentifierPrefix(TEXT("ItemInstanceId")); writer->WriteValue(ItemInstanceId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FMoveItemToCharacterFromUserRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> ItemInstanceIdValue = obj->TryGetField(TEXT("ItemInstanceId")); if (ItemInstanceIdValue.IsValid() && !ItemInstanceIdValue->IsNull()) { FString TmpValue; if (ItemInstanceIdValue->TryGetString(TmpValue)) { ItemInstanceId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FMoveItemToCharacterFromUserResult::~FMoveItemToCharacterFromUserResult() { } void PlayFab::ServerModels::FMoveItemToCharacterFromUserResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FMoveItemToCharacterFromUserResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FMoveItemToUserFromCharacterRequest::~FMoveItemToUserFromCharacterRequest() { } void PlayFab::ServerModels::FMoveItemToUserFromCharacterRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); writer->WriteIdentifierPrefix(TEXT("ItemInstanceId")); writer->WriteValue(ItemInstanceId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FMoveItemToUserFromCharacterRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> ItemInstanceIdValue = obj->TryGetField(TEXT("ItemInstanceId")); if (ItemInstanceIdValue.IsValid() && !ItemInstanceIdValue->IsNull()) { FString TmpValue; if (ItemInstanceIdValue->TryGetString(TmpValue)) { ItemInstanceId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FMoveItemToUserFromCharacterResult::~FMoveItemToUserFromCharacterResult() { } void PlayFab::ServerModels::FMoveItemToUserFromCharacterResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FMoveItemToUserFromCharacterResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FNotifyMatchmakerPlayerLeftRequest::~FNotifyMatchmakerPlayerLeftRequest() { } void PlayFab::ServerModels::FNotifyMatchmakerPlayerLeftRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("LobbyId")); writer->WriteValue(LobbyId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FNotifyMatchmakerPlayerLeftRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> LobbyIdValue = obj->TryGetField(TEXT("LobbyId")); if (LobbyIdValue.IsValid() && !LobbyIdValue->IsNull()) { FString TmpValue; if (LobbyIdValue->TryGetString(TmpValue)) { LobbyId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } void PlayFab::ServerModels::writePlayerConnectionStateEnumJSON(PlayerConnectionState enumVal, JsonWriter& writer) { switch (enumVal) { case PlayerConnectionStateUnassigned: writer->WriteValue(TEXT("Unassigned")); break; case PlayerConnectionStateConnecting: writer->WriteValue(TEXT("Connecting")); break; case PlayerConnectionStateParticipating: writer->WriteValue(TEXT("Participating")); break; case PlayerConnectionStateParticipated: writer->WriteValue(TEXT("Participated")); break; } } ServerModels::PlayerConnectionState PlayFab::ServerModels::readPlayerConnectionStateFromValue(const TSharedPtr<FJsonValue>& value) { return readPlayerConnectionStateFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::PlayerConnectionState PlayFab::ServerModels::readPlayerConnectionStateFromValue(const FString& value) { static TMap<FString, PlayerConnectionState> _PlayerConnectionStateMap; if (_PlayerConnectionStateMap.Num() == 0) { // Auto-generate the map on the first use _PlayerConnectionStateMap.Add(TEXT("Unassigned"), PlayerConnectionStateUnassigned); _PlayerConnectionStateMap.Add(TEXT("Connecting"), PlayerConnectionStateConnecting); _PlayerConnectionStateMap.Add(TEXT("Participating"), PlayerConnectionStateParticipating); _PlayerConnectionStateMap.Add(TEXT("Participated"), PlayerConnectionStateParticipated); } if (!value.IsEmpty()) { auto output = _PlayerConnectionStateMap.Find(value); if (output != nullptr) return *output; } return PlayerConnectionStateUnassigned; // Basically critical fail } PlayFab::ServerModels::FNotifyMatchmakerPlayerLeftResult::~FNotifyMatchmakerPlayerLeftResult() { } void PlayFab::ServerModels::FNotifyMatchmakerPlayerLeftResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (PlayerState.notNull()) { writer->WriteIdentifierPrefix(TEXT("PlayerState")); writePlayerConnectionStateEnumJSON(PlayerState, writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FNotifyMatchmakerPlayerLeftResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; PlayerState = readPlayerConnectionStateFromValue(obj->TryGetField(TEXT("PlayerState"))); return HasSucceeded; } PlayFab::ServerModels::FPushNotificationPackage::~FPushNotificationPackage() { } void PlayFab::ServerModels::FPushNotificationPackage::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Badge")); writer->WriteValue(Badge); if (CustomData.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CustomData")); writer->WriteValue(CustomData); } if (Icon.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Icon")); writer->WriteValue(Icon); } writer->WriteIdentifierPrefix(TEXT("Message")); writer->WriteValue(Message); if (Sound.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Sound")); writer->WriteValue(Sound); } writer->WriteIdentifierPrefix(TEXT("Title")); writer->WriteValue(Title); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FPushNotificationPackage::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> BadgeValue = obj->TryGetField(TEXT("Badge")); if (BadgeValue.IsValid() && !BadgeValue->IsNull()) { int32 TmpValue; if (BadgeValue->TryGetNumber(TmpValue)) { Badge = TmpValue; } } const TSharedPtr<FJsonValue> CustomDataValue = obj->TryGetField(TEXT("CustomData")); if (CustomDataValue.IsValid() && !CustomDataValue->IsNull()) { FString TmpValue; if (CustomDataValue->TryGetString(TmpValue)) { CustomData = TmpValue; } } const TSharedPtr<FJsonValue> IconValue = obj->TryGetField(TEXT("Icon")); if (IconValue.IsValid() && !IconValue->IsNull()) { FString TmpValue; if (IconValue->TryGetString(TmpValue)) { Icon = TmpValue; } } const TSharedPtr<FJsonValue> MessageValue = obj->TryGetField(TEXT("Message")); if (MessageValue.IsValid() && !MessageValue->IsNull()) { FString TmpValue; if (MessageValue->TryGetString(TmpValue)) { Message = TmpValue; } } const TSharedPtr<FJsonValue> SoundValue = obj->TryGetField(TEXT("Sound")); if (SoundValue.IsValid() && !SoundValue->IsNull()) { FString TmpValue; if (SoundValue->TryGetString(TmpValue)) { Sound = TmpValue; } } const TSharedPtr<FJsonValue> TitleValue = obj->TryGetField(TEXT("Title")); if (TitleValue.IsValid() && !TitleValue->IsNull()) { FString TmpValue; if (TitleValue->TryGetString(TmpValue)) { Title = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FRedeemCouponRequest::~FRedeemCouponRequest() { } void PlayFab::ServerModels::FRedeemCouponRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } writer->WriteIdentifierPrefix(TEXT("CouponCode")); writer->WriteValue(CouponCode); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRedeemCouponRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> CouponCodeValue = obj->TryGetField(TEXT("CouponCode")); if (CouponCodeValue.IsValid() && !CouponCodeValue->IsNull()) { FString TmpValue; if (CouponCodeValue->TryGetString(TmpValue)) { CouponCode = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FRedeemCouponResult::~FRedeemCouponResult() { } void PlayFab::ServerModels::FRedeemCouponResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (GrantedItems.Num() != 0) { writer->WriteArrayStart(TEXT("GrantedItems")); for (const FItemInstance& item : GrantedItems) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRedeemCouponResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&GrantedItemsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("GrantedItems")); for (int32 Idx = 0; Idx < GrantedItemsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = GrantedItemsArray[Idx]; GrantedItems.Add(FItemInstance(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FRedeemMatchmakerTicketRequest::~FRedeemMatchmakerTicketRequest() { } void PlayFab::ServerModels::FRedeemMatchmakerTicketRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("LobbyId")); writer->WriteValue(LobbyId); writer->WriteIdentifierPrefix(TEXT("Ticket")); writer->WriteValue(Ticket); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRedeemMatchmakerTicketRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> LobbyIdValue = obj->TryGetField(TEXT("LobbyId")); if (LobbyIdValue.IsValid() && !LobbyIdValue->IsNull()) { FString TmpValue; if (LobbyIdValue->TryGetString(TmpValue)) { LobbyId = TmpValue; } } const TSharedPtr<FJsonValue> TicketValue = obj->TryGetField(TEXT("Ticket")); if (TicketValue.IsValid() && !TicketValue->IsNull()) { FString TmpValue; if (TicketValue->TryGetString(TmpValue)) { Ticket = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FRedeemMatchmakerTicketResult::~FRedeemMatchmakerTicketResult() { //if (UserInfo != nullptr) delete UserInfo; } void PlayFab::ServerModels::FRedeemMatchmakerTicketResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Error.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Error")); writer->WriteValue(Error); } writer->WriteIdentifierPrefix(TEXT("TicketIsValid")); writer->WriteValue(TicketIsValid); if (UserInfo.IsValid()) { writer->WriteIdentifierPrefix(TEXT("UserInfo")); UserInfo->writeJSON(writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRedeemMatchmakerTicketResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ErrorValue = obj->TryGetField(TEXT("Error")); if (ErrorValue.IsValid() && !ErrorValue->IsNull()) { FString TmpValue; if (ErrorValue->TryGetString(TmpValue)) { Error = TmpValue; } } const TSharedPtr<FJsonValue> TicketIsValidValue = obj->TryGetField(TEXT("TicketIsValid")); if (TicketIsValidValue.IsValid() && !TicketIsValidValue->IsNull()) { bool TmpValue; if (TicketIsValidValue->TryGetBool(TmpValue)) { TicketIsValid = TmpValue; } } const TSharedPtr<FJsonValue> UserInfoValue = obj->TryGetField(TEXT("UserInfo")); if (UserInfoValue.IsValid() && !UserInfoValue->IsNull()) { UserInfo = MakeShareable(new FUserAccountInfo(UserInfoValue->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FRefreshGameServerInstanceHeartbeatRequest::~FRefreshGameServerInstanceHeartbeatRequest() { } void PlayFab::ServerModels::FRefreshGameServerInstanceHeartbeatRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("LobbyId")); writer->WriteValue(LobbyId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRefreshGameServerInstanceHeartbeatRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> LobbyIdValue = obj->TryGetField(TEXT("LobbyId")); if (LobbyIdValue.IsValid() && !LobbyIdValue->IsNull()) { FString TmpValue; if (LobbyIdValue->TryGetString(TmpValue)) { LobbyId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FRefreshGameServerInstanceHeartbeatResult::~FRefreshGameServerInstanceHeartbeatResult() { } void PlayFab::ServerModels::FRefreshGameServerInstanceHeartbeatResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRefreshGameServerInstanceHeartbeatResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } void PlayFab::ServerModels::writeRegionEnumJSON(Region enumVal, JsonWriter& writer) { switch (enumVal) { case RegionUSCentral: writer->WriteValue(TEXT("USCentral")); break; case RegionUSEast: writer->WriteValue(TEXT("USEast")); break; case RegionEUWest: writer->WriteValue(TEXT("EUWest")); break; case RegionSingapore: writer->WriteValue(TEXT("Singapore")); break; case RegionJapan: writer->WriteValue(TEXT("Japan")); break; case RegionBrazil: writer->WriteValue(TEXT("Brazil")); break; case RegionAustralia: writer->WriteValue(TEXT("Australia")); break; } } ServerModels::Region PlayFab::ServerModels::readRegionFromValue(const TSharedPtr<FJsonValue>& value) { return readRegionFromValue(value.IsValid() ? value->AsString() : ""); } ServerModels::Region PlayFab::ServerModels::readRegionFromValue(const FString& value) { static TMap<FString, Region> _RegionMap; if (_RegionMap.Num() == 0) { // Auto-generate the map on the first use _RegionMap.Add(TEXT("USCentral"), RegionUSCentral); _RegionMap.Add(TEXT("USEast"), RegionUSEast); _RegionMap.Add(TEXT("EUWest"), RegionEUWest); _RegionMap.Add(TEXT("Singapore"), RegionSingapore); _RegionMap.Add(TEXT("Japan"), RegionJapan); _RegionMap.Add(TEXT("Brazil"), RegionBrazil); _RegionMap.Add(TEXT("Australia"), RegionAustralia); } if (!value.IsEmpty()) { auto output = _RegionMap.Find(value); if (output != nullptr) return *output; } return RegionUSCentral; // Basically critical fail } PlayFab::ServerModels::FRegisterGameRequest::~FRegisterGameRequest() { } void PlayFab::ServerModels::FRegisterGameRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Build")); writer->WriteValue(Build); writer->WriteIdentifierPrefix(TEXT("GameMode")); writer->WriteValue(GameMode); if (LobbyId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("LobbyId")); writer->WriteValue(LobbyId); } writer->WriteIdentifierPrefix(TEXT("Region")); writeRegionEnumJSON(pfRegion, writer); if (ServerIPV4Address.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ServerIPV4Address")); writer->WriteValue(ServerIPV4Address); } if (ServerIPV6Address.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ServerIPV6Address")); writer->WriteValue(ServerIPV6Address); } writer->WriteIdentifierPrefix(TEXT("ServerPort")); writer->WriteValue(ServerPort); if (ServerPublicDNSName.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("ServerPublicDNSName")); writer->WriteValue(ServerPublicDNSName); } if (Tags.Num() != 0) { writer->WriteObjectStart(TEXT("Tags")); for (TMap<FString, FString>::TConstIterator It(Tags); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRegisterGameRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> BuildValue = obj->TryGetField(TEXT("Build")); if (BuildValue.IsValid() && !BuildValue->IsNull()) { FString TmpValue; if (BuildValue->TryGetString(TmpValue)) { Build = TmpValue; } } const TSharedPtr<FJsonValue> GameModeValue = obj->TryGetField(TEXT("GameMode")); if (GameModeValue.IsValid() && !GameModeValue->IsNull()) { FString TmpValue; if (GameModeValue->TryGetString(TmpValue)) { GameMode = TmpValue; } } const TSharedPtr<FJsonValue> LobbyIdValue = obj->TryGetField(TEXT("LobbyId")); if (LobbyIdValue.IsValid() && !LobbyIdValue->IsNull()) { FString TmpValue; if (LobbyIdValue->TryGetString(TmpValue)) { LobbyId = TmpValue; } } pfRegion = readRegionFromValue(obj->TryGetField(TEXT("Region"))); const TSharedPtr<FJsonValue> ServerIPV4AddressValue = obj->TryGetField(TEXT("ServerIPV4Address")); if (ServerIPV4AddressValue.IsValid() && !ServerIPV4AddressValue->IsNull()) { FString TmpValue; if (ServerIPV4AddressValue->TryGetString(TmpValue)) { ServerIPV4Address = TmpValue; } } const TSharedPtr<FJsonValue> ServerIPV6AddressValue = obj->TryGetField(TEXT("ServerIPV6Address")); if (ServerIPV6AddressValue.IsValid() && !ServerIPV6AddressValue->IsNull()) { FString TmpValue; if (ServerIPV6AddressValue->TryGetString(TmpValue)) { ServerIPV6Address = TmpValue; } } const TSharedPtr<FJsonValue> ServerPortValue = obj->TryGetField(TEXT("ServerPort")); if (ServerPortValue.IsValid() && !ServerPortValue->IsNull()) { FString TmpValue; if (ServerPortValue->TryGetString(TmpValue)) { ServerPort = TmpValue; } } const TSharedPtr<FJsonValue> ServerPublicDNSNameValue = obj->TryGetField(TEXT("ServerPublicDNSName")); if (ServerPublicDNSNameValue.IsValid() && !ServerPublicDNSNameValue->IsNull()) { FString TmpValue; if (ServerPublicDNSNameValue->TryGetString(TmpValue)) { ServerPublicDNSName = TmpValue; } } const TSharedPtr<FJsonObject>* TagsObject; if (obj->TryGetObjectField(TEXT("Tags"), TagsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*TagsObject)->Values); It; ++It) { Tags.Add(It.Key(), It.Value()->AsString()); } } return HasSucceeded; } PlayFab::ServerModels::FRegisterGameResponse::~FRegisterGameResponse() { } void PlayFab::ServerModels::FRegisterGameResponse::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (LobbyId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("LobbyId")); writer->WriteValue(LobbyId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRegisterGameResponse::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> LobbyIdValue = obj->TryGetField(TEXT("LobbyId")); if (LobbyIdValue.IsValid() && !LobbyIdValue->IsNull()) { FString TmpValue; if (LobbyIdValue->TryGetString(TmpValue)) { LobbyId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FRemoveFriendRequest::~FRemoveFriendRequest() { } void PlayFab::ServerModels::FRemoveFriendRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("FriendPlayFabId")); writer->WriteValue(FriendPlayFabId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRemoveFriendRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> FriendPlayFabIdValue = obj->TryGetField(TEXT("FriendPlayFabId")); if (FriendPlayFabIdValue.IsValid() && !FriendPlayFabIdValue->IsNull()) { FString TmpValue; if (FriendPlayFabIdValue->TryGetString(TmpValue)) { FriendPlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FRemoveGenericIDRequest::~FRemoveGenericIDRequest() { } void PlayFab::ServerModels::FRemoveGenericIDRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("GenericId")); GenericId.writeJSON(writer); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRemoveGenericIDRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> GenericIdValue = obj->TryGetField(TEXT("GenericId")); if (GenericIdValue.IsValid() && !GenericIdValue->IsNull()) { GenericId = FGenericServiceId(GenericIdValue->AsObject()); } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FRemovePlayerTagRequest::~FRemovePlayerTagRequest() { } void PlayFab::ServerModels::FRemovePlayerTagRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("TagName")); writer->WriteValue(TagName); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRemovePlayerTagRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> TagNameValue = obj->TryGetField(TEXT("TagName")); if (TagNameValue.IsValid() && !TagNameValue->IsNull()) { FString TmpValue; if (TagNameValue->TryGetString(TmpValue)) { TagName = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FRemovePlayerTagResult::~FRemovePlayerTagResult() { } void PlayFab::ServerModels::FRemovePlayerTagResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRemovePlayerTagResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FRemoveSharedGroupMembersRequest::~FRemoveSharedGroupMembersRequest() { } void PlayFab::ServerModels::FRemoveSharedGroupMembersRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteArrayStart(TEXT("PlayFabIds")); for (const FString& item : PlayFabIds) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteIdentifierPrefix(TEXT("SharedGroupId")); writer->WriteValue(SharedGroupId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRemoveSharedGroupMembersRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; HasSucceeded &= obj->TryGetStringArrayField(TEXT("PlayFabIds"), PlayFabIds); const TSharedPtr<FJsonValue> SharedGroupIdValue = obj->TryGetField(TEXT("SharedGroupId")); if (SharedGroupIdValue.IsValid() && !SharedGroupIdValue->IsNull()) { FString TmpValue; if (SharedGroupIdValue->TryGetString(TmpValue)) { SharedGroupId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FRemoveSharedGroupMembersResult::~FRemoveSharedGroupMembersResult() { } void PlayFab::ServerModels::FRemoveSharedGroupMembersResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRemoveSharedGroupMembersResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FReportPlayerServerRequest::~FReportPlayerServerRequest() { } void PlayFab::ServerModels::FReportPlayerServerRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Comment.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Comment")); writer->WriteValue(Comment); } writer->WriteIdentifierPrefix(TEXT("ReporteeId")); writer->WriteValue(ReporteeId); writer->WriteIdentifierPrefix(TEXT("ReporterId")); writer->WriteValue(ReporterId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FReportPlayerServerRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CommentValue = obj->TryGetField(TEXT("Comment")); if (CommentValue.IsValid() && !CommentValue->IsNull()) { FString TmpValue; if (CommentValue->TryGetString(TmpValue)) { Comment = TmpValue; } } const TSharedPtr<FJsonValue> ReporteeIdValue = obj->TryGetField(TEXT("ReporteeId")); if (ReporteeIdValue.IsValid() && !ReporteeIdValue->IsNull()) { FString TmpValue; if (ReporteeIdValue->TryGetString(TmpValue)) { ReporteeId = TmpValue; } } const TSharedPtr<FJsonValue> ReporterIdValue = obj->TryGetField(TEXT("ReporterId")); if (ReporterIdValue.IsValid() && !ReporterIdValue->IsNull()) { FString TmpValue; if (ReporterIdValue->TryGetString(TmpValue)) { ReporterId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FReportPlayerServerResult::~FReportPlayerServerResult() { } void PlayFab::ServerModels::FReportPlayerServerResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("SubmissionsRemaining")); writer->WriteValue(SubmissionsRemaining); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FReportPlayerServerResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> SubmissionsRemainingValue = obj->TryGetField(TEXT("SubmissionsRemaining")); if (SubmissionsRemainingValue.IsValid() && !SubmissionsRemainingValue->IsNull()) { int32 TmpValue; if (SubmissionsRemainingValue->TryGetNumber(TmpValue)) { SubmissionsRemaining = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FRevokeAllBansForUserRequest::~FRevokeAllBansForUserRequest() { } void PlayFab::ServerModels::FRevokeAllBansForUserRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRevokeAllBansForUserRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FRevokeAllBansForUserResult::~FRevokeAllBansForUserResult() { } void PlayFab::ServerModels::FRevokeAllBansForUserResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (BanData.Num() != 0) { writer->WriteArrayStart(TEXT("BanData")); for (const FBanInfo& item : BanData) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRevokeAllBansForUserResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&BanDataArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("BanData")); for (int32 Idx = 0; Idx < BanDataArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = BanDataArray[Idx]; BanData.Add(FBanInfo(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FRevokeBansRequest::~FRevokeBansRequest() { } void PlayFab::ServerModels::FRevokeBansRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteArrayStart(TEXT("BanIds")); for (const FString& item : BanIds) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRevokeBansRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; HasSucceeded &= obj->TryGetStringArrayField(TEXT("BanIds"), BanIds); return HasSucceeded; } PlayFab::ServerModels::FRevokeBansResult::~FRevokeBansResult() { } void PlayFab::ServerModels::FRevokeBansResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (BanData.Num() != 0) { writer->WriteArrayStart(TEXT("BanData")); for (const FBanInfo& item : BanData) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRevokeBansResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&BanDataArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("BanData")); for (int32 Idx = 0; Idx < BanDataArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = BanDataArray[Idx]; BanData.Add(FBanInfo(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FRevokeInventoryItem::~FRevokeInventoryItem() { } void PlayFab::ServerModels::FRevokeInventoryItem::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } writer->WriteIdentifierPrefix(TEXT("ItemInstanceId")); writer->WriteValue(ItemInstanceId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRevokeInventoryItem::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> ItemInstanceIdValue = obj->TryGetField(TEXT("ItemInstanceId")); if (ItemInstanceIdValue.IsValid() && !ItemInstanceIdValue->IsNull()) { FString TmpValue; if (ItemInstanceIdValue->TryGetString(TmpValue)) { ItemInstanceId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FRevokeInventoryItemRequest::~FRevokeInventoryItemRequest() { } void PlayFab::ServerModels::FRevokeInventoryItemRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } writer->WriteIdentifierPrefix(TEXT("ItemInstanceId")); writer->WriteValue(ItemInstanceId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRevokeInventoryItemRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> ItemInstanceIdValue = obj->TryGetField(TEXT("ItemInstanceId")); if (ItemInstanceIdValue.IsValid() && !ItemInstanceIdValue->IsNull()) { FString TmpValue; if (ItemInstanceIdValue->TryGetString(TmpValue)) { ItemInstanceId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FRevokeInventoryItemsRequest::~FRevokeInventoryItemsRequest() { } void PlayFab::ServerModels::FRevokeInventoryItemsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteArrayStart(TEXT("Items")); for (const FRevokeInventoryItem& item : Items) item.writeJSON(writer); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRevokeInventoryItemsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&ItemsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Items")); for (int32 Idx = 0; Idx < ItemsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = ItemsArray[Idx]; Items.Add(FRevokeInventoryItem(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FRevokeItemError::~FRevokeItemError() { //if (Item != nullptr) delete Item; } void PlayFab::ServerModels::FRevokeItemError::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Error.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Error")); writer->WriteValue(Error); } if (Item.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Item")); Item->writeJSON(writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRevokeItemError::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ErrorValue = obj->TryGetField(TEXT("Error")); if (ErrorValue.IsValid() && !ErrorValue->IsNull()) { FString TmpValue; if (ErrorValue->TryGetString(TmpValue)) { Error = TmpValue; } } const TSharedPtr<FJsonValue> ItemValue = obj->TryGetField(TEXT("Item")); if (ItemValue.IsValid() && !ItemValue->IsNull()) { Item = MakeShareable(new FRevokeInventoryItem(ItemValue->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FRevokeInventoryItemsResult::~FRevokeInventoryItemsResult() { } void PlayFab::ServerModels::FRevokeInventoryItemsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Errors.Num() != 0) { writer->WriteArrayStart(TEXT("Errors")); for (const FRevokeItemError& item : Errors) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRevokeInventoryItemsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&ErrorsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Errors")); for (int32 Idx = 0; Idx < ErrorsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = ErrorsArray[Idx]; Errors.Add(FRevokeItemError(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FRevokeInventoryResult::~FRevokeInventoryResult() { } void PlayFab::ServerModels::FRevokeInventoryResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FRevokeInventoryResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FSavePushNotificationTemplateRequest::~FSavePushNotificationTemplateRequest() { } void PlayFab::ServerModels::FSavePushNotificationTemplateRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (AndroidPayload.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("AndroidPayload")); writer->WriteValue(AndroidPayload); } if (Id.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Id")); writer->WriteValue(Id); } if (IOSPayload.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("IOSPayload")); writer->WriteValue(IOSPayload); } if (LocalizedPushNotificationTemplates.Num() != 0) { writer->WriteObjectStart(TEXT("LocalizedPushNotificationTemplates")); for (TMap<FString, FLocalizedPushNotificationProperties>::TConstIterator It(LocalizedPushNotificationTemplates); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteIdentifierPrefix(TEXT("Name")); writer->WriteValue(Name); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSavePushNotificationTemplateRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AndroidPayloadValue = obj->TryGetField(TEXT("AndroidPayload")); if (AndroidPayloadValue.IsValid() && !AndroidPayloadValue->IsNull()) { FString TmpValue; if (AndroidPayloadValue->TryGetString(TmpValue)) { AndroidPayload = TmpValue; } } const TSharedPtr<FJsonValue> IdValue = obj->TryGetField(TEXT("Id")); if (IdValue.IsValid() && !IdValue->IsNull()) { FString TmpValue; if (IdValue->TryGetString(TmpValue)) { Id = TmpValue; } } const TSharedPtr<FJsonValue> IOSPayloadValue = obj->TryGetField(TEXT("IOSPayload")); if (IOSPayloadValue.IsValid() && !IOSPayloadValue->IsNull()) { FString TmpValue; if (IOSPayloadValue->TryGetString(TmpValue)) { IOSPayload = TmpValue; } } const TSharedPtr<FJsonObject>* LocalizedPushNotificationTemplatesObject; if (obj->TryGetObjectField(TEXT("LocalizedPushNotificationTemplates"), LocalizedPushNotificationTemplatesObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*LocalizedPushNotificationTemplatesObject)->Values); It; ++It) { LocalizedPushNotificationTemplates.Add(It.Key(), FLocalizedPushNotificationProperties(It.Value()->AsObject())); } } const TSharedPtr<FJsonValue> NameValue = obj->TryGetField(TEXT("Name")); if (NameValue.IsValid() && !NameValue->IsNull()) { FString TmpValue; if (NameValue->TryGetString(TmpValue)) { Name = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FSavePushNotificationTemplateResult::~FSavePushNotificationTemplateResult() { } void PlayFab::ServerModels::FSavePushNotificationTemplateResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (PushNotificationTemplateId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PushNotificationTemplateId")); writer->WriteValue(PushNotificationTemplateId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSavePushNotificationTemplateResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PushNotificationTemplateIdValue = obj->TryGetField(TEXT("PushNotificationTemplateId")); if (PushNotificationTemplateIdValue.IsValid() && !PushNotificationTemplateIdValue->IsNull()) { FString TmpValue; if (PushNotificationTemplateIdValue->TryGetString(TmpValue)) { PushNotificationTemplateId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FSendCustomAccountRecoveryEmailRequest::~FSendCustomAccountRecoveryEmailRequest() { } void PlayFab::ServerModels::FSendCustomAccountRecoveryEmailRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Email.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Email")); writer->WriteValue(Email); } writer->WriteIdentifierPrefix(TEXT("EmailTemplateId")); writer->WriteValue(EmailTemplateId); if (Username.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Username")); writer->WriteValue(Username); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSendCustomAccountRecoveryEmailRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> EmailValue = obj->TryGetField(TEXT("Email")); if (EmailValue.IsValid() && !EmailValue->IsNull()) { FString TmpValue; if (EmailValue->TryGetString(TmpValue)) { Email = TmpValue; } } const TSharedPtr<FJsonValue> EmailTemplateIdValue = obj->TryGetField(TEXT("EmailTemplateId")); if (EmailTemplateIdValue.IsValid() && !EmailTemplateIdValue->IsNull()) { FString TmpValue; if (EmailTemplateIdValue->TryGetString(TmpValue)) { EmailTemplateId = TmpValue; } } const TSharedPtr<FJsonValue> UsernameValue = obj->TryGetField(TEXT("Username")); if (UsernameValue.IsValid() && !UsernameValue->IsNull()) { FString TmpValue; if (UsernameValue->TryGetString(TmpValue)) { Username = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FSendCustomAccountRecoveryEmailResult::~FSendCustomAccountRecoveryEmailResult() { } void PlayFab::ServerModels::FSendCustomAccountRecoveryEmailResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSendCustomAccountRecoveryEmailResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FSendEmailFromTemplateRequest::~FSendEmailFromTemplateRequest() { } void PlayFab::ServerModels::FSendEmailFromTemplateRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("EmailTemplateId")); writer->WriteValue(EmailTemplateId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSendEmailFromTemplateRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> EmailTemplateIdValue = obj->TryGetField(TEXT("EmailTemplateId")); if (EmailTemplateIdValue.IsValid() && !EmailTemplateIdValue->IsNull()) { FString TmpValue; if (EmailTemplateIdValue->TryGetString(TmpValue)) { EmailTemplateId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FSendEmailFromTemplateResult::~FSendEmailFromTemplateResult() { } void PlayFab::ServerModels::FSendEmailFromTemplateResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSendEmailFromTemplateResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FSendPushNotificationFromTemplateRequest::~FSendPushNotificationFromTemplateRequest() { } void PlayFab::ServerModels::FSendPushNotificationFromTemplateRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PushNotificationTemplateId")); writer->WriteValue(PushNotificationTemplateId); writer->WriteIdentifierPrefix(TEXT("Recipient")); writer->WriteValue(Recipient); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSendPushNotificationFromTemplateRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PushNotificationTemplateIdValue = obj->TryGetField(TEXT("PushNotificationTemplateId")); if (PushNotificationTemplateIdValue.IsValid() && !PushNotificationTemplateIdValue->IsNull()) { FString TmpValue; if (PushNotificationTemplateIdValue->TryGetString(TmpValue)) { PushNotificationTemplateId = TmpValue; } } const TSharedPtr<FJsonValue> RecipientValue = obj->TryGetField(TEXT("Recipient")); if (RecipientValue.IsValid() && !RecipientValue->IsNull()) { FString TmpValue; if (RecipientValue->TryGetString(TmpValue)) { Recipient = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FSendPushNotificationRequest::~FSendPushNotificationRequest() { //if (Package != nullptr) delete Package; } void PlayFab::ServerModels::FSendPushNotificationRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (AdvancedPlatformDelivery.Num() != 0) { writer->WriteArrayStart(TEXT("AdvancedPlatformDelivery")); for (const FAdvancedPushPlatformMsg& item : AdvancedPlatformDelivery) item.writeJSON(writer); writer->WriteArrayEnd(); } if (Message.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Message")); writer->WriteValue(Message); } if (Package.IsValid()) { writer->WriteIdentifierPrefix(TEXT("Package")); Package->writeJSON(writer); } writer->WriteIdentifierPrefix(TEXT("Recipient")); writer->WriteValue(Recipient); if (Subject.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Subject")); writer->WriteValue(Subject); } if (TargetPlatforms.Num() != 0) { writer->WriteArrayStart(TEXT("TargetPlatforms")); for (const PushNotificationPlatform& item : TargetPlatforms) writePushNotificationPlatformEnumJSON(item, writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSendPushNotificationRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&AdvancedPlatformDeliveryArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("AdvancedPlatformDelivery")); for (int32 Idx = 0; Idx < AdvancedPlatformDeliveryArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = AdvancedPlatformDeliveryArray[Idx]; AdvancedPlatformDelivery.Add(FAdvancedPushPlatformMsg(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> MessageValue = obj->TryGetField(TEXT("Message")); if (MessageValue.IsValid() && !MessageValue->IsNull()) { FString TmpValue; if (MessageValue->TryGetString(TmpValue)) { Message = TmpValue; } } const TSharedPtr<FJsonValue> PackageValue = obj->TryGetField(TEXT("Package")); if (PackageValue.IsValid() && !PackageValue->IsNull()) { Package = MakeShareable(new FPushNotificationPackage(PackageValue->AsObject())); } const TSharedPtr<FJsonValue> RecipientValue = obj->TryGetField(TEXT("Recipient")); if (RecipientValue.IsValid() && !RecipientValue->IsNull()) { FString TmpValue; if (RecipientValue->TryGetString(TmpValue)) { Recipient = TmpValue; } } const TSharedPtr<FJsonValue> SubjectValue = obj->TryGetField(TEXT("Subject")); if (SubjectValue.IsValid() && !SubjectValue->IsNull()) { FString TmpValue; if (SubjectValue->TryGetString(TmpValue)) { Subject = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&TargetPlatformsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("TargetPlatforms")); for (int32 Idx = 0; Idx < TargetPlatformsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = TargetPlatformsArray[Idx]; TargetPlatforms.Add(readPushNotificationPlatformFromValue(CurrentItem)); } return HasSucceeded; } PlayFab::ServerModels::FSendPushNotificationResult::~FSendPushNotificationResult() { } void PlayFab::ServerModels::FSendPushNotificationResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSendPushNotificationResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FUserSettings::~FUserSettings() { } void PlayFab::ServerModels::FUserSettings::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("GatherDeviceInfo")); writer->WriteValue(GatherDeviceInfo); writer->WriteIdentifierPrefix(TEXT("GatherFocusInfo")); writer->WriteValue(GatherFocusInfo); writer->WriteIdentifierPrefix(TEXT("NeedsAttribution")); writer->WriteValue(NeedsAttribution); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUserSettings::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> GatherDeviceInfoValue = obj->TryGetField(TEXT("GatherDeviceInfo")); if (GatherDeviceInfoValue.IsValid() && !GatherDeviceInfoValue->IsNull()) { bool TmpValue; if (GatherDeviceInfoValue->TryGetBool(TmpValue)) { GatherDeviceInfo = TmpValue; } } const TSharedPtr<FJsonValue> GatherFocusInfoValue = obj->TryGetField(TEXT("GatherFocusInfo")); if (GatherFocusInfoValue.IsValid() && !GatherFocusInfoValue->IsNull()) { bool TmpValue; if (GatherFocusInfoValue->TryGetBool(TmpValue)) { GatherFocusInfo = TmpValue; } } const TSharedPtr<FJsonValue> NeedsAttributionValue = obj->TryGetField(TEXT("NeedsAttribution")); if (NeedsAttributionValue.IsValid() && !NeedsAttributionValue->IsNull()) { bool TmpValue; if (NeedsAttributionValue->TryGetBool(TmpValue)) { NeedsAttribution = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FServerLoginResult::~FServerLoginResult() { //if (EntityToken != nullptr) delete EntityToken; //if (InfoResultPayload != nullptr) delete InfoResultPayload; //if (SettingsForUser != nullptr) delete SettingsForUser; } void PlayFab::ServerModels::FServerLoginResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (EntityToken.IsValid()) { writer->WriteIdentifierPrefix(TEXT("EntityToken")); EntityToken->writeJSON(writer); } if (InfoResultPayload.IsValid()) { writer->WriteIdentifierPrefix(TEXT("InfoResultPayload")); InfoResultPayload->writeJSON(writer); } if (LastLoginTime.notNull()) { writer->WriteIdentifierPrefix(TEXT("LastLoginTime")); writeDatetime(LastLoginTime, writer); } writer->WriteIdentifierPrefix(TEXT("NewlyCreated")); writer->WriteValue(NewlyCreated); if (PlayFabId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); } if (SessionTicket.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("SessionTicket")); writer->WriteValue(SessionTicket); } if (SettingsForUser.IsValid()) { writer->WriteIdentifierPrefix(TEXT("SettingsForUser")); SettingsForUser->writeJSON(writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FServerLoginResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> EntityTokenValue = obj->TryGetField(TEXT("EntityToken")); if (EntityTokenValue.IsValid() && !EntityTokenValue->IsNull()) { EntityToken = MakeShareable(new FEntityTokenResponse(EntityTokenValue->AsObject())); } const TSharedPtr<FJsonValue> InfoResultPayloadValue = obj->TryGetField(TEXT("InfoResultPayload")); if (InfoResultPayloadValue.IsValid() && !InfoResultPayloadValue->IsNull()) { InfoResultPayload = MakeShareable(new FGetPlayerCombinedInfoResultPayload(InfoResultPayloadValue->AsObject())); } const TSharedPtr<FJsonValue> LastLoginTimeValue = obj->TryGetField(TEXT("LastLoginTime")); if (LastLoginTimeValue.IsValid()) LastLoginTime = readDatetime(LastLoginTimeValue); const TSharedPtr<FJsonValue> NewlyCreatedValue = obj->TryGetField(TEXT("NewlyCreated")); if (NewlyCreatedValue.IsValid() && !NewlyCreatedValue->IsNull()) { bool TmpValue; if (NewlyCreatedValue->TryGetBool(TmpValue)) { NewlyCreated = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> SessionTicketValue = obj->TryGetField(TEXT("SessionTicket")); if (SessionTicketValue.IsValid() && !SessionTicketValue->IsNull()) { FString TmpValue; if (SessionTicketValue->TryGetString(TmpValue)) { SessionTicket = TmpValue; } } const TSharedPtr<FJsonValue> SettingsForUserValue = obj->TryGetField(TEXT("SettingsForUser")); if (SettingsForUserValue.IsValid() && !SettingsForUserValue->IsNull()) { SettingsForUser = MakeShareable(new FUserSettings(SettingsForUserValue->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FSetFriendTagsRequest::~FSetFriendTagsRequest() { } void PlayFab::ServerModels::FSetFriendTagsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("FriendPlayFabId")); writer->WriteValue(FriendPlayFabId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteArrayStart(TEXT("Tags")); for (const FString& item : Tags) writer->WriteValue(item); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSetFriendTagsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> FriendPlayFabIdValue = obj->TryGetField(TEXT("FriendPlayFabId")); if (FriendPlayFabIdValue.IsValid() && !FriendPlayFabIdValue->IsNull()) { FString TmpValue; if (FriendPlayFabIdValue->TryGetString(TmpValue)) { FriendPlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } HasSucceeded &= obj->TryGetStringArrayField(TEXT("Tags"), Tags); return HasSucceeded; } PlayFab::ServerModels::FSetGameServerInstanceDataRequest::~FSetGameServerInstanceDataRequest() { } void PlayFab::ServerModels::FSetGameServerInstanceDataRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("GameServerData")); writer->WriteValue(GameServerData); writer->WriteIdentifierPrefix(TEXT("LobbyId")); writer->WriteValue(LobbyId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSetGameServerInstanceDataRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> GameServerDataValue = obj->TryGetField(TEXT("GameServerData")); if (GameServerDataValue.IsValid() && !GameServerDataValue->IsNull()) { FString TmpValue; if (GameServerDataValue->TryGetString(TmpValue)) { GameServerData = TmpValue; } } const TSharedPtr<FJsonValue> LobbyIdValue = obj->TryGetField(TEXT("LobbyId")); if (LobbyIdValue.IsValid() && !LobbyIdValue->IsNull()) { FString TmpValue; if (LobbyIdValue->TryGetString(TmpValue)) { LobbyId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FSetGameServerInstanceDataResult::~FSetGameServerInstanceDataResult() { } void PlayFab::ServerModels::FSetGameServerInstanceDataResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSetGameServerInstanceDataResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FSetGameServerInstanceStateRequest::~FSetGameServerInstanceStateRequest() { } void PlayFab::ServerModels::FSetGameServerInstanceStateRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("LobbyId")); writer->WriteValue(LobbyId); writer->WriteIdentifierPrefix(TEXT("State")); writeGameInstanceStateEnumJSON(State, writer); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSetGameServerInstanceStateRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> LobbyIdValue = obj->TryGetField(TEXT("LobbyId")); if (LobbyIdValue.IsValid() && !LobbyIdValue->IsNull()) { FString TmpValue; if (LobbyIdValue->TryGetString(TmpValue)) { LobbyId = TmpValue; } } State = readGameInstanceStateFromValue(obj->TryGetField(TEXT("State"))); return HasSucceeded; } PlayFab::ServerModels::FSetGameServerInstanceStateResult::~FSetGameServerInstanceStateResult() { } void PlayFab::ServerModels::FSetGameServerInstanceStateResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSetGameServerInstanceStateResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FSetGameServerInstanceTagsRequest::~FSetGameServerInstanceTagsRequest() { } void PlayFab::ServerModels::FSetGameServerInstanceTagsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("LobbyId")); writer->WriteValue(LobbyId); writer->WriteObjectStart(TEXT("Tags")); for (TMap<FString, FString>::TConstIterator It(Tags); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSetGameServerInstanceTagsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> LobbyIdValue = obj->TryGetField(TEXT("LobbyId")); if (LobbyIdValue.IsValid() && !LobbyIdValue->IsNull()) { FString TmpValue; if (LobbyIdValue->TryGetString(TmpValue)) { LobbyId = TmpValue; } } const TSharedPtr<FJsonObject>* TagsObject; if (obj->TryGetObjectField(TEXT("Tags"), TagsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*TagsObject)->Values); It; ++It) { Tags.Add(It.Key(), It.Value()->AsString()); } } return HasSucceeded; } PlayFab::ServerModels::FSetGameServerInstanceTagsResult::~FSetGameServerInstanceTagsResult() { } void PlayFab::ServerModels::FSetGameServerInstanceTagsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSetGameServerInstanceTagsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FSetPlayerSecretRequest::~FSetPlayerSecretRequest() { } void PlayFab::ServerModels::FSetPlayerSecretRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (PlayerSecret.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("PlayerSecret")); writer->WriteValue(PlayerSecret); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSetPlayerSecretRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayerSecretValue = obj->TryGetField(TEXT("PlayerSecret")); if (PlayerSecretValue.IsValid() && !PlayerSecretValue->IsNull()) { FString TmpValue; if (PlayerSecretValue->TryGetString(TmpValue)) { PlayerSecret = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FSetPlayerSecretResult::~FSetPlayerSecretResult() { } void PlayFab::ServerModels::FSetPlayerSecretResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSetPlayerSecretResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FSetPublisherDataRequest::~FSetPublisherDataRequest() { } void PlayFab::ServerModels::FSetPublisherDataRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Key")); writer->WriteValue(Key); if (Value.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Value")); writer->WriteValue(Value); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSetPublisherDataRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> KeyValue = obj->TryGetField(TEXT("Key")); if (KeyValue.IsValid() && !KeyValue->IsNull()) { FString TmpValue; if (KeyValue->TryGetString(TmpValue)) { Key = TmpValue; } } const TSharedPtr<FJsonValue> ValueValue = obj->TryGetField(TEXT("Value")); if (ValueValue.IsValid() && !ValueValue->IsNull()) { FString TmpValue; if (ValueValue->TryGetString(TmpValue)) { Value = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FSetPublisherDataResult::~FSetPublisherDataResult() { } void PlayFab::ServerModels::FSetPublisherDataResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSetPublisherDataResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FSetTitleDataRequest::~FSetTitleDataRequest() { } void PlayFab::ServerModels::FSetTitleDataRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Key")); writer->WriteValue(Key); if (Value.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Value")); writer->WriteValue(Value); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSetTitleDataRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> KeyValue = obj->TryGetField(TEXT("Key")); if (KeyValue.IsValid() && !KeyValue->IsNull()) { FString TmpValue; if (KeyValue->TryGetString(TmpValue)) { Key = TmpValue; } } const TSharedPtr<FJsonValue> ValueValue = obj->TryGetField(TEXT("Value")); if (ValueValue.IsValid() && !ValueValue->IsNull()) { FString TmpValue; if (ValueValue->TryGetString(TmpValue)) { Value = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FSetTitleDataResult::~FSetTitleDataResult() { } void PlayFab::ServerModels::FSetTitleDataResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSetTitleDataResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FStatisticUpdate::~FStatisticUpdate() { } void PlayFab::ServerModels::FStatisticUpdate::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("StatisticName")); writer->WriteValue(StatisticName); writer->WriteIdentifierPrefix(TEXT("Value")); writer->WriteValue(Value); if (Version.notNull()) { writer->WriteIdentifierPrefix(TEXT("Version")); writer->WriteValue(static_cast<int64>(Version)); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FStatisticUpdate::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> StatisticNameValue = obj->TryGetField(TEXT("StatisticName")); if (StatisticNameValue.IsValid() && !StatisticNameValue->IsNull()) { FString TmpValue; if (StatisticNameValue->TryGetString(TmpValue)) { StatisticName = TmpValue; } } const TSharedPtr<FJsonValue> ValueValue = obj->TryGetField(TEXT("Value")); if (ValueValue.IsValid() && !ValueValue->IsNull()) { int32 TmpValue; if (ValueValue->TryGetNumber(TmpValue)) { Value = TmpValue; } } const TSharedPtr<FJsonValue> VersionValue = obj->TryGetField(TEXT("Version")); if (VersionValue.IsValid() && !VersionValue->IsNull()) { uint32 TmpValue; if (VersionValue->TryGetNumber(TmpValue)) { Version = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FSubtractCharacterVirtualCurrencyRequest::~FSubtractCharacterVirtualCurrencyRequest() { } void PlayFab::ServerModels::FSubtractCharacterVirtualCurrencyRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Amount")); writer->WriteValue(Amount); writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("VirtualCurrency")); writer->WriteValue(VirtualCurrency); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSubtractCharacterVirtualCurrencyRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AmountValue = obj->TryGetField(TEXT("Amount")); if (AmountValue.IsValid() && !AmountValue->IsNull()) { int32 TmpValue; if (AmountValue->TryGetNumber(TmpValue)) { Amount = TmpValue; } } const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> VirtualCurrencyValue = obj->TryGetField(TEXT("VirtualCurrency")); if (VirtualCurrencyValue.IsValid() && !VirtualCurrencyValue->IsNull()) { FString TmpValue; if (VirtualCurrencyValue->TryGetString(TmpValue)) { VirtualCurrency = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FSubtractUserVirtualCurrencyRequest::~FSubtractUserVirtualCurrencyRequest() { } void PlayFab::ServerModels::FSubtractUserVirtualCurrencyRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("Amount")); writer->WriteValue(Amount); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("VirtualCurrency")); writer->WriteValue(VirtualCurrency); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FSubtractUserVirtualCurrencyRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> AmountValue = obj->TryGetField(TEXT("Amount")); if (AmountValue.IsValid() && !AmountValue->IsNull()) { int32 TmpValue; if (AmountValue->TryGetNumber(TmpValue)) { Amount = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> VirtualCurrencyValue = obj->TryGetField(TEXT("VirtualCurrency")); if (VirtualCurrencyValue.IsValid() && !VirtualCurrencyValue->IsNull()) { FString TmpValue; if (VirtualCurrencyValue->TryGetString(TmpValue)) { VirtualCurrency = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUnlinkServerCustomIdRequest::~FUnlinkServerCustomIdRequest() { } void PlayFab::ServerModels::FUnlinkServerCustomIdRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("ServerCustomId")); writer->WriteValue(ServerCustomId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUnlinkServerCustomIdRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> ServerCustomIdValue = obj->TryGetField(TEXT("ServerCustomId")); if (ServerCustomIdValue.IsValid() && !ServerCustomIdValue->IsNull()) { FString TmpValue; if (ServerCustomIdValue->TryGetString(TmpValue)) { ServerCustomId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUnlinkServerCustomIdResult::~FUnlinkServerCustomIdResult() { } void PlayFab::ServerModels::FUnlinkServerCustomIdResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUnlinkServerCustomIdResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FUnlinkXboxAccountRequest::~FUnlinkXboxAccountRequest() { } void PlayFab::ServerModels::FUnlinkXboxAccountRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteIdentifierPrefix(TEXT("XboxToken")); writer->WriteValue(XboxToken); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUnlinkXboxAccountRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> XboxTokenValue = obj->TryGetField(TEXT("XboxToken")); if (XboxTokenValue.IsValid() && !XboxTokenValue->IsNull()) { FString TmpValue; if (XboxTokenValue->TryGetString(TmpValue)) { XboxToken = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUnlinkXboxAccountResult::~FUnlinkXboxAccountResult() { } void PlayFab::ServerModels::FUnlinkXboxAccountResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUnlinkXboxAccountResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FUnlockContainerInstanceRequest::~FUnlockContainerInstanceRequest() { } void PlayFab::ServerModels::FUnlockContainerInstanceRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } writer->WriteIdentifierPrefix(TEXT("ContainerItemInstanceId")); writer->WriteValue(ContainerItemInstanceId); if (KeyItemInstanceId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("KeyItemInstanceId")); writer->WriteValue(KeyItemInstanceId); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUnlockContainerInstanceRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> ContainerItemInstanceIdValue = obj->TryGetField(TEXT("ContainerItemInstanceId")); if (ContainerItemInstanceIdValue.IsValid() && !ContainerItemInstanceIdValue->IsNull()) { FString TmpValue; if (ContainerItemInstanceIdValue->TryGetString(TmpValue)) { ContainerItemInstanceId = TmpValue; } } const TSharedPtr<FJsonValue> KeyItemInstanceIdValue = obj->TryGetField(TEXT("KeyItemInstanceId")); if (KeyItemInstanceIdValue.IsValid() && !KeyItemInstanceIdValue->IsNull()) { FString TmpValue; if (KeyItemInstanceIdValue->TryGetString(TmpValue)) { KeyItemInstanceId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUnlockContainerItemRequest::~FUnlockContainerItemRequest() { } void PlayFab::ServerModels::FUnlockContainerItemRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CatalogVersion.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CatalogVersion")); writer->WriteValue(CatalogVersion); } if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } writer->WriteIdentifierPrefix(TEXT("ContainerItemId")); writer->WriteValue(ContainerItemId); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUnlockContainerItemRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CatalogVersionValue = obj->TryGetField(TEXT("CatalogVersion")); if (CatalogVersionValue.IsValid() && !CatalogVersionValue->IsNull()) { FString TmpValue; if (CatalogVersionValue->TryGetString(TmpValue)) { CatalogVersion = TmpValue; } } const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> ContainerItemIdValue = obj->TryGetField(TEXT("ContainerItemId")); if (ContainerItemIdValue.IsValid() && !ContainerItemIdValue->IsNull()) { FString TmpValue; if (ContainerItemIdValue->TryGetString(TmpValue)) { ContainerItemId = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUnlockContainerItemResult::~FUnlockContainerItemResult() { } void PlayFab::ServerModels::FUnlockContainerItemResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (GrantedItems.Num() != 0) { writer->WriteArrayStart(TEXT("GrantedItems")); for (const FItemInstance& item : GrantedItems) item.writeJSON(writer); writer->WriteArrayEnd(); } if (UnlockedItemInstanceId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("UnlockedItemInstanceId")); writer->WriteValue(UnlockedItemInstanceId); } if (UnlockedWithItemInstanceId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("UnlockedWithItemInstanceId")); writer->WriteValue(UnlockedWithItemInstanceId); } if (VirtualCurrency.Num() != 0) { writer->WriteObjectStart(TEXT("VirtualCurrency")); for (TMap<FString, uint32>::TConstIterator It(VirtualCurrency); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue(static_cast<int64>((*It).Value)); } writer->WriteObjectEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUnlockContainerItemResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&GrantedItemsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("GrantedItems")); for (int32 Idx = 0; Idx < GrantedItemsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = GrantedItemsArray[Idx]; GrantedItems.Add(FItemInstance(CurrentItem->AsObject())); } const TSharedPtr<FJsonValue> UnlockedItemInstanceIdValue = obj->TryGetField(TEXT("UnlockedItemInstanceId")); if (UnlockedItemInstanceIdValue.IsValid() && !UnlockedItemInstanceIdValue->IsNull()) { FString TmpValue; if (UnlockedItemInstanceIdValue->TryGetString(TmpValue)) { UnlockedItemInstanceId = TmpValue; } } const TSharedPtr<FJsonValue> UnlockedWithItemInstanceIdValue = obj->TryGetField(TEXT("UnlockedWithItemInstanceId")); if (UnlockedWithItemInstanceIdValue.IsValid() && !UnlockedWithItemInstanceIdValue->IsNull()) { FString TmpValue; if (UnlockedWithItemInstanceIdValue->TryGetString(TmpValue)) { UnlockedWithItemInstanceId = TmpValue; } } const TSharedPtr<FJsonObject>* VirtualCurrencyObject; if (obj->TryGetObjectField(TEXT("VirtualCurrency"), VirtualCurrencyObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*VirtualCurrencyObject)->Values); It; ++It) { uint32 TmpValue; It.Value()->TryGetNumber(TmpValue); VirtualCurrency.Add(It.Key(), TmpValue); } } return HasSucceeded; } PlayFab::ServerModels::FUpdateAvatarUrlRequest::~FUpdateAvatarUrlRequest() { } void PlayFab::ServerModels::FUpdateAvatarUrlRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("ImageUrl")); writer->WriteValue(ImageUrl); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdateAvatarUrlRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ImageUrlValue = obj->TryGetField(TEXT("ImageUrl")); if (ImageUrlValue.IsValid() && !ImageUrlValue->IsNull()) { FString TmpValue; if (ImageUrlValue->TryGetString(TmpValue)) { ImageUrl = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUpdateBanRequest::~FUpdateBanRequest() { } void PlayFab::ServerModels::FUpdateBanRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Active.notNull()) { writer->WriteIdentifierPrefix(TEXT("Active")); writer->WriteValue(Active); } writer->WriteIdentifierPrefix(TEXT("BanId")); writer->WriteValue(BanId); if (Expires.notNull()) { writer->WriteIdentifierPrefix(TEXT("Expires")); writeDatetime(Expires, writer); } if (IPAddress.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("IPAddress")); writer->WriteValue(IPAddress); } if (MACAddress.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("MACAddress")); writer->WriteValue(MACAddress); } if (Permanent.notNull()) { writer->WriteIdentifierPrefix(TEXT("Permanent")); writer->WriteValue(Permanent); } if (Reason.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("Reason")); writer->WriteValue(Reason); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdateBanRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ActiveValue = obj->TryGetField(TEXT("Active")); if (ActiveValue.IsValid() && !ActiveValue->IsNull()) { bool TmpValue; if (ActiveValue->TryGetBool(TmpValue)) { Active = TmpValue; } } const TSharedPtr<FJsonValue> BanIdValue = obj->TryGetField(TEXT("BanId")); if (BanIdValue.IsValid() && !BanIdValue->IsNull()) { FString TmpValue; if (BanIdValue->TryGetString(TmpValue)) { BanId = TmpValue; } } const TSharedPtr<FJsonValue> ExpiresValue = obj->TryGetField(TEXT("Expires")); if (ExpiresValue.IsValid()) Expires = readDatetime(ExpiresValue); const TSharedPtr<FJsonValue> IPAddressValue = obj->TryGetField(TEXT("IPAddress")); if (IPAddressValue.IsValid() && !IPAddressValue->IsNull()) { FString TmpValue; if (IPAddressValue->TryGetString(TmpValue)) { IPAddress = TmpValue; } } const TSharedPtr<FJsonValue> MACAddressValue = obj->TryGetField(TEXT("MACAddress")); if (MACAddressValue.IsValid() && !MACAddressValue->IsNull()) { FString TmpValue; if (MACAddressValue->TryGetString(TmpValue)) { MACAddress = TmpValue; } } const TSharedPtr<FJsonValue> PermanentValue = obj->TryGetField(TEXT("Permanent")); if (PermanentValue.IsValid() && !PermanentValue->IsNull()) { bool TmpValue; if (PermanentValue->TryGetBool(TmpValue)) { Permanent = TmpValue; } } const TSharedPtr<FJsonValue> ReasonValue = obj->TryGetField(TEXT("Reason")); if (ReasonValue.IsValid() && !ReasonValue->IsNull()) { FString TmpValue; if (ReasonValue->TryGetString(TmpValue)) { Reason = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUpdateBansRequest::~FUpdateBansRequest() { } void PlayFab::ServerModels::FUpdateBansRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteArrayStart(TEXT("Bans")); for (const FUpdateBanRequest& item : Bans) item.writeJSON(writer); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdateBansRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&BansArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Bans")); for (int32 Idx = 0; Idx < BansArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = BansArray[Idx]; Bans.Add(FUpdateBanRequest(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FUpdateBansResult::~FUpdateBansResult() { } void PlayFab::ServerModels::FUpdateBansResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (BanData.Num() != 0) { writer->WriteArrayStart(TEXT("BanData")); for (const FBanInfo& item : BanData) item.writeJSON(writer); writer->WriteArrayEnd(); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdateBansResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TArray<TSharedPtr<FJsonValue>>&BanDataArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("BanData")); for (int32 Idx = 0; Idx < BanDataArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = BanDataArray[Idx]; BanData.Add(FBanInfo(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FUpdateCharacterDataRequest::~FUpdateCharacterDataRequest() { } void PlayFab::ServerModels::FUpdateCharacterDataRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); if (Data.Num() != 0) { writer->WriteObjectStart(TEXT("Data")); for (TMap<FString, FString>::TConstIterator It(Data); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (KeysToRemove.Num() != 0) { writer->WriteArrayStart(TEXT("KeysToRemove")); for (const FString& item : KeysToRemove) writer->WriteValue(item); writer->WriteArrayEnd(); } if (Permission.notNull()) { writer->WriteIdentifierPrefix(TEXT("Permission")); writeUserDataPermissionEnumJSON(Permission, writer); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdateCharacterDataRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonObject>* DataObject; if (obj->TryGetObjectField(TEXT("Data"), DataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*DataObject)->Values); It; ++It) { Data.Add(It.Key(), It.Value()->AsString()); } } obj->TryGetStringArrayField(TEXT("KeysToRemove"), KeysToRemove); Permission = readUserDataPermissionFromValue(obj->TryGetField(TEXT("Permission"))); const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUpdateCharacterDataResult::~FUpdateCharacterDataResult() { } void PlayFab::ServerModels::FUpdateCharacterDataResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("DataVersion")); writer->WriteValue(static_cast<int64>(DataVersion)); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdateCharacterDataResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> DataVersionValue = obj->TryGetField(TEXT("DataVersion")); if (DataVersionValue.IsValid() && !DataVersionValue->IsNull()) { uint32 TmpValue; if (DataVersionValue->TryGetNumber(TmpValue)) { DataVersion = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUpdateCharacterStatisticsRequest::~FUpdateCharacterStatisticsRequest() { } void PlayFab::ServerModels::FUpdateCharacterStatisticsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); if (CharacterStatistics.Num() != 0) { writer->WriteObjectStart(TEXT("CharacterStatistics")); for (TMap<FString, int32>::TConstIterator It(CharacterStatistics); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdateCharacterStatisticsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonObject>* CharacterStatisticsObject; if (obj->TryGetObjectField(TEXT("CharacterStatistics"), CharacterStatisticsObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*CharacterStatisticsObject)->Values); It; ++It) { int32 TmpValue; It.Value()->TryGetNumber(TmpValue); CharacterStatistics.Add(It.Key(), TmpValue); } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUpdateCharacterStatisticsResult::~FUpdateCharacterStatisticsResult() { } void PlayFab::ServerModels::FUpdateCharacterStatisticsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdateCharacterStatisticsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FUpdatePlayerStatisticsRequest::~FUpdatePlayerStatisticsRequest() { } void PlayFab::ServerModels::FUpdatePlayerStatisticsRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (ForceUpdate.notNull()) { writer->WriteIdentifierPrefix(TEXT("ForceUpdate")); writer->WriteValue(ForceUpdate); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteArrayStart(TEXT("Statistics")); for (const FStatisticUpdate& item : Statistics) item.writeJSON(writer); writer->WriteArrayEnd(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdatePlayerStatisticsRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> ForceUpdateValue = obj->TryGetField(TEXT("ForceUpdate")); if (ForceUpdateValue.IsValid() && !ForceUpdateValue->IsNull()) { bool TmpValue; if (ForceUpdateValue->TryGetBool(TmpValue)) { ForceUpdate = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TArray<TSharedPtr<FJsonValue>>&StatisticsArray = FPlayFabJsonHelpers::ReadArray(obj, TEXT("Statistics")); for (int32 Idx = 0; Idx < StatisticsArray.Num(); Idx++) { TSharedPtr<FJsonValue> CurrentItem = StatisticsArray[Idx]; Statistics.Add(FStatisticUpdate(CurrentItem->AsObject())); } return HasSucceeded; } PlayFab::ServerModels::FUpdatePlayerStatisticsResult::~FUpdatePlayerStatisticsResult() { } void PlayFab::ServerModels::FUpdatePlayerStatisticsResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdatePlayerStatisticsResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FUpdateSharedGroupDataRequest::~FUpdateSharedGroupDataRequest() { } void PlayFab::ServerModels::FUpdateSharedGroupDataRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteObjectStart(TEXT("Data")); for (TMap<FString, FString>::TConstIterator It(Data); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (KeysToRemove.Num() != 0) { writer->WriteArrayStart(TEXT("KeysToRemove")); for (const FString& item : KeysToRemove) writer->WriteValue(item); writer->WriteArrayEnd(); } if (Permission.notNull()) { writer->WriteIdentifierPrefix(TEXT("Permission")); writeUserDataPermissionEnumJSON(Permission, writer); } writer->WriteIdentifierPrefix(TEXT("SharedGroupId")); writer->WriteValue(SharedGroupId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdateSharedGroupDataRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* DataObject; if (obj->TryGetObjectField(TEXT("Data"), DataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*DataObject)->Values); It; ++It) { Data.Add(It.Key(), It.Value()->AsString()); } } obj->TryGetStringArrayField(TEXT("KeysToRemove"), KeysToRemove); Permission = readUserDataPermissionFromValue(obj->TryGetField(TEXT("Permission"))); const TSharedPtr<FJsonValue> SharedGroupIdValue = obj->TryGetField(TEXT("SharedGroupId")); if (SharedGroupIdValue.IsValid() && !SharedGroupIdValue->IsNull()) { FString TmpValue; if (SharedGroupIdValue->TryGetString(TmpValue)) { SharedGroupId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUpdateSharedGroupDataResult::~FUpdateSharedGroupDataResult() { } void PlayFab::ServerModels::FUpdateSharedGroupDataResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdateSharedGroupDataResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; return HasSucceeded; } PlayFab::ServerModels::FUpdateUserDataRequest::~FUpdateUserDataRequest() { } void PlayFab::ServerModels::FUpdateUserDataRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteObjectStart(TEXT("Data")); for (TMap<FString, FString>::TConstIterator It(Data); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (KeysToRemove.Num() != 0) { writer->WriteArrayStart(TEXT("KeysToRemove")); for (const FString& item : KeysToRemove) writer->WriteValue(item); writer->WriteArrayEnd(); } if (Permission.notNull()) { writer->WriteIdentifierPrefix(TEXT("Permission")); writeUserDataPermissionEnumJSON(Permission, writer); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdateUserDataRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* DataObject; if (obj->TryGetObjectField(TEXT("Data"), DataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*DataObject)->Values); It; ++It) { Data.Add(It.Key(), It.Value()->AsString()); } } obj->TryGetStringArrayField(TEXT("KeysToRemove"), KeysToRemove); Permission = readUserDataPermissionFromValue(obj->TryGetField(TEXT("Permission"))); const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUpdateUserDataResult::~FUpdateUserDataResult() { } void PlayFab::ServerModels::FUpdateUserDataResult::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); writer->WriteIdentifierPrefix(TEXT("DataVersion")); writer->WriteValue(static_cast<int64>(DataVersion)); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdateUserDataResult::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> DataVersionValue = obj->TryGetField(TEXT("DataVersion")); if (DataVersionValue.IsValid() && !DataVersionValue->IsNull()) { uint32 TmpValue; if (DataVersionValue->TryGetNumber(TmpValue)) { DataVersion = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUpdateUserInternalDataRequest::~FUpdateUserInternalDataRequest() { } void PlayFab::ServerModels::FUpdateUserInternalDataRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Data.Num() != 0) { writer->WriteObjectStart(TEXT("Data")); for (TMap<FString, FString>::TConstIterator It(Data); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } if (KeysToRemove.Num() != 0) { writer->WriteArrayStart(TEXT("KeysToRemove")); for (const FString& item : KeysToRemove) writer->WriteValue(item); writer->WriteArrayEnd(); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdateUserInternalDataRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* DataObject; if (obj->TryGetObjectField(TEXT("Data"), DataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*DataObject)->Values); It; ++It) { Data.Add(It.Key(), It.Value()->AsString()); } } obj->TryGetStringArrayField(TEXT("KeysToRemove"), KeysToRemove); const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FUpdateUserInventoryItemDataRequest::~FUpdateUserInventoryItemDataRequest() { } void PlayFab::ServerModels::FUpdateUserInventoryItemDataRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (CharacterId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); } if (Data.Num() != 0) { writer->WriteObjectStart(TEXT("Data")); for (TMap<FString, FString>::TConstIterator It(Data); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); writer->WriteValue((*It).Value); } writer->WriteObjectEnd(); } writer->WriteIdentifierPrefix(TEXT("ItemInstanceId")); writer->WriteValue(ItemInstanceId); if (KeysToRemove.Num() != 0) { writer->WriteArrayStart(TEXT("KeysToRemove")); for (const FString& item : KeysToRemove) writer->WriteValue(item); writer->WriteArrayEnd(); } writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FUpdateUserInventoryItemDataRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonObject>* DataObject; if (obj->TryGetObjectField(TEXT("Data"), DataObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*DataObject)->Values); It; ++It) { Data.Add(It.Key(), It.Value()->AsString()); } } const TSharedPtr<FJsonValue> ItemInstanceIdValue = obj->TryGetField(TEXT("ItemInstanceId")); if (ItemInstanceIdValue.IsValid() && !ItemInstanceIdValue->IsNull()) { FString TmpValue; if (ItemInstanceIdValue->TryGetString(TmpValue)) { ItemInstanceId = TmpValue; } } obj->TryGetStringArrayField(TEXT("KeysToRemove"), KeysToRemove); const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FWriteEventResponse::~FWriteEventResponse() { } void PlayFab::ServerModels::FWriteEventResponse::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (EventId.IsEmpty() == false) { writer->WriteIdentifierPrefix(TEXT("EventId")); writer->WriteValue(EventId); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FWriteEventResponse::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonValue> EventIdValue = obj->TryGetField(TEXT("EventId")); if (EventIdValue.IsValid() && !EventIdValue->IsNull()) { FString TmpValue; if (EventIdValue->TryGetString(TmpValue)) { EventId = TmpValue; } } return HasSucceeded; } PlayFab::ServerModels::FWriteServerCharacterEventRequest::~FWriteServerCharacterEventRequest() { } void PlayFab::ServerModels::FWriteServerCharacterEventRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Body.Num() != 0) { writer->WriteObjectStart(TEXT("Body")); for (TMap<FString, FJsonKeeper>::TConstIterator It(Body); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteIdentifierPrefix(TEXT("CharacterId")); writer->WriteValue(CharacterId); writer->WriteIdentifierPrefix(TEXT("EventName")); writer->WriteValue(EventName); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); if (Timestamp.notNull()) { writer->WriteIdentifierPrefix(TEXT("Timestamp")); writeDatetime(Timestamp, writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FWriteServerCharacterEventRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* BodyObject; if (obj->TryGetObjectField(TEXT("Body"), BodyObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*BodyObject)->Values); It; ++It) { Body.Add(It.Key(), FJsonKeeper(It.Value())); } } const TSharedPtr<FJsonValue> CharacterIdValue = obj->TryGetField(TEXT("CharacterId")); if (CharacterIdValue.IsValid() && !CharacterIdValue->IsNull()) { FString TmpValue; if (CharacterIdValue->TryGetString(TmpValue)) { CharacterId = TmpValue; } } const TSharedPtr<FJsonValue> EventNameValue = obj->TryGetField(TEXT("EventName")); if (EventNameValue.IsValid() && !EventNameValue->IsNull()) { FString TmpValue; if (EventNameValue->TryGetString(TmpValue)) { EventName = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> TimestampValue = obj->TryGetField(TEXT("Timestamp")); if (TimestampValue.IsValid()) Timestamp = readDatetime(TimestampValue); return HasSucceeded; } PlayFab::ServerModels::FWriteServerPlayerEventRequest::~FWriteServerPlayerEventRequest() { } void PlayFab::ServerModels::FWriteServerPlayerEventRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Body.Num() != 0) { writer->WriteObjectStart(TEXT("Body")); for (TMap<FString, FJsonKeeper>::TConstIterator It(Body); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteIdentifierPrefix(TEXT("EventName")); writer->WriteValue(EventName); writer->WriteIdentifierPrefix(TEXT("PlayFabId")); writer->WriteValue(PlayFabId); if (Timestamp.notNull()) { writer->WriteIdentifierPrefix(TEXT("Timestamp")); writeDatetime(Timestamp, writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FWriteServerPlayerEventRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* BodyObject; if (obj->TryGetObjectField(TEXT("Body"), BodyObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*BodyObject)->Values); It; ++It) { Body.Add(It.Key(), FJsonKeeper(It.Value())); } } const TSharedPtr<FJsonValue> EventNameValue = obj->TryGetField(TEXT("EventName")); if (EventNameValue.IsValid() && !EventNameValue->IsNull()) { FString TmpValue; if (EventNameValue->TryGetString(TmpValue)) { EventName = TmpValue; } } const TSharedPtr<FJsonValue> PlayFabIdValue = obj->TryGetField(TEXT("PlayFabId")); if (PlayFabIdValue.IsValid() && !PlayFabIdValue->IsNull()) { FString TmpValue; if (PlayFabIdValue->TryGetString(TmpValue)) { PlayFabId = TmpValue; } } const TSharedPtr<FJsonValue> TimestampValue = obj->TryGetField(TEXT("Timestamp")); if (TimestampValue.IsValid()) Timestamp = readDatetime(TimestampValue); return HasSucceeded; } PlayFab::ServerModels::FWriteTitleEventRequest::~FWriteTitleEventRequest() { } void PlayFab::ServerModels::FWriteTitleEventRequest::writeJSON(JsonWriter& writer) const { writer->WriteObjectStart(); if (Body.Num() != 0) { writer->WriteObjectStart(TEXT("Body")); for (TMap<FString, FJsonKeeper>::TConstIterator It(Body); It; ++It) { writer->WriteIdentifierPrefix((*It).Key); (*It).Value.writeJSON(writer); } writer->WriteObjectEnd(); } writer->WriteIdentifierPrefix(TEXT("EventName")); writer->WriteValue(EventName); if (Timestamp.notNull()) { writer->WriteIdentifierPrefix(TEXT("Timestamp")); writeDatetime(Timestamp, writer); } writer->WriteObjectEnd(); } bool PlayFab::ServerModels::FWriteTitleEventRequest::readFromValue(const TSharedPtr<FJsonObject>& obj) { bool HasSucceeded = true; const TSharedPtr<FJsonObject>* BodyObject; if (obj->TryGetObjectField(TEXT("Body"), BodyObject)) { for (TMap<FString, TSharedPtr<FJsonValue>>::TConstIterator It((*BodyObject)->Values); It; ++It) { Body.Add(It.Key(), FJsonKeeper(It.Value())); } } const TSharedPtr<FJsonValue> EventNameValue = obj->TryGetField(TEXT("EventName")); if (EventNameValue.IsValid() && !EventNameValue->IsNull()) { FString TmpValue; if (EventNameValue->TryGetString(TmpValue)) { EventName = TmpValue; } } const TSharedPtr<FJsonValue> TimestampValue = obj->TryGetField(TEXT("Timestamp")); if (TimestampValue.IsValid()) Timestamp = readDatetime(TimestampValue); return HasSucceeded; }
[ "vduggirala@csu.fullerton.edu" ]
vduggirala@csu.fullerton.edu
18bcfbe0651bc6e22877416548409ac361e6113f
de239ee228c04444b0c3ea40703814fc5cb29dae
/jni/processors/phaser.cpp
84b37274bc4c10e4a4cbe9aeb22983b2535c62b0
[ "MIT" ]
permissive
rexchun/MWEngine
3263ac69e3d814c6822a75c89fa61724b0170d63
ab4e4355c8c6c6a92c57df24b80c1f267ec8c505
refs/heads/master
2021-04-12T08:29:28.060907
2017-06-12T22:05:46
2017-06-12T22:05:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,607
cpp
/** * The MIT License (MIT) * * Copyright (c) 2013-2014 Igor Zinken - http://www.igorski.nl * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "phaser.h" #include "../global.h" #include <math.h> /* constructor / destructor */ /** * @param aRate {float} desired LFO rate in Hz * @param aFeedback {float} 0 - 1 * @param aDepth {float} 0 - 1 * @param aMinFreq {float} minimum frequency value in Hz allowed for the filters range * @param aMaxFreq {float} maxiumum frequency value in Hz allowed for the filters range */ Phaser::Phaser( float aRate, float aFeedback, float aDepth, float aMinFreq, float aMaxFreq ) { _lfoPhase = 0.0; _zm1 = 0.0; setRange( aMinFreq, aMaxFreq ); setRate( aRate ); _fb = aFeedback; _depth = aDepth; int stages = 6; // six-stage phaser for ( int i = 0; i < stages; ++i ) _alps[ i ] = new AllPassDelay(); } Phaser::~Phaser() { int stages = 6; for ( int i = 0; i < stages; ++i ) delete _alps[ i ]; // _alps wasn't allocated with new[], nothing to delete[] ;) } /* public methods */ /** * set the filter range * @param aMin {float} lowest allowed value in Hz * @param aMax {float} highest allowed value in Hz */ void Phaser::setRange( float aMin, float aMax ) { _dmin = aMin / ( AudioEngineProps::SAMPLE_RATE / 2.0 ); _dmax = aMax / ( AudioEngineProps::SAMPLE_RATE / 2.0 ); } float Phaser::getRate() { return _rate; } /** * @param aRate {float} in Hz */ void Phaser::setRate( float aRate ) { _rate = aRate; _lfoInc = 2.0 * 3.14159f * ( _rate / AudioEngineProps::SAMPLE_RATE ); } float Phaser::getFeedback() { return _fb; } void Phaser::setFeedback( float fb ) { _fb = fb; } float Phaser::getDepth() { return _depth; } void Phaser::setDepth( float depth ) { _depth = depth; } void Phaser::process( AudioBuffer* sampleBuffer, bool isMonoSource ) { int bufferSize = sampleBuffer->bufferSize; SAMPLE_TYPE maxPhase = 3.14159 * 2; // two PI for ( int c = 0, ca = sampleBuffer->amountOfChannels; c < ca; ++c ) { SAMPLE_TYPE* channelBuffer = sampleBuffer->getBufferForChannel( c ); int i = 0; int j; for ( i; i < bufferSize; ++i ) { // calculate and update phaser sweep LFO... SAMPLE_TYPE d = _dmin + ( _dmax - _dmin ) * (( sin( _lfoPhase ) + 1.0 ) / 2.0 ); _lfoPhase += _lfoInc; if ( _lfoPhase >= maxPhase ) _lfoPhase -= maxPhase; // update filter coeffs for ( j = 0; j < 6; ++j ) _alps[ j ]->delay( d ); // calculate output float y = _alps[ 0 ]->update( _alps[ 1 ]->update( _alps[ 2 ]->update( _alps[ 3 ]->update( _alps[ 4 ]->update( _alps[ 5 ]->update( channelBuffer[ i ] + _zm1 * _fb )))))); _zm1 = y; channelBuffer[ i ] += ( y * _depth ); } // save CPU cycles when mono source if ( isMonoSource ) { sampleBuffer->applyMonoSource(); break; } } } /* "private" class */ AllPassDelay::AllPassDelay() { _a1 = 0.0; _zm1 = 0.0; } /* public methods */ // sample delay time void AllPassDelay::delay( float aDelay ) { _a1 = ( 1.0 - aDelay ) / ( 1.0 + aDelay ); } float AllPassDelay::update( float aSample ) { float y = aSample * - _a1 + _zm1; _zm1 = y * _a1 + aSample; return y; }
[ "igor.zinken@igorski.nl" ]
igor.zinken@igorski.nl
715af58b447e49c1907eb04348f2fe49add63e08
e7a236f9804109047d442513cc5174fcfd07fe91
/binary_search/search_rotated.cpp
2bf82a28ecfe4bff5c32e48b32d4ea31ae771811
[]
no_license
sas-practice/cpp-singles
3eae579e1780ab642c3a99cc2baf15d6ef28de1f
96042eff6ed1a9f4e88e94e823980f58e9b6fe8c
refs/heads/master
2020-05-27T09:12:21.737929
2020-03-12T17:19:53
2020-03-12T17:19:53
188,561,911
0
0
null
null
null
null
UTF-8
C++
false
false
2,194
cpp
#include <vector> #include <iostream> using namespace std; int findPivot(vector<int> const &nums) { int start = 0, end = nums.size() - 1; while (start < end) { int mid = start + (end - start) / 2; if (nums[mid] > nums[end]) start = mid + 1; else end = mid; } return start; } int search1(vector<int> const &nums, int target) { int last = nums.size() - 1; if (last < 0) return -1; int pivot = findPivot(nums); if (target == nums[pivot]) return pivot; int start = (target <= nums[last]) ? pivot : 0; int end = (target > nums[last]) ? pivot : last; while (start <= end) { int mid = start + (end - start) / 2; if (nums[mid] == target) return mid; else if (target > nums[mid]) start = mid + 1; else end = mid - 1; } return -1; } //////////////// int search(vector<int> &nums, int target) { int low = 0, high = nums.size() - 1; while (low <= high) { int mid = low + (high - low) / 2; if (nums[mid] == target) return mid; // check repeating if (nums[low] == nums[mid] && nums[mid] == nums[high]) { // move towards mid ++low; --high; } // check in range left else if (nums[low] <= nums[mid]) { if (nums[low] <= target && target < nums[mid]) { high = mid - 1; } else { low = mid + 1; } // check in range right } else if (nums[mid] <= nums[high]) { if (nums[mid] < target && target <= nums[high]) { low = mid + 1; } else { high = mid - 1; } } } return -1; } void test1() { vector<int> arr{2, 5, 6, 0, 0, 1, 2}; cout << search(arr, 0) << endl; cout << search(arr, 5) << endl; cout << search(arr, 2) << endl; cout << "---" << endl; } void test2() { vector<int> arr{2, 5, 6, 0, 0, 1, 2}; cout << search1(arr, 0) << endl; cout << search1(arr, 5) << endl; cout << search1(arr, 2) << endl; cout << "---" << endl; } int main() { test1(); test2(); return 0; }
[ "saswat.dutta@gmail.com" ]
saswat.dutta@gmail.com
ea379c5465558982d28e0d6badae5c3c82fede53
6ee567fc3836fce02cc2b4c9c87f107e85164b1e
/TLC_leonardo/Screen.h
532eec54aae898377c2ec416804480f1bfa492c4
[]
no_license
kamilmmach/projects
761f65ea73427786ce5a67f7fcfdb3b78b61dcaa
a73708af576c93e282cd31b10a9446b7bda63891
refs/heads/master
2023-01-07T17:07:06.442548
2020-11-10T15:00:02
2020-11-10T15:00:02
311,422,090
0
0
null
null
null
null
UTF-8
C++
false
false
645
h
#ifndef _SCREEN_H_ #define _SCREEN_H_ #include "Arduino.h" #include "Pixel.h" class Screen { private: int width_; int height_; Pixel** pixels_; byte* tlc_data_; int tlc_data_size_; void setChannel(int i, int value); public: Screen(int width, int height, int num_tlcs); ~Screen(); int width() const { return width_; } int height() const { return height_; } void update(); byte* tlc_data() const { return tlc_data_; } int tlc_data_size() const { return tlc_data_size_; } Pixel* pixel(int x, int y) const; void set_pixel(int x, int y, float r, float g, float b); void set_pixel(int x, int y, float intensity); }; #endif
[ "kamil.m.mach@gmail.com" ]
kamil.m.mach@gmail.com
5a143459d91f7d88e67ff06a0c4566796b70adbf
a86e02e2d77ec6ab4a7da09df0262b363690b55e
/eg5_7a.cpp
4be614eff96d98a08dfb5ab470ca3705ffb91719
[]
no_license
rajaniket/Cpp_programs
59e20ef7c0918b0dfad1ed9468a479c49bd7ccc0
6528a5bff5c58dd734d46cf8a6aa5363b90219d9
refs/heads/master
2021-06-18T11:19:51.830199
2021-06-08T17:26:59
2021-06-08T17:26:59
215,588,831
5
0
null
2020-01-04T18:15:40
2019-10-16T16:00:09
C++
UTF-8
C++
false
false
647
cpp
// using objects as argument add two time to get new time //(only Pass Object from the Function with no return type) #include<iostream> #include<bits/stdc++.h> using namespace std; class Time { int hours,minutes; public: void gettime(int h,int m){ hours=h; minutes=m; } void showtime() { int x; x=hours; hours=minutes/60; minutes=minutes%60; hours=x+hours; cout<<"The time is "<<hours<<" hours and "<<minutes<<" minutes. "<<endl; } void addtime(Time x,Time y) // object as an argument { hours=x.hours + y.hours; minutes=x.minutes + y.minutes; } }; int main() { Time a,b,c; a.gettime(2,123); b.gettime(3,64); c.addtime(a,b); c.showtime(); }
[ "noreply@github.com" ]
noreply@github.com
874625d04769e962048d34a2f1dcade406c5a9fc
d6fbac3f4b66e15c454666e03c4f8e5f7b4e42f1
/src/StruturalPattern/AdapterPattern.cpp
e644e2c111acc79368e29e6aef01b15e8221d4cf
[]
no_license
cxduc92/ModernCppDesignPattern
736f48ac4f0d6efbd8cd4791728a4a1dadedb504
c09f22203f20ebb5de171f8682b41dcf82824145
refs/heads/master
2022-07-25T05:10:21.949259
2020-05-17T16:12:48
2020-05-17T16:12:48
262,351,042
0
0
null
null
null
null
UTF-8
C++
false
false
702
cpp
/* * AdapterPattern.cpp * * Use case: Get the interface you want from the interface you have * We can not modify our gadgets to support every possible interface * * ========> Adapter: A construct which adapts an existing interface X to conform * to a required interface Y * * Application Ex: Adapt interfaces * * Created on: Oct 24, 2019 * Author: ubuntu */ #include "iostream" #include "cstdio" #include "stdint.h" #include "stdio.h" #include "string" #include "vector" #include "fstream" #include "map" #include "boost/lexical_cast.hpp" using namespace std; int runAdapterPattern() //int main(int argc, char *argv[]) { return 0; }
[ "cxduc92@gmail.com" ]
cxduc92@gmail.com
1515afe9dc43854bd80afb1376c030066c8556de
8f52afac97ecfbdd22b33e7530dd584b3f6c0bda
/test/decorator_counter_node.cpp
5dda7ee2f2691619f95893972bb0f9445ccbb656
[]
no_license
ufownl/ranger_bhvr_tree
95d49f2a11927a1db9f5431901c567e82c3a0ccc
0697886fcc0c1932a0292d6fb5cea0f29ceeb9d9
refs/heads/master
2020-05-17T14:18:18.395284
2015-11-24T02:45:12
2015-11-24T02:45:12
40,969,569
3
1
null
2015-08-22T14:57:59
2015-08-18T12:02:31
C++
UTF-8
C++
false
false
3,198
cpp
// Copyright (c) 2015, RangerUFO // 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 ranger_bhvr_tree nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "test_util.hpp" #include <gtest/gtest.h> TEST(decorator_counter_node, counter_true) { test_generator gen; auto root = gen.generate( "<bhvr_tree class = \"decorator_counter_node\" count = \"5\">" "<bhvr_tree class = \"true_node\"/>" "</bhvr_tree>" ); ASSERT_NE(nullptr, root); test_agent agent; EXPECT_EQ(0, agent.get_true_counter()); EXPECT_EQ(0, agent.get_false_counter()); test_agent_proxy ap(agent); for (size_t i = 0; i < 10; ++i) { root->exec(ap, [i] (bool result, test_agent* agent) { if (i < 5) { EXPECT_TRUE(result); EXPECT_EQ(i + 1, agent->get_true_counter()); EXPECT_EQ(0, agent->get_false_counter()); } else { EXPECT_FALSE(result); EXPECT_EQ(5, agent->get_true_counter()); EXPECT_EQ(0, agent->get_false_counter()); } }); } } TEST(decorator_counter_node, counter_false) { test_generator gen; auto root = gen.generate( "<bhvr_tree class = \"decorator_counter_node\" count = \"5\">" "<bhvr_tree class = \"false_node\"/>" "</bhvr_tree>" ); ASSERT_NE(nullptr, root); test_agent agent; EXPECT_EQ(0, agent.get_true_counter()); EXPECT_EQ(0, agent.get_false_counter()); test_agent_proxy ap(agent); for (size_t i = 0; i < 10; ++i) { root->exec(ap, [i] (bool result, test_agent* agent) { EXPECT_FALSE(result); if (i < 5) { EXPECT_EQ(0, agent->get_true_counter()); EXPECT_EQ(i + 1, agent->get_false_counter()); } else { EXPECT_EQ(0, agent->get_true_counter()); EXPECT_EQ(5, agent->get_false_counter()); } }); } }
[ "ufownl@gmail.com" ]
ufownl@gmail.com
d26418bb1f2ea87f0541077b2be44cec025cfc43
a555fdf8e9a91505808d4fab4707cf6044a0d03e
/jni/serial_port_jni_mgr.cpp
c946f54b68c19edc9be7577e69dea04071e1a519
[]
no_license
lhc180/msg_analyzer_java
e9f75f8874f27757b9c46f5d9c7c32743c512274
ee7ef6ccaf683703c66be7385660baf35557b28a
refs/heads/master
2021-01-24T22:22:51.665677
2015-02-12T07:21:52
2015-02-12T07:21:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,195
cpp
#include "serial_port_jni_mgr.h" #include "serial_port_cmn_def.h" #include "syslog_debug.h" SerialPortJniMgr::SerialPortJniMgr() : fd(0) { memset(device_file, 0x0, sizeof(char) * 256); } unsigned short SerialPortJniMgr::get_supported_baudrate(unsigned int serial_baudrate, tcflag_t& baudrate) { switch (serial_baudrate) { case 9600: baudrate = B9600; break; case 115200: baudrate = B115200; break; default: return SERIAL_PORT_FAILURE_INVALID_ARGUMENT; } return SERIAL_PORT_SUCCESS; } unsigned short SerialPortJniMgr::open_serial(const char* serial_device_file, int serial_baudrate) { if (serial_device_file == NULL) { WRITE_ERR_SYSLOG("Invalid argument: serial_device_file\n"); return SERIAL_PORT_FAILURE_INVALID_ARGUMENT; } unsigned short ret = get_supported_baudrate(serial_baudrate, baudrate); if (CHECK_SERIAL_PORT_FAILURE(ret)) { WRITE_ERR_FORMAT_SYSLOG("Unsupported baud rate: %d\n", serial_baudrate); return ret; } WRITE_DEBUG_FORMAT_SYSLOG("Try to open a serial port[%s] with baud rate: %d\n", serial_device_file, serial_baudrate); memcpy(device_file, serial_device_file, sizeof(char) * strlen(serial_device_file)); // Open modem device for reading and writing and not as controlling tty because we don't want to get killed if line noise sends CTRL-C. fd = open(device_file, O_RDWR | O_NOCTTY); if (fd <0) { WRITE_ERR_FORMAT_SYSLOG("open() failed, due to %s\n", strerror(errno)); return SERIAL_PORT_FAILURE_OPEN_FILE; } tcgetattr(fd, &oldtio); /* save current serial port settings */ bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */ // BAUDRATE: Set bps rate. You could also use cfsetispeed and cfsetospeed. // CRTSCTS : output hardware flow control (only used if the cable has all necessary lines. See sect. 7 of Serial-HOWTO) // CS8 : 8n1 (8bit,no parity,1 stopbit) // CLOCAL : local connection, no modem control // CREAD : enable receiving characters newtio.c_cflag = baudrate | CRTSCTS | CS8 | CLOCAL | CREAD; // IGNPAR : ignore bytes with parity errors // ICRNL : map CR to NL (otherwise a CR input on the other computer will not terminate input), otherwise make device raw (no other input processing) newtio.c_iflag = IGNPAR | ICRNL; // Raw output. newtio.c_oflag = 0; // ICANON : enable canonical input, disable all echo functionality, and don't send signals to calling program newtio.c_lflag = ICANON; // initialize all control characters default values can be found in /usr/include/termios.h, and are given in the comments, but we don't need them here newtio.c_cc[VINTR] = 0; /* Ctrl-c */ newtio.c_cc[VQUIT] = 0; /* Ctrl-\ */ newtio.c_cc[VERASE] = 0; /* del */ newtio.c_cc[VKILL] = 0; /* @ */ newtio.c_cc[VEOF] = 4; /* Ctrl-d */ newtio.c_cc[VTIME] = 0; /* inter-character timer unused */ newtio.c_cc[VMIN] = 1; /* blocking read until 1 character arrives */ newtio.c_cc[VSWTC] = 0; /* '\0' */ newtio.c_cc[VSTART] = 0; /* Ctrl-q */ newtio.c_cc[VSTOP] = 0; /* Ctrl-s */ newtio.c_cc[VSUSP] = 0; /* Ctrl-z */ newtio.c_cc[VEOL] = 0; /* '\0' */ newtio.c_cc[VREPRINT] = 0; /* Ctrl-r */ newtio.c_cc[VDISCARD] = 0; /* Ctrl-u */ newtio.c_cc[VWERASE] = 0; /* Ctrl-w */ newtio.c_cc[VLNEXT] = 0; /* Ctrl-v */ newtio.c_cc[VEOL2] = 0; /* '\0' */ // now clean the modem line and activate the settings for the port tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &newtio); return SERIAL_PORT_SUCCESS; } unsigned short SerialPortJniMgr::close_serial() { if (fd != 0) { tcsetattr(fd, TCSANOW, &oldtio); close(fd); fd = 0; } return SERIAL_PORT_SUCCESS; } unsigned short SerialPortJniMgr::read_serial(char* buf, int buf_size, int& actual_datalen) { if (buf == NULL) { WRITE_ERR_SYSLOG("Invalid argument: buf"); return SERIAL_PORT_FAILURE_INVALID_ARGUMENT; } actual_datalen = read(fd, buf, buf_size); WRITE_DEBUG_FORMAT_SYSLOG("read data: %s, len: %d\n", buf, buf_size); if (actual_datalen == -1) { WRITE_ERR_FORMAT_SYSLOG("read() failed, due to %s\n", strerror(errno)); return SERIAL_PORT_FAILURE_UNKNOWN; } return SERIAL_PORT_SUCCESS; }
[ "Everett6802@hotmail.com" ]
Everett6802@hotmail.com
9d54c1952d32afe15c66948902c9a1f9e7a49f17
b39446a01e5270c983614000f36ed7776c37fd5a
/code_snippets/Chapter04/chapter.4.5.1.cpp
c69058cef2f406a5f21ab2414b8d73cd787a5029
[ "MIT" ]
permissive
ltr01/stroustrup-ppp-1
aa6e063e11b1dccab854602895e85bef876f2ea5
d9736cc67ef8e2f0483003c8ec35cc0785460cd1
refs/heads/master
2023-01-03T09:16:13.399468
2020-10-28T10:41:25
2020-10-28T10:41:25
261,959,252
1
0
MIT
2020-05-07T05:38:23
2020-05-07T05:38:22
null
UTF-8
C++
false
false
569
cpp
// // This is example code from Chapter 4.5.1 "Why bother with functions?" of // "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup // #include "std_lib_facilities.h" //------------------------------------------------------------------------------ void print_square(int v) { cout << v << '\t' << v*v << '\n'; } //------------------------------------------------------------------------------ int main() { for (int i = 0; i<100; ++i) print_square(i); } //------------------------------------------------------------------------------
[ "bewuethr@users.noreply.github.com" ]
bewuethr@users.noreply.github.com
3731de201612ceede974f6364cb68c66c7a78a00
d2ba0389accde0370662b9df282ef1f8df8d69c7
/frameworks/cocos2d-x/cocos/editor-support/spine/Updatable.h
90411915fa28a4fcbec3d692fee907080e06632a
[]
no_license
Kuovane/LearnOpenGLES
6a42438db05eecf5c877504013e9ac7682bc291c
8458b9c87d1bf333b8679e90a8a47bc27ebe9ccd
refs/heads/master
2022-07-27T00:28:02.066179
2020-05-14T10:34:46
2020-05-14T10:34:46
262,535,484
0
0
null
null
null
null
UTF-8
C++
false
false
2,183
h
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #ifndef Spine_Updatable_h #define Spine_Updatable_h #include <spine/RTTI.h> #include <spine/SpineObject.h> namespace spine { class SP_API Updatable : public SpineObject { RTTI_DECL public: Updatable(); virtual ~Updatable(); virtual void update() = 0; }; } #endif /* Spine_Updatable_h */
[ "811408414@qq.com" ]
811408414@qq.com
bbf9253f2916b5a03ff9efbb794a10961c75640c
47ff8543c73dab22c7854d9571dfc8d5f467ee8c
/BOJ/10874/10874.cpp
8de8e1f3495edc1030d320191544e5fca95eb685
[]
no_license
eldsg/BOJ
4bb0c93dc60783da151e685530fa9a511df3a141
6bd15e36d69ce1fcf208d193d5e9067de9bb405e
refs/heads/master
2020-04-16T02:18:55.808362
2017-11-28T11:02:37
2017-11-28T11:02:37
55,879,791
2
0
null
null
null
null
UTF-8
C++
false
false
284
cpp
#include<stdio.h> int main(){ int number; scanf("%d", &number); for(int i = 0; i<=number; i++){ int count = 0; for(int j = 1; j<=10; j++){ int numbers; scanf("%d", &numbers); if(numbers == ((j-1)%5)+1) count++; } if(count == 10){ printf("%d\n", i+1); } } }
[ "kgm0219@gmail.com" ]
kgm0219@gmail.com
158c6e34fbc25a316edfd5543824d77a2a89c6b4
4ea7ad6e3c5c1ba5839edae3a08db0ca371520ca
/UVAOJ/10718.cpp
224ddfa383d2aa8ec26037fccaa87721e8ae6235
[]
no_license
nawZeroX239/competitive-programming
144eac050fafffc51267c67afb96e60316ae2294
f52472db0e1e6fe724e9a7456deac19683fa4813
refs/heads/master
2021-03-10T12:30:42.533862
2020-12-24T00:32:01
2020-12-24T00:32:01
246,452,848
0
1
null
2020-10-02T18:22:05
2020-03-11T02:10:17
C++
UTF-8
C++
false
false
1,508
cpp
#include <iostream> //#include <string> #include <sstream> #include <algorithm> #include <functional> #include <utility> //#include <unordered_set> #include <vector> //#include <list> //#include <string> //#include <iterator> //#include <iomanip> //#include <deque> //#include <array> //#include <forward_list> //#include <queue> //#include <stack> //#include <set> #include <map> //#include <unordered_set> //#include <unordered_map> //#include <cstdio> //#include <cstdlib> //#include <cstring> //#include <ctime> #include <climits> #include <cmath> //#include <bitset> //#include <numeric> using namespace std; const long double PI = 3.14159265358979323846264338327950; const double EPS = 1e-9; const int cx[] = { -1, 1, 0, 0 }, cy[] = { 0, 0, -1, 1 }; const int N = 6; template <class T> T gcd(T a, T b) { if (b == 0) { return a; } return gcd(b, a % b); } int toInt(string& s) { stringstream ss(s); int n; ss >> n; return n; } //bool sort_pred(const pair<int, int>& left, const pair<int, int>& right) { // return left.second > right.second; //} // //bool lb_pred(const pair<int, int>& left, const int right) { // return left.first < right; //} // int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long n, l, u, m, a, b; while (cin >> n >> l >> u) { m = 0; for (int i = 31; i >= 0; --i) { a = 1LL << i; if (m + a - 1 < l) { m += a; } else if (!((n >> i) & 1)) { if (m+a<=u ) m += a; } } cout << m << '\n'; } return 0; }
[ "naw122333444455555@gmail.com" ]
naw122333444455555@gmail.com
d2cc9fa4b783058a1a9031453d45b602dbaf927e
afb20fe808cd2756f248ca276af3f62c4b8ece98
/0148/Solution.cpp
dfc74f8633e8aef520e9ab8ab635b0c78fce75e2
[]
no_license
S213B/LeetCode
27abe62689595bacf61332464caafa572db6e850
f3b8ee4ca4bac128414804946122e4d814c5c1eb
refs/heads/master
2021-01-15T10:47:37.584255
2020-06-12T22:28:15
2020-06-12T22:28:15
33,704,429
0
0
null
null
null
null
UTF-8
C++
false
false
1,439
cpp
#include <iostream> #include <string> #include <vector> #include <unordered_map> #include <unordered_set> #include <algorithm> #include <deque> #include <queue> #include <stack> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* sortList(ListNode* head) { if (!head || !head->next) return head; ListNode *mid_prev = head, *tail = head; while (tail->next && tail->next->next) { tail = tail->next->next; mid_prev = mid_prev->next; } ListNode *mid = mid_prev->next; mid_prev->next = NULL; head = sortList(head); mid = sortList(mid); ListNode *ans = NULL, **pans = &ans; while (head && mid) { ListNode **n = head->val < mid->val ? &head : &mid; *pans = *n; pans = &((*pans)->next); *n = (*n)->next; } *pans = head ? head : mid; return ans; } }; int main(int argc, char *argv[]) { Solution solution; ListNode *head = NULL, **phead = &head; for (int i = 1; i < argc; i ++) { *phead = new ListNode(atoi(argv[i])); phead = &((*phead)->next); } head = solution.sortList(head); while (head) { cout << head->val << " "; head = head->next; } cout << endl; return 0; }
[ "xlq.s213b@gmail.com" ]
xlq.s213b@gmail.com
e8d3e52c33f25bc78fd2909ff0ca75f0a6de2dcb
96592a6b5d159f843fe0e0ee18308cc0ebefcf82
/third_party/boost/libs/math/test/test_barycentric_rational.cpp
6427e856e7e1bb927d6c4ef2556c5c2e42313e82
[ "BSL-1.0" ]
permissive
avplayer/tinyrpc
8d505b9f2a8594c59a6cab2d186ec945c7952394
7049b4079fac78b3828e68f787d04d699ce52f6d
refs/heads/master
2020-04-25T02:29:18.753768
2019-05-24T01:55:28
2019-05-24T01:55:28
172,441,102
8
3
null
null
null
null
UTF-8
C++
false
false
9,121
cpp
// Copyright Nick Thompson, 2017 // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) #define BOOST_TEST_MODULE barycentric_rational #include <cmath> #include <random> #include <boost/random/uniform_real_distribution.hpp> #include <boost/type_index.hpp> #include <boost/test/included/unit_test.hpp> #include <boost/test/floating_point_comparison.hpp> #include <boost/math/interpolators/barycentric_rational.hpp> #include <boost/multiprecision/cpp_bin_float.hpp> #ifdef BOOST_HAS_FLOAT128 #include <boost/multiprecision/float128.hpp> #endif using std::sqrt; using std::abs; using std::numeric_limits; using boost::multiprecision::cpp_bin_float_50; template<class Real> void test_interpolation_condition() { std::cout << "Testing interpolation condition for barycentric interpolation on type " << boost::typeindex::type_id<Real>().pretty_name() << "\n"; std::mt19937 gen(4); boost::random::uniform_real_distribution<Real> dis(0.1f, 1); std::vector<Real> x(500); std::vector<Real> y(500); x[0] = dis(gen); y[0] = dis(gen); for (size_t i = 1; i < x.size(); ++i) { x[i] = x[i-1] + dis(gen); y[i] = dis(gen); } boost::math::barycentric_rational<Real> interpolator(x.data(), y.data(), y.size()); for (size_t i = 0; i < x.size(); ++i) { Real z = interpolator(x[i]); BOOST_CHECK_CLOSE(z, y[i], 100*numeric_limits<Real>::epsilon()); } } template<class Real> void test_interpolation_condition_high_order() { std::cout << "Testing interpolation condition in high order for barycentric interpolation on type " << boost::typeindex::type_id<Real>().pretty_name() << "\n"; std::mt19937 gen(5); boost::random::uniform_real_distribution<Real> dis(0.1f, 1); std::vector<Real> x(500); std::vector<Real> y(500); x[0] = dis(gen); y[0] = dis(gen); for (size_t i = 1; i < x.size(); ++i) { x[i] = x[i-1] + dis(gen); y[i] = dis(gen); } // Order 5 approximation: boost::math::barycentric_rational<Real> interpolator(x.data(), y.data(), y.size(), 5); for (size_t i = 0; i < x.size(); ++i) { Real z = interpolator(x[i]); BOOST_CHECK_CLOSE(z, y[i], 100*numeric_limits<Real>::epsilon()); } } template<class Real> void test_constant() { std::cout << "Testing that constants are interpolated correctly using barycentric interpolation on type " << boost::typeindex::type_id<Real>().pretty_name() << "\n"; std::mt19937 gen(6); boost::random::uniform_real_distribution<Real> dis(0.1f, 1); std::vector<Real> x(500); std::vector<Real> y(500); Real constant = -8; x[0] = dis(gen); y[0] = constant; for (size_t i = 1; i < x.size(); ++i) { x[i] = x[i-1] + dis(gen); y[i] = y[0]; } boost::math::barycentric_rational<Real> interpolator(x.data(), y.data(), y.size()); for (size_t i = 0; i < x.size(); ++i) { // Don't evaluate the constant at x[i]; that's already tested in the interpolation condition test. Real t = x[i] + dis(gen); Real z = interpolator(t); BOOST_CHECK_CLOSE(z, constant, 100*sqrt(numeric_limits<Real>::epsilon())); BOOST_CHECK_SMALL(interpolator.prime(t), sqrt(numeric_limits<Real>::epsilon())); } } template<class Real> void test_constant_high_order() { std::cout << "Testing that constants are interpolated correctly in high order using barycentric interpolation on type " << boost::typeindex::type_id<Real>().pretty_name() << "\n"; std::mt19937 gen(7); boost::random::uniform_real_distribution<Real> dis(0.1f, 1); std::vector<Real> x(500); std::vector<Real> y(500); Real constant = 5; x[0] = dis(gen); y[0] = constant; for (size_t i = 1; i < x.size(); ++i) { x[i] = x[i-1] + dis(gen); y[i] = y[0]; } // Set interpolation order to 7: boost::math::barycentric_rational<Real> interpolator(x.data(), y.data(), y.size(), 7); for (size_t i = 0; i < x.size(); ++i) { Real t = x[i] + dis(gen); Real z = interpolator(t); BOOST_CHECK_CLOSE(z, constant, 1000*sqrt(numeric_limits<Real>::epsilon())); BOOST_CHECK_SMALL(interpolator.prime(t), 100*sqrt(numeric_limits<Real>::epsilon())); } } template<class Real> void test_runge() { std::cout << "Testing interpolation of Runge's 1/(1+25x^2) function using barycentric interpolation on type " << boost::typeindex::type_id<Real>().pretty_name() << "\n"; std::mt19937 gen(8); boost::random::uniform_real_distribution<Real> dis(0.005f, 0.01f); std::vector<Real> x(500); std::vector<Real> y(500); x[0] = -2; y[0] = 1/(1+25*x[0]*x[0]); for (size_t i = 1; i < x.size(); ++i) { x[i] = x[i-1] + dis(gen); y[i] = 1/(1+25*x[i]*x[i]); } boost::math::barycentric_rational<Real> interpolator(x.data(), y.data(), y.size(), 5); for (size_t i = 0; i < x.size(); ++i) { Real t = x[i]; Real z = interpolator(t); BOOST_CHECK_CLOSE(z, y[i], 0.03); Real z_prime = interpolator.prime(t); Real num = -50*t; Real denom = (1+25*t*t)*(1+25*t*t); if (abs(num/denom) > 0.00001) { BOOST_CHECK_CLOSE_FRACTION(z_prime, num/denom, 0.03); } } Real tol = 0.0001; for (size_t i = 0; i < x.size(); ++i) { Real t = x[i] + dis(gen); Real z = interpolator(t); BOOST_CHECK_CLOSE(z, 1/(1+25*t*t), tol); Real z_prime = interpolator.prime(t); Real num = -50*t; Real denom = (1+25*t*t)*(1+25*t*t); Real runge_prime = num/denom; if (abs(runge_prime) > 0 && abs(z_prime - runge_prime)/abs(runge_prime) > tol) { std::cout << "Error too high for t = " << t << " which is a distance " << t - x[i] << " from node " << i << "/" << x.size() << " associated with data (" << x[i] << ", " << y[i] << ")\n"; BOOST_CHECK_CLOSE_FRACTION(z_prime, runge_prime, tol); } } } template<class Real> void test_weights() { std::cout << "Testing weights are calculated correctly using barycentric interpolation on type " << boost::typeindex::type_id<Real>().pretty_name() << "\n"; std::mt19937 gen(9); boost::random::uniform_real_distribution<Real> dis(0.005, 0.01); std::vector<Real> x(500); std::vector<Real> y(500); x[0] = -2; y[0] = 1/(1+25*x[0]*x[0]); for (size_t i = 1; i < x.size(); ++i) { x[i] = x[i-1] + dis(gen); y[i] = 1/(1+25*x[i]*x[i]); } boost::math::detail::barycentric_rational_imp<Real> interpolator(x.data(), x.data() + x.size(), y.data(), 0); for (size_t i = 0; i < x.size(); ++i) { Real w = interpolator.weight(i); if (i % 2 == 0) { BOOST_CHECK_CLOSE(w, 1, 0.00001); } else { BOOST_CHECK_CLOSE(w, -1, 0.00001); } } // d = 1: interpolator = boost::math::detail::barycentric_rational_imp<Real>(x.data(), x.data() + x.size(), y.data(), 1); for (size_t i = 1; i < x.size() -1; ++i) { Real w = interpolator.weight(i); Real w_expect = 1/(x[i] - x[i - 1]) + 1/(x[i+1] - x[i]); if (i % 2 == 0) { BOOST_CHECK_CLOSE(w, -w_expect, 0.00001); } else { BOOST_CHECK_CLOSE(w, w_expect, 0.00001); } } } BOOST_AUTO_TEST_CASE(barycentric_rational) { test_weights<double>(); test_constant<float>(); test_constant<double>(); test_constant<long double>(); test_constant<cpp_bin_float_50>(); test_constant_high_order<float>(); test_constant_high_order<double>(); test_constant_high_order<long double>(); test_constant_high_order<cpp_bin_float_50>(); test_interpolation_condition<float>(); test_interpolation_condition<double>(); test_interpolation_condition<long double>(); test_interpolation_condition<cpp_bin_float_50>(); test_interpolation_condition_high_order<float>(); test_interpolation_condition_high_order<double>(); test_interpolation_condition_high_order<long double>(); test_interpolation_condition_high_order<cpp_bin_float_50>(); test_runge<double>(); test_runge<long double>(); test_runge<cpp_bin_float_50>(); #ifdef BOOST_HAS_FLOAT128 test_interpolation_condition<boost::multiprecision::float128>(); test_constant<boost::multiprecision::float128>(); test_constant_high_order<boost::multiprecision::float128>(); test_interpolation_condition_high_order<boost::multiprecision::float128>(); test_runge<boost::multiprecision::float128>(); #endif }
[ "jack.wgm@gmail.com" ]
jack.wgm@gmail.com
0a2ff703c855c26b52f6165d93143ef50cd686df
9f9660f318732124b8a5154e6670e1cfc372acc4
/test/case0/constant/polyMesh/boundary
e70dab37174187fb3e6df0c19df1f60ae2df2adb
[]
no_license
mamitsu2/aircond5
9a6857f4190caec15823cb3f975cdddb7cfec80b
20a6408fb10c3ba7081923b61e44454a8f09e2be
refs/heads/master
2020-04-10T22:41:47.782141
2019-09-02T03:42:37
2019-09-02T03:42:37
161,329,638
0
0
null
null
null
null
UTF-8
C++
false
false
2,694
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class polyBoundaryMesh; location "constant/polyMesh"; object boundary; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // 14 ( floor { type wall; inGroups 1(wall); nFaces 29; startFace 852; } ceiling { type wall; inGroups 1(wall); nFaces 43; startFace 881; } sWall { type wall; inGroups 1(wall); nFaces 1; startFace 924; } nWall { type wall; inGroups 1(wall); nFaces 6; startFace 925; } sideWalls { type empty; inGroups 1(empty); nFaces 918; startFace 931; } glass1 { type wall; inGroups 1(wall); nFaces 9; startFace 1849; } glass2 { type wall; inGroups 1(wall); nFaces 2; startFace 1858; } sun { type wall; inGroups 1(wall); nFaces 14; startFace 1860; } heatsource1 { type wall; inGroups 1(wall); nFaces 3; startFace 1874; } heatsource2 { type wall; inGroups 1(wall); nFaces 4; startFace 1877; } Table_master { type wall; inGroups 2 ( wall Table ) ; nFaces 9; startFace 1881; } Table_slave { type wall; inGroups 2 ( wall Table ) ; nFaces 9; startFace 1890; } inlet { type patch; nFaces 1; startFace 1899; } outlet { type patch; nFaces 2; startFace 1900; } ) // ************************************************************************* //
[ "mitsuaki.makino@tryeting.jp" ]
mitsuaki.makino@tryeting.jp
095cdef35e5a7497f56f75047cad817be20dd222
39719ced2451b97c266568e2d9364bfe90ab3498
/Include/Gui3D/Gui3DPanelColors.h
16f7bfeaa90bb836640bcf0851c05d77e19ffc3a
[ "MIT" ]
permissive
shanefarris/CoreGameEngine
74ae026cdc443242fa80fe9802f5739c1064fb66
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
refs/heads/master
2020-05-07T12:19:23.055995
2019-04-11T14:10:16
2019-04-11T14:10:16
180,496,793
3
2
null
null
null
null
UTF-8
C++
false
false
19,945
h
/* Gui3D ------- Copyright (c) 2012 Valentin Frechaud 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. */ #ifndef Gui3DPanelColors_H #define Gui3DPanelColors_H #include <OGRE\Ogre.h> #include "Gorilla.h" namespace Gui3D { /*! class. PanelColors desc. Interface for colors of the Gui3D elements. note. By default, an element will use its gradients, colors and borders definitions. To use sprites, you have to set ALL the sprite names (each has to be different of "" or "none"), and thoses sprites have to be defined in the .gorilla file, otherwise, an OGRE EXCEPTION will be throwned by Gorilla (with the sprite name or sprite informations) */ struct PanelColors { /** \brief Init all the colour values */ PanelColors() { transparent = Gorilla::rgb(0, 0, 0, 0); // NorthSouth gradient by default panelGradientType = Gorilla::Gradient_NorthSouth; buttonBackgroundClickedGradientType = panelGradientType; buttonBackgroundOveredGradientType = panelGradientType; buttonBackgroundNotOveredGradientType = panelGradientType; buttonBackgroundInactiveGradientType = panelGradientType; checkboxOveredGradientType = panelGradientType; checkboxNotOveredGradientType = panelGradientType; comboboxBackgroundGradientType = panelGradientType; inlineselectorBackgroundGradientType = panelGradientType; listboxBackgroundGradientType = panelGradientType; scrollbarBackgroundGradientType = panelGradientType; scrollbarProgressbarGradientType = panelGradientType; scrollbarCursorOveredGradientType = panelGradientType; scrollbarCursorNotOveredGradientType = panelGradientType; scrollbarCursorSelectedGradientType = panelGradientType; textzoneBackgroundOveredGradientType = panelGradientType; textzoneBackgroundNotOveredGradientType = panelGradientType; textzoneBackgroundSelectedGradientType = panelGradientType; captionBackgroundGradientType = panelGradientType; progressbarBackgroundGradientType = panelGradientType; progressbarLoadingBarGradientType = panelGradientType; // Init border sizes size_t defaultBorderSize = 0; panelCursorSpriteSizeX = defaultBorderSize; panelCursorSpriteSizeY = defaultBorderSize; panelBorderSize = defaultBorderSize; buttonTextSize = defaultBorderSize; buttonBorderSize = defaultBorderSize; checkboxTextSize = defaultBorderSize; checkboxBorderSize = defaultBorderSize; comboboxTextSize = defaultBorderSize; comboboxBorderSize = defaultBorderSize; inlineselectorTextSize = defaultBorderSize; inlineselectorBorderSize = defaultBorderSize; listboxTextSize = defaultBorderSize; listboxBorderSize = defaultBorderSize; scrollbarTextSize = defaultBorderSize; scrollbarBorderSize = defaultBorderSize; scrollbarCursorBorderSize = defaultBorderSize; textzoneTextSize = defaultBorderSize; textzoneBorderSize = defaultBorderSize; captionTextSize = defaultBorderSize; captionBorderSize = defaultBorderSize; progressbarTextSize = defaultBorderSize; progressbarBorderSize = defaultBorderSize; } // General Ogre::ColourValue transparent; // Panel Ogre::String panelBackgroundSpriteName; Ogre::String panelCursorSpriteName; size_t panelCursorSpriteSizeX; size_t panelCursorSpriteSizeY; Gorilla::Gradient panelGradientType; //!< \brief The gradient type of a panel. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue panelGradientColorStart; Ogre::ColourValue panelGradientColorEnd; Ogre::ColourValue panelBorder; //!< \brief The border colour of a panel. size_t panelBorderSize; //!< \brief The border size of a panel. /** * * Button configuration * */ Ogre::String buttonOveredSpriteName; Ogre::String buttonNotOveredSpriteName; Ogre::String buttonInactiveSpriteName; Ogre::String buttonClickedSpriteName; Gorilla::Gradient buttonBackgroundClickedGradientType; //!< \brief The gradient type of an overed button. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue buttonBackgroundClickedGradientStart; Ogre::ColourValue buttonBackgroundClickedGradientEnd; Gorilla::Gradient buttonBackgroundOveredGradientType; //!< \brief The gradient type of an overed button. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue buttonBackgroundOveredGradientStart; Ogre::ColourValue buttonBackgroundOveredGradientEnd; Gorilla::Gradient buttonBackgroundNotOveredGradientType; //!< \brief The gradient type of a not overed button. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue buttonBackgroundNotOveredGradientStart; Ogre::ColourValue buttonBackgroundNotOveredGradientEnd; Gorilla::Gradient buttonBackgroundInactiveGradientType; Ogre::ColourValue buttonBackgroundInactiveGradientStart; //!< \brief The gradient type of an inactive hovered button. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue buttonBackgroundInactiveGradientEnd; Ogre::ColourValue buttonText; //!< \brief The text colour of a button. Ogre::ColourValue buttonTextInactive; //!< \brief The text colour of an inactive button. size_t buttonTextSize; Ogre::ColourValue buttonBorder; //!< \brief The border colour of a button. Ogre::ColourValue buttonBorderHighlight; //!< \brief The border colour of a highlight button. Ogre::ColourValue buttonBorderInactive; //!< \brief The border colour of an inactive button. size_t buttonBorderSize; //!< \brief The border size of a button. /** * * Checkbox configuration * */ Ogre::String checkboxOveredBackgroundSpriteName; Ogre::String checkboxNotOveredBackgroundSpriteName; Ogre::String checkboxCheckedNotOveredBackgroundSpriteName; Ogre::String checkboxCheckedOveredBackgroundSpriteName; char checkboxCheckedSymbol; Gorilla::Gradient checkboxOveredGradientType; //!< \brief The gradient tye of an overed checkbox. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue checkboxOveredGradientStart; Ogre::ColourValue checkboxOveredGradientEnd; Gorilla::Gradient checkboxNotOveredGradientType; //!< \brief The gradient type of a not overed button. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue checkboxNotOveredGradientStart; Ogre::ColourValue checkboxNotOveredGradientEnd; Gorilla::Gradient checkboxSelectedOveredGradientType; //!< \brief The gradient tye of an overed checkbox. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue checkboxSelectedOveredGradientStart; Ogre::ColourValue checkboxSelectedOveredGradientEnd; Gorilla::Gradient checkboxSelectedNotOveredGradientType; //!< \brief The gradient type of a not overed button. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue checkboxSelectedNotOveredGradientStart; Ogre::ColourValue checkboxSelectedNotOveredGradientEnd; Ogre::ColourValue checkboxText; //!< \brief The text colour of a checked symbol of a checkbox. size_t checkboxTextSize; Ogre::ColourValue checkboxBorder; //!< \brief The border colour of a checkbox. Ogre::ColourValue checkboxBorderHighlight; //!< \brief The border colour of a highlight checkbox. size_t checkboxBorderSize; //!< The border size of a checkbox. /** * * Combobox configuration * */ Ogre::String comboboxButtonPreviousOveredSpriteName; Ogre::String comboboxButtonPreviousNotOveredSpriteName; Ogre::String comboboxButtonPreviousInactiveSpriteName; Ogre::String comboboxButtonPreviousClickedSpriteName; Ogre::String comboboxButtonNextOveredSpriteName; Ogre::String comboboxButtonNextNotOveredSpriteName; Ogre::String comboboxButtonNextInactiveSpriteName; Ogre::String comboboxButtonNextClickedSpriteName; Gorilla::Gradient comboboxBackgroundGradientType; //!< \brief The gradient type of an overed combobox. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue comboboxBackgroundGradientStart; Ogre::ColourValue comboboxBackgroundGradientEnd; Ogre::ColourValue comboboxOveredElement; Ogre::ColourValue comboboxNotOveredElement; Ogre::ColourValue comboboxSelectedElement; Ogre::ColourValue comboboxText; //!< \brief The text colour of combobox elements size_t comboboxTextSize; Ogre::ColourValue comboboxBorder; //!< \brief The border colour of a combobox Ogre::ColourValue comboboxBorderHighlight; //!< \brief The border colour of a highlight combobox size_t comboboxBorderSize; //!< \brief The border size of a combobox /** * * InlineSelector configuration * */ Ogre::String inlineselectorButtonPreviousOveredSpriteName; Ogre::String inlineselectorButtonPreviousNotOveredSpriteName; Ogre::String inlineselectorButtonPreviousInactiveSpriteName; Ogre::String inlineselectorButtonPreviousClickedSpriteName; Ogre::String inlineselectorButtonNextOveredSpriteName; Ogre::String inlineselectorButtonNextNotOveredSpriteName; Ogre::String inlineselectorButtonNextInactiveSpriteName; Ogre::String inlineselectorButtonNextClickedSpriteName; Gorilla::Gradient inlineselectorBackgroundGradientType; //!< \brief The gradient type of an inline selector. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue inlineselectorBackgroundGradientStart; Ogre::ColourValue inlineselectorBackgroundGradientEnd; Ogre::ColourValue inlineselectorText; //!< \brief The text colour of an inline selector size_t inlineselectorTextSize; Ogre::ColourValue inlineselectorBorder; //!< \brief The border colour of an inline selector Ogre::ColourValue inlineselectorBorderHighlight; //!< \brief The border colour of a highlight inline selector size_t inlineselectorBorderSize; //!< \brief The border size of an inline selector /** * * Listbox configuration * */ Ogre::String listboxButtonPreviousOveredSpriteName; Ogre::String listboxButtonPreviousNotOveredSpriteName; Ogre::String listboxButtonPreviousInactiveSpriteName; Ogre::String listboxButtonPreviousClickedSpriteName; Ogre::String listboxButtonNextOveredSpriteName; Ogre::String listboxButtonNextNotOveredSpriteName; Ogre::String listboxButtonNextInactiveSpriteName; Ogre::String listboxButtonNextClickedSpriteName; Gorilla::Gradient listboxBackgroundGradientType; //!< \brief The gradient type of an overed combobox. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue listboxBackgroundGradientStart; Ogre::ColourValue listboxBackgroundGradientEnd; Ogre::ColourValue listboxOveredElement; Ogre::ColourValue listboxNotOveredElement; Ogre::ColourValue listboxOveredSelectedElement; Ogre::ColourValue listboxNotOveredSelectedElement; Ogre::ColourValue listboxText; //!< \brief The text colour of combobox elements size_t listboxTextSize; Ogre::ColourValue listboxBorder; //!< \brief The border colour of a combobox Ogre::ColourValue listboxBorderHighlight; //!< \brief The border colour of a highlight combobox size_t listboxBorderSize; //!< \brief The border size of a combobox /** * * Scrollbar configuration * */ Ogre::String scrollbarCursorNotOveredSpriteName; Ogre::String scrollbarCursorOveredSpriteName; Ogre::String scrollbarCursorSelectedSpriteName; Gorilla::Gradient scrollbarBackgroundGradientType; //!< \brief The gradient type of a scrollbar background. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue scrollbarBackgroundGradientStart; Ogre::ColourValue scrollbarBackgroundGradientEnd; Gorilla::Gradient scrollbarProgressbarGradientType; //!< \brief The gradient type of a scrollbar bar. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue scrollbarProgressbarGradientStart; Ogre::ColourValue scrollbarProgressbarGradientEnd; Gorilla::Gradient scrollbarCursorOveredGradientType; //!< \brief The gradient type of a scrollbar overed cursor. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue scrollbarCursorOveredGradientStart; Ogre::ColourValue scrollbarCursorOveredGradientEnd; Gorilla::Gradient scrollbarCursorNotOveredGradientType; //!< \brief The gradient type of a scrollbar not overed cursor. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue scrollbarCursorNotOveredGradientStart; Ogre::ColourValue scrollbarCursorNotOveredGradientEnd; Gorilla::Gradient scrollbarCursorSelectedGradientType; //!< \brief The gradient type of a scrollbar selected cursor. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue scrollbarCursorSelectedGradientStart; Ogre::ColourValue scrollbarCursorSelectedGradientEnd; Ogre::ColourValue scrollbarText; //!< \brief The text colour of a scrollbar. size_t scrollbarTextSize; Ogre::ColourValue scrollbarBorder; //!< \brief The border colour of a scrollbar. Ogre::ColourValue scrollbarBorderHighlight; //!< \brief The border colour of a highlight scrollbar. Ogre::ColourValue scrollbarCursorBorder; //!< \brief The border colour of a scrollbar cursor. size_t scrollbarBorderSize; //!< \brief The border size of a scrollbar. size_t scrollbarCursorBorderSize; //!< \brief The border size of a cursor scrollbar. /** * * Textzone configuration * */ Gorilla::Gradient textzoneBackgroundOveredGradientType; //!< \brief The gradient type of a overed textzone. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue textzoneBackgroundOveredGradientStart; Ogre::ColourValue textzoneBackgroundOveredGradientEnd; Gorilla::Gradient textzoneBackgroundNotOveredGradientType; //!< \brief The gradient type of a not overed textzone. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue textzoneBackgroundNotOveredGradientStart; Ogre::ColourValue textzoneBackgroundNotOveredGradientEnd; Gorilla::Gradient textzoneBackgroundSelectedGradientType; //!< \brief The gradient type of a selected textzone. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue textzoneBackgroundSelectedGradientStart; Ogre::ColourValue textzoneBackgroundSelectedGradientEnd; Ogre::ColourValue textzoneText; //!< \brief The text colour of a textzone. size_t textzoneTextSize; Ogre::ColourValue textzoneBorder; //!< \brief The border colour of a textzone. Ogre::ColourValue textzoneBorderHighlight; //!< \brief The border colour of a highlight textzone. Ogre::ColourValue textzoneBorderSelected; //!< \brief The border colour of a selected textzone. size_t textzoneBorderSize; //!< \brief The border size of a textzone. /** * * Caption configuration * */ Ogre::String captionBackgroundSpriteName; Gorilla::Gradient captionBackgroundGradientType; //!< \brief The gradient type of a caption. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue captionBackgroundGradientStart; Ogre::ColourValue captionBackgroundGradientEnd; Ogre::ColourValue captionText; //!< \brief The text colour of a caption. size_t captionTextSize; Ogre::ColourValue captionBorder; //!< \brief The border colour of a caption. size_t captionBorderSize; //!< \brief The border size of a caption. /** * * ProgressBar configuration * */ Gorilla::Gradient progressbarBackgroundGradientType; //!< \brief The gradient type of a progressbar background. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue progressbarBackgroundGradientStart; Ogre::ColourValue progressbarBackgroundGradientEnd; Gorilla::Gradient progressbarLoadingBarGradientType; //!< \brief The gradient type of a progressbar loadingbar background. If you want a single color, set the gradient to whatever type you want and the same colors for gradientStart and gradientEnd. Ogre::ColourValue progressbarLoadingBarGradientStart; Ogre::ColourValue progressbarLoadingBarGradientEnd; Ogre::ColourValue progressbarText; //!< \brief The text colour of a progressbar. size_t progressbarTextSize; //!< \brief The text colour of a caption. Ogre::ColourValue progressbarBorder; //!< \brief The border colour of a progressbar. Ogre::ColourValue progressbarBorderHighlight; //!< \brief The border colour of a highlight progressbar. size_t progressbarBorderSize; //!< \brief The border size of a progressbar. }; } #endif
[ "farris.shane@gmail.com" ]
farris.shane@gmail.com
f9c730498b25b321f42a34e203390bb1e1ab9deb
37251aeeec224175f66efda2158843859e755f16
/int.cpp
4dee6d926db75198c8816a5d3d96b81c015b6b0a
[]
no_license
DelowarHossen45/Algorithm
17062e603e3cb78b3acd0c47c7a74376796ba3ea
22be5e0db8a4f9cf142f087a9e123eb4a8de4829
refs/heads/master
2020-03-30T10:29:00.235806
2018-12-05T02:16:47
2018-12-05T02:16:47
151,121,884
0
0
null
null
null
null
UTF-8
C++
false
false
401
cpp
#include <iostream> #include <fstream> using namespace std; int main(){ char text[200]; fstream file; file.open ("example.txt", ios::out | ios::in ); cout << "Write text to be written on file." << endl; cin.getline(text, 3); // Writing on file file << text << endl; // Reding from file file >> text; cout << text << endl; //closing the file file.close(); return 0; }
[ "applecse25@gmail.com" ]
applecse25@gmail.com
7326266b8c2fd8a0c2a0b1d88a6f3e1175bcc242
c4a0b017e4c7c34722868c2371c1603981d228b6
/ParticleSystem/ParticleEmitterObjectEditor.h
a438d8743e44bad51e41fb721475cd19d4279229
[ "Zlib" ]
permissive
4ian/GD-Extensions
573e9d7f7a926f00e8dea0d1df977f15db802b05
fe248a51b7e25f071ea0cf1df6bda5c0cc6a9923
refs/heads/master
2021-01-10T20:36:53.839916
2014-06-30T19:34:52
2014-06-30T19:34:52
11,022,885
2
2
null
2014-04-28T12:00:26
2013-06-28T10:20:51
C
UTF-8
C++
false
false
12,773
h
/** Game Develop - Particle System Extension Copyright (c) 2010-2014 Florian Rival (Florian.Rival@gmail.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #if defined(GD_IDE_ONLY) #ifndef PARTICLEEMITTEROBJECTEDITOR_H #define PARTICLEEMITTEROBJECTEDITOR_H //(*Headers(ParticleEmitterObjectEditor) #include <wx/notebook.h> #include <wx/sizer.h> #include <wx/stattext.h> #include <wx/textctrl.h> #include <wx/checkbox.h> #include <wx/spinctrl.h> #include <wx/statline.h> #include <wx/radiobut.h> #include <wx/panel.h> #include <wx/bmpbuttn.h> #include <wx/button.h> #include <wx/dialog.h> #include <wx/clrpicker.h> //*) #include <wx/aui/aui.h> namespace gd { class Project; } class ParticleEmitterObject; namespace gd { class MainFrameWrapper; } class ResourcesEditor; class ParticleEmitterObjectEditor: public wxDialog { public: ParticleEmitterObjectEditor( wxWindow* parent, gd::Project & game_, ParticleEmitterObject & object_, gd::MainFrameWrapper & mainFrameWrapper ); virtual ~ParticleEmitterObjectEditor(); //(*Declarations(ParticleEmitterObjectEditor) wxStaticText* StaticText10; wxTextCtrl* gravityXEdit; wxSpinCtrlDouble* size1RandomnessEdit; wxPanel* Core; wxStaticText* StaticText9; wxStaticText* StaticText53; wxStaticText* rendererParam1Txt; wxStaticText* StaticText45; wxRadioButton* angleMutableCheck; wxColourPickerCtrl* simpleColor1Bt; wxPanel* Panel5; wxSpinCtrlDouble* green2Edit; wxStaticText* StaticText29; wxTextCtrl* frictionEdit; wxCheckBox* infiniteTankCheck; wxStaticText* StaticText37; wxTextCtrl* angle1Edit; wxNotebook* emissionNotebook; wxStaticText* StaticText33; wxStaticText* StaticText13; wxStaticText* StaticText2; wxTextCtrl* tankEdit; wxPanel* Panel4; wxStaticText* StaticText30; wxStaticText* StaticText14; wxRadioButton* blueFixedCheck; wxTextCtrl* simpleFrictionEdit; wxRadioButton* quadCheck; wxRadioButton* additiveRenderingCheck; wxStaticText* StaticText6; wxSpinCtrlDouble* size1Edit; wxTextCtrl* angle2RandomnessEdit; wxTextCtrl* simpleGravityAngleEdit; wxTextCtrl* emitterAngleAEdit; wxStaticText* StaticText40; wxTextCtrl* angle2Edit; wxCheckBox* destroyWhenNoParticlesCheck; wxSpinCtrlDouble* blue2Edit; wxRadioButton* alphaRenderingCheck; wxSpinCtrlDouble* alpha2RandomnessEdit; wxStaticText* StaticText19; wxStaticText* StaticText8; wxStaticText* StaticText38; wxStaticText* StaticText11; wxTextCtrl* lifeTimeMaxEdit; wxStaticText* StaticText18; wxTextCtrl* angle1RandomnessEdit; wxStaticText* StaticText50; wxStaticText* StaticText31; wxPanel* Panel1; wxRadioButton* pointCheck; wxSpinCtrlDouble* red1Edit; wxStaticText* StaticText1; wxStaticText* StaticText58; wxStaticText* StaticText27; wxSpinCtrlDouble* size2RandomnessEdit; wxRadioButton* blueMutableCheck; wxStaticText* StaticText3; wxButton* cancelBt; wxTextCtrl* textureEdit; wxStaticText* StaticText54; wxRadioButton* alphaMutableCheck; wxPanel* Panel6; wxPanel* Panel3; wxStaticText* StaticText56; wxStaticText* StaticText39; wxTextCtrl* gravityZEdit; wxButton* imageBankBt; wxStaticText* StaticText55; wxRadioButton* blueRandomCheck; wxSpinCtrlDouble* blue1Edit; wxRadioButton* redMutableCheck; wxStaticText* StaticText49; wxTextCtrl* emitterDirZEdit; wxSpinCtrlDouble* alpha1Edit; wxRadioButton* sizeMutableCheck; wxStaticText* StaticText5; wxStaticText* StaticText7; wxRadioButton* angleRandomCheck; wxStaticText* StaticText57; wxRadioButton* lineCheck; wxTextCtrl* maxParticleNbEdit; wxRadioButton* redRandomCheck; wxTextCtrl* gravityYEdit; wxRadioButton* greenFixedCheck; wxRadioButton* greenMutableCheck; wxStaticLine* StaticLine1; wxStaticText* StaticText47; wxTextCtrl* lifeTimeMinEdit; wxStaticText* rendererParam2Txt; wxSpinCtrlDouble* alpha2Edit; wxStaticText* StaticText52; wxNotebook* particleNotebook; wxSpinCtrlDouble* red2Edit; wxRadioButton* redFixedCheck; wxRadioButton* alphaRandomCheck; wxStaticText* StaticText28; wxStaticText* StaticText41; wxStaticText* StaticText15; wxStaticText* StaticText12; wxTextCtrl* simpleConeAngleEdit; wxStaticText* textureTxt; wxTextCtrl* emitterAngleBEdit; wxSpinCtrlDouble* alpha1RandomnessEdit; wxStaticText* StaticText35; wxBitmapButton* imageChooseBt; wxTextCtrl* emitterForceMinEdit; wxSpinCtrlDouble* green1Edit; wxPanel* Panel2; wxSpinCtrlDouble* size2Edit; wxTextCtrl* rendererParam2Edit; wxNotebook* gravityNotebook; wxTextCtrl* flowEdit; wxStaticText* StaticText59; wxRadioButton* sizeRandomCheck; wxTextCtrl* zoneRadiusEdit; wxStaticText* StaticText36; wxStaticText* StaticText4; wxStaticText* StaticText17; wxStaticText* StaticText48; wxButton* okBt; wxStaticText* StaticText16; wxTextCtrl* rendererParam1Edit; wxTextCtrl* simpleGravityLengthEdit; wxStaticText* StaticText46; wxStaticText* StaticText51; wxRadioButton* greenRandomCheck; wxColourPickerCtrl* simpleColor2Bt; wxTextCtrl* emitterForceMaxEdit; //*) ResourcesEditor * editorImagesPnl; protected: //(*Identifiers(ParticleEmitterObjectEditor) static const long ID_STATICTEXT7; static const long ID_RADIOBUTTON2; static const long ID_RADIOBUTTON1; static const long ID_RADIOBUTTON3; static const long ID_STATICTEXT9; static const long ID_TEXTCTRL9; static const long ID_STATICTEXT10; static const long ID_TEXTCTRL10; static const long ID_STATICTEXT32; static const long ID_TEXTCTRL13; static const long ID_BITMAPBUTTON1; static const long ID_RADIOBUTTON22; static const long ID_RADIOBUTTON23; static const long ID_STATICTEXT29; static const long ID_TEXTCTRL11; static const long ID_STATICTEXT30; static const long ID_TEXTCTRL12; static const long ID_STATICTEXT31; static const long ID_CHECKBOX1; static const long ID_STATICTEXT3; static const long ID_TEXTCTRL1; static const long ID_STATICTEXT1; static const long ID_TEXTCTRL2; static const long ID_STATICTEXT62; static const long ID_TEXTCTRL24; static const long ID_STATICTEXT40; static const long ID_COLOURPICKERCTRL1; static const long ID_STATICTEXT41; static const long ID_COLOURPICKERCTRL2; static const long ID_PANEL3; static const long ID_RADIOBUTTON6; static const long ID_RADIOBUTTON5; static const long ID_RADIOBUTTON4; static const long ID_STATICTEXT13; static const long ID_SPINCTRL1; static const long ID_STATICTEXT12; static const long ID_CUSTOM1; static const long ID_RADIOBUTTON10; static const long ID_RADIOBUTTON11; static const long ID_RADIOBUTTON12; static const long ID_STATICTEXT18; static const long ID_CUSTOM2; static const long ID_STATICTEXT19; static const long ID_CUSTOM3; static const long ID_RADIOBUTTON7; static const long ID_RADIOBUTTON8; static const long ID_RADIOBUTTON9; static const long ID_STATICTEXT15; static const long ID_CUSTOM4; static const long ID_STATICTEXT16; static const long ID_CUSTOM5; static const long ID_PANEL2; static const long ID_NOTEBOOK1; static const long ID_RADIOBUTTON13; static const long ID_RADIOBUTTON14; static const long ID_STATICTEXT42; static const long ID_CUSTOM12; static const long ID_STATICTEXT61; static const long ID_CUSTOM17; static const long ID_STATICTEXT17; static const long ID_CUSTOM6; static const long ID_CUSTOM7; static const long ID_RADIOBUTTON26; static const long ID_RADIOBUTTON27; static const long ID_STATICTEXT44; static const long ID_TEXTCTRL28; static const long ID_STATICTEXT58; static const long ID_STATICTEXT59; static const long ID_TEXTCTRL27; static const long ID_STATICTEXT60; static const long ID_STATICTEXT20; static const long ID_TEXTCTRL17; static const long ID_TEXTCTRL29; static const long ID_RADIOBUTTON25; static const long ID_RADIOBUTTON24; static const long ID_STATICTEXT43; static const long ID_CUSTOM13; static const long ID_STATICTEXT56; static const long ID_STATICTEXT55; static const long ID_CUSTOM14; static const long ID_STATICTEXT54; static const long ID_STATICTEXT57; static const long ID_STATICTEXT21; static const long ID_CUSTOM8; static const long ID_CUSTOM9; static const long ID_STATICTEXT4; static const long ID_STATICTEXT5; static const long ID_TEXTCTRL6; static const long ID_STATICTEXT6; static const long ID_TEXTCTRL7; static const long ID_STATICTEXT33; static const long ID_TEXTCTRL14; static const long ID_STATICTEXT48; static const long ID_TEXTCTRL22; static const long ID_STATICTEXT49; static const long ID_PANEL5; static const long ID_STATICTEXT34; static const long ID_TEXTCTRL20; static const long ID_STATICTEXT36; static const long ID_STATICTEXT38; static const long ID_TEXTCTRL15; static const long ID_STATICTEXT11; static const long ID_STATICTEXT39; static const long ID_TEXTCTRL16; static const long ID_STATICTEXT14; static const long ID_PANEL4; static const long ID_NOTEBOOK2; static const long ID_STATICTEXT50; static const long ID_TEXTCTRL23; static const long ID_STATICTEXT52; static const long ID_TEXTCTRL25; static const long ID_STATICTEXT53; static const long ID_STATICTEXT51; static const long ID_TEXTCTRL26; static const long ID_PANEL7; static const long ID_STATICTEXT2; static const long ID_TEXTCTRL3; static const long ID_TEXTCTRL4; static const long ID_TEXTCTRL5; static const long ID_STATICTEXT8; static const long ID_TEXTCTRL8; static const long ID_PANEL6; static const long ID_NOTEBOOK3; static const long ID_CHECKBOX2; static const long ID_STATICLINE1; static const long ID_BUTTON3; static const long ID_BUTTON1; static const long ID_BUTTON2; static const long ID_PANEL1; //*) private: //(*Handlers(ParticleEmitterObjectEditor) void OnokBtClick(wxCommandEvent& event); void OncolorBtClick(wxCommandEvent& event); void OnfontBtClick(wxCommandEvent& event); void OnSizeEditChange(wxSpinEvent& event); void OncancelBtClick(wxCommandEvent& event); void OninfiniteTankCheckClick(wxCommandEvent& event); void OnpointCheckSelect(wxCommandEvent& event); void OnLineCheckSelect(wxCommandEvent& event); void OnQuadCheckSelect(wxCommandEvent& event); void OnredFixedCheckSelect(wxCommandEvent& event); void OnredRandomCheckSelect(wxCommandEvent& event); void OngreenFixedCheckSelect(wxCommandEvent& event); void OngreenRandomCheckSelect(wxCommandEvent& event); void OnblueFixedCheckSelect(wxCommandEvent& event); void OnblueRandomCheckSelect(wxCommandEvent& event); void OnalphaFixedCheckSelect(wxCommandEvent& event); void OnalphaRandomCheckSelect(wxCommandEvent& event); void OnsizeRandomCheckSelect(wxCommandEvent& event); void OnsizeNothingCheckSelect(wxCommandEvent& event); void OnangleNothingCheckSelect(wxCommandEvent& event); void OnangleRandomCheckSelect(wxCommandEvent& event); void OnimageChooseBtClick(wxCommandEvent& event); void OnimageBankBtClick(wxCommandEvent& event); void OnsimpleColor1BtColourChanged(wxColourPickerEvent& event); void OnsimpleRadiusEditText(wxCommandEvent& event); void OnsimpleAngleText(wxCommandEvent& event); void OnsimpleConeAngleText(wxCommandEvent& event); void OnsimpleGravityAngleText(wxCommandEvent& event); void OnsimpleFrictionEditText(wxCommandEvent& event); void OnalphaMutableCheckSelect(wxCommandEvent& event); void OnalphaRandomCheckSelect1(wxCommandEvent& event); void OnangleRandomCheckSelect1(wxCommandEvent& event); void OnangleMutableCheckSelect(wxCommandEvent& event); void OnsizeRandomCheckSelect1(wxCommandEvent& event); void OnsizeMutableCheckSelect(wxCommandEvent& event); //*) void PrepareControlsForPointRenderer(); void PrepareControlsForQuadRenderer(); void PrepareControlsForLineRenderer(); gd::Project & game; ParticleEmitterObject & object; wxAuiManager m_mgr; ///< Used to display the image bank editor DECLARE_EVENT_TABLE() }; #endif #endif
[ "Florian.rival@gmail.com" ]
Florian.rival@gmail.com
4ec873c86e62d0fd3a88a962e1f5904683c380db
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/components/dom_distiller/webui/dom_distiller_ui.cc
8bee051aba90af8c5369f6f0e8d5f171bfae8499
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
2,631
cc
// Copyright 2013 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 "components/dom_distiller/webui/dom_distiller_ui.h" #include "components/dom_distiller/core/dom_distiller_constants.h" #include "components/dom_distiller/core/dom_distiller_service.h" #include "components/dom_distiller/webui/dom_distiller_handler.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "grit/components_resources.h" #include "grit/components_strings.h" namespace dom_distiller { DomDistillerUi::DomDistillerUi(content::WebUI* web_ui, DomDistillerService* service, const std::string& scheme) : content::WebUIController(web_ui) { // Set up WebUIDataSource. content::WebUIDataSource* source = content::WebUIDataSource::Create(kChromeUIDomDistillerHost); source->SetDefaultResource(IDR_ABOUT_DOM_DISTILLER_HTML); source->AddResourcePath("about_dom_distiller.css", IDR_ABOUT_DOM_DISTILLER_CSS); source->AddResourcePath("about_dom_distiller.js", IDR_ABOUT_DOM_DISTILLER_JS); source->AddLocalizedString("domDistillerTitle", IDS_DOM_DISTILLER_WEBUI_TITLE); source->AddLocalizedString("addArticleUrl", IDS_DOM_DISTILLER_WEBUI_ENTRY_URL); source->AddLocalizedString("addArticleAddButtonLabel", IDS_DOM_DISTILLER_WEBUI_ENTRY_ADD); source->AddLocalizedString("addArticleFailedLabel", IDS_DOM_DISTILLER_WEBUI_ENTRY_ADD_FAILED); source->AddLocalizedString("viewUrlButtonLabel", IDS_DOM_DISTILLER_WEBUI_VIEW_URL); source->AddLocalizedString("viewUrlFailedLabel", IDS_DOM_DISTILLER_WEBUI_VIEW_URL_FAILED); source->AddLocalizedString("loadingEntries", IDS_DOM_DISTILLER_WEBUI_FETCHING_ENTRIES); source->AddLocalizedString("refreshButtonLabel", IDS_DOM_DISTILLER_WEBUI_REFRESH); content::BrowserContext* browser_context = web_ui->GetWebContents()->GetBrowserContext(); content::WebUIDataSource::Add(browser_context, source); source->SetJsonPath("strings.js"); // Add message handler. web_ui->AddMessageHandler(new DomDistillerHandler(service, scheme)); } DomDistillerUi::~DomDistillerUi() {} } // namespace dom_distiller
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
cb782088029db63f72b80bf7af3dfbf81c15593f
4dbb45758447dcfa13c0be21e4749d62588aab70
/iOS/Libraries/libil2cpp/include/icalls/System/System.Threading/Semaphore.h
644bcddedd837b06b107cb5ffcf7aaec1dbc3439
[ "MIT" ]
permissive
mopsicus/unity-share-plugin-ios-android
6dd6ccd2fa05c73f0bf5e480a6f2baecb7e7a710
3ee99aef36034a1e4d7b156172953f9b4dfa696f
refs/heads/master
2020-12-25T14:38:03.861759
2016-07-19T10:06:04
2016-07-19T10:06:04
63,676,983
12
0
null
null
null
null
UTF-8
C++
false
false
723
h
#pragma once #include <stdint.h> #include "il2cpp-config.h" #include "object-internals.h" struct Il2CppString; namespace il2cpp { namespace icalls { namespace System { namespace System { namespace Threading { class LIBIL2CPP_CODEGEN_API Semaphore { public: static Il2CppIntPtr CreateSemaphore_internal(int32_t initialCount, int32_t maximumCount, Il2CppString* name, bool* created); static int32_t ReleaseSemaphore_internal(Il2CppIntPtr handlePtr, int32_t releaseCount, bool* fail); static Il2CppIntPtr OpenSemaphore_internal(Il2CppString* name, int32_t rights, int32_t* error); }; } /* namespace Threading */ } /* namespace System */ } /* namespace System */ } /* namespace icalls */ } /* namespace il2cpp */
[ "lii@rstgames.com" ]
lii@rstgames.com
e7964b988b40eef524381b007d4d14085509ca27
39d1f586447ed9c48c805350e3b0abcaeb52dc07
/BASIC/ARRAYS/max_Sum_SubArray(n)_kadane.cpp
3ca29d62333997a52d14115250833a6eca746bc1
[]
no_license
vaarigupta/OOPS_DS_ALGO
80e3123f59b09c10e0b2750130b5554d9a7690a0
921756a9ef5a4b99c610bb9803776940d072438f
refs/heads/master
2022-06-15T04:35:21.238885
2022-06-10T20:00:00
2022-06-10T20:00:00
132,237,189
1
1
null
2019-12-06T19:35:57
2018-05-05T10:20:30
C++
UTF-8
C++
false
false
415
cpp
#include<iostream> using namespace std; int main() { int n ,a[50], currSum=0 , maxSum=0; cout<<"Enter range : "; cin>>n; for(int i =0;i<n;i++) { cin>>a[i]; } for(int i =0;i<n;i++) { currSum += a[i]; if(currSum<0) { currSum =0; } maxSum = max(currSum,maxSum); } cout<<endl<<"Maximum Sum of SubArray : "<<maxSum; return 0; }
[ "vaarigupta24@gmail.com" ]
vaarigupta24@gmail.com
c351964042f52a9348085bab9dbe382df9f845ae
8aa7d98443c4a76e6ab421d325881e374ed92f3f
/arduino_code/squirrel_odomomtry/squirrel_odomomtry.ino
697b228ada5f3ef2cee03529d9699c2d5d8a3f28
[]
no_license
bdemere/TRIN_EARL
c5bdd4f3868540b89f9f2a5264f2cdbd483258c8
b399a371b2a733c366a6ee0afbaaf20c1e6c36e7
refs/heads/master
2021-01-25T10:21:00.461262
2018-02-23T19:48:51
2018-02-23T19:48:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,428
ino
#include <ros.h> #include <std_msgs/Float32.h> #include <std_msgs/Int16.h> // pins const byte motorLeft = 2; const byte motorRight = 3; // reset int reset_at = 200; // counters long countLeft = 0; long countRight = 0; // time diffs long start = 0; // number of counts of holes per second float cpsLeft = 0; float cpsRight = 0; // ros related std_msgs::Float32 vLeft, vRight; ros::Publisher ard_cpsR("ard_cpsR", &vRight); ros::Publisher ard_cpsL("ard_cpsL", &vLeft); ros::NodeHandle nh; void setup() { // set pins pinMode(motorLeft, INPUT_PULLUP); pinMode(motorRight, INPUT_PULLUP); // attach interrupt handler to digital pints attachInterrupt(digitalPinToInterrupt(motorLeft), counterLeft, CHANGE); attachInterrupt(digitalPinToInterrupt(motorRight), counterRight, CHANGE); start = millis(); nh.initNode(); nh.advertise(ard_cpsR); nh.advertise(ard_cpsL); } void loop() { // reset left count every 200 millis if (millis() - start > 200) { cpsLeft = (countLeft/double(millis()-start) * 1000); cpsRight = (countRight/double(millis()-start) * 1000); start = millis(); countLeft = 0; countRight = 0; vLeft.data = cpsLeft; ard_cpsL.publish(&vLeft); vRight.data = cpsRight; ard_cpsR.publish(&vRight); } nh.spinOnce(); delay(50); } void counterLeft() { countLeft = countLeft + 1; } void counterRight() { countRight = countRight + 1; }
[ "jinpyo.jeon@trincoll.edu" ]
jinpyo.jeon@trincoll.edu
bc92832420d344bb39f99e44410d97add44cdd81
daff87f0db2b6e43d8df12dd8512a58cfd6ca630
/ClientQT/mainwindow.cpp
b765b3de91e616c5fd48be5c13ac503eae610810
[]
no_license
BharatKJain/Encrypted_Socket_Chat
16255ecf93d61927980d56ee2e070e91848b7603
68c5ef55e42f8c5a6570f0ffb97ca1a0ec41018a
refs/heads/master
2020-06-09T06:29:04.828262
2019-07-01T13:07:20
2019-07-01T13:07:20
193,391,189
2
0
null
2019-06-29T04:39:39
2019-06-23T20:12:25
Makefile
UTF-8
C++
false
false
2,553
cpp
#include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <netdb.h> #include "mainwindow.h" #include "ui_mainwindow.h" #include <QPushButton> #include <QTextEdit> #include <QLabel> #include <iostream> #include <stdio.h> #include <string.h> #define PORT 8080 #define MAX 80 using namespace std; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { QString text=ui->textEdit_2->toPlainText(); QByteArray ba = text.toLocal8Bit(); char str[10],*c_str2 = ba.data(); strcpy(Message,c_str2); send(sock , Message , strlen(Message) , 0 ); std::cout<<c_str2; char buff[1024]; bzero(buff, MAX); // read the message from client and copy it in buffer read(sock, buff, sizeof(buff)); // print buffer which contains the client contents ui->textEdit_3->append(QString("Message Count: ")); sprintf(str,"%d",mcount); ui->textEdit_3->append(QString(str)); mcount++; ui->textEdit_3->append(QString("Message: ")); ui->textEdit_3->append(QString(buff)); //ui->textEdit->append(QString("\nEnter Data for Server : ")); bzero(buff, MAX); return; } void MainWindow::on_pushButton_2_clicked() { //char *hello = "Hello from client"; //char buffer[1024] = {0}; //int valread; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { cout<<"\n Socket creation error \n"; ui->textEdit->append(QString("Socket Creation Error!")); return; } else { ui->textEdit->append(QString("Socket Created!")); } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); // Convert IPv4 and IPv6 addresses from text to binary form if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) { cout<<"\nInvalid address/ Address not supported \n"; ui->textEdit->append(QString("Invalid address// Address not supported \\")); return ; } else { ui->textEdit->append(QString("Valid Address...")); } if (::connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { cout<<"\nConnection Failed \n"; ui->textEdit->append(QString("Connection Failed")); return; } else { ui->textEdit->append(QString("Connection Successful!")); } ui->textEdit->append(QString("Enter Data for Server...")); mcount=1; } void MainWindow::on_pushButton_3_clicked() { ::close(sock); }
[ "noreply@github.com" ]
noreply@github.com
bac32a0eff0c227a29841d14abceb83d4e089829
74837c92508b3190f8639564eaa7fa4388679f1d
/xic/src/cd/cd_scriptout.cc
9ebe89e0337b7341de5bbd61d23dea20f63b8c89
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
frankhoff/xictools
35d49a88433901cc9cb88b1cfd3e8bf16ddba71c
9ff0aa58a5f5137f8a9e374a809a1cb84bab04fb
refs/heads/master
2023-03-21T13:05:38.481014
2022-09-18T21:51:41
2022-09-18T21:51:41
197,598,973
1
0
null
2019-07-18T14:07:13
2019-07-18T14:07:13
null
UTF-8
C++
false
false
18,488
cc
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the License. * * * * 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 NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY 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. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * Xic Integrated Circuit Layout and Schematic Editor * * * *========================================================================* $Id:$ *========================================================================*/ #include "cd.h" #include "cd_types.h" #include "cd_hypertext.h" #include "cd_propnum.h" #include "cd_lgen.h" #include "cd_objects.h" #include "cd_cell.h" #include "cd_instance.h" #include "miscutil/errorrec.h" struct CDscriptOut { CDscriptOut() { so_sdesc = 0; so_fp = 0; so_pfx = 0; so_newlyr = false; } bool write(const CDs*, FILE*, const char*); private: bool writeBox(const CDo*); bool writePoly(const CDo*); bool writeWire(const CDo*); bool writeLabel(const CDo*); bool writeInst(const CDo*); CDp *cellProperties(); CDp *objProperties(const CDo*); void getRefPt(const CDs *sdesc, const CDc*, int*, int*); const CDs *so_sdesc; FILE *so_fp; const char *so_pfx; bool so_newlyr; }; // Write out the content of the cell in the form of script functions // that will create the features when executed. The pfx if not null // or empty is prepended to non-pcell instance names. // bool CDs::writeScript(FILE *fp, const char *pfx) const { CDscriptOut so; return (so.write(this, fp, pfx)); } bool CDscriptOut::write(const CDs *sd, FILE *fp, const char *pfx) { if (!sd) { Errs()->add_error("write: null cell descriptor"); return (false); } if (!fp) { Errs()->add_error("write: null file pointer"); return (false); } so_sdesc = sd; so_fp = fp; so_pfx = pfx; // Write cell properties CDp *p0 = cellProperties(); while (p0) { fprintf(so_fp, "AddCellProperty(%d, \"%s\")\n", p0->value(), p0->string()); CDp *px = p0; p0 = p0->next_prp(); delete px; } fprintf(fp, "mkscr_sy = IsShowSymbolic()\n"); fprintf(fp, "if (mkscr_sy != 0)\n SetSymbolicFast(FALSE)\nend\n"); CDl *ld; CDlgen lgen(so_sdesc->displayMode(), CDlgen::BotToTopWithCells); fprintf(so_fp, "mkscr_indx = GetCurLayerIndex()\n"); while ((ld = lgen.next()) != 0) { so_newlyr = true; CDg gdesc; gdesc.init_gen(so_sdesc, ld); CDo *odesc; while ((odesc = gdesc.next()) != 0) { bool ret = true; if (odesc->type() == CDBOX) ret = writeBox(odesc); else if (odesc->type() == CDPOLYGON) ret = writePoly(odesc); else if (odesc->type() == CDWIRE) ret = writeWire(odesc); else if (odesc->type() == CDLABEL) ret = writeLabel(odesc); else if (odesc->type() == CDINSTANCE) ret = writeInst(odesc); if (!ret) { Errs()->add_error("writeScript: write to disk failed"); return (false); } } } fprintf(so_fp, "if (mkscr_sy != 0)\n SetSymbolicFast(TRUE)\nend\n"); fprintf(so_fp, "SetCurLayerFast(mkscr_indx)\n"); return (true); } bool CDscriptOut::writeBox(const CDo *odesc) { if (!odesc) return (false); CDl *ld = odesc->ldesc(); if (so_newlyr) { fprintf(so_fp, "SetCurLayerFast(\"%s\")\n", ld->name()); so_newlyr = false; } CDp *p0 = objProperties(odesc); int ret = 0; if (p0) { fprintf(so_fp, "mkscr_h = BoxH(%.5f, %.5f, %.5f, %.5f)\n", MICRONS(odesc->oBB().left), MICRONS(odesc->oBB().bottom), MICRONS(odesc->oBB().right), MICRONS(odesc->oBB().top)); while (p0) { fprintf(so_fp, "PrptyAdd(mkscr_h, %d, \"%s\")\n", p0->value(), p0->string()); CDp *px = p0; p0 = p0->next_prp(); delete px; } ret = fprintf(so_fp, "Close(mkscr_h)\n"); } else { ret = fprintf(so_fp, "Box(%.5f, %.5f, %.5f, %.5f)\n", MICRONS(odesc->oBB().left), MICRONS(odesc->oBB().bottom), MICRONS(odesc->oBB().right), MICRONS(odesc->oBB().top)); } return (ret >= 0); } bool CDscriptOut::writePoly(const CDo *odesc) { if (!odesc) return (false); CDpo *p = (CDpo*)odesc; if (so_newlyr) { CDl *ld = odesc->ldesc(); fprintf(so_fp, "SetCurLayerFast(\"%s\")\n", ld->name()); so_newlyr = false; } int numpts = p->numpts(); const Point *pts = p->points(); fprintf(so_fp, "mkscr_ary[0] = \\\n ["); int j = 0; int ret = 0; for (int i = 0; i < numpts; i++) { j++; fprintf(so_fp, "%.5f,%.5f", MICRONS(pts[i].x), MICRONS(pts[i].y)); if (i == numpts-1) fprintf(so_fp, "]\n"); else if (j == 4) { fprintf(so_fp, ",\\\n "); j = 0; } else fprintf(so_fp, ", "); } CDp *p0 = objProperties(odesc); if (p0) { fprintf(so_fp, "mkscr_h = PolygonH(%d, mkscr_ary)\n", numpts); while (p0) { fprintf(so_fp, "PrptyAdd(mkscr_h, %d, \"%s\")\n", p0->value(), p0->string()); CDp *px = p0; p0 = p0->next_prp(); delete px; } ret = fprintf(so_fp, "Close(mkscr_h)\n"); } else ret = fprintf(so_fp, "Polygon(%d, mkscr_ary)\n", numpts); return (ret >= 0); } bool CDscriptOut::writeWire(const CDo *odesc) { if (!odesc) return (false); CDw *w = (CDw*)odesc; if (so_newlyr) { CDl *ld = odesc->ldesc(); fprintf(so_fp, "SetCurLayerFast(\"%s\")\n", ld->name()); so_newlyr = false; } int numpts = w->numpts(); const Point *pts = w->points(); fprintf(so_fp, "mkscr_ary[0] = \\\n ["); int j = 0; int ret = 0; for (int i = 0; i < numpts; i++) { j++; fprintf(so_fp, "%.5f,%.5f", MICRONS(pts[i].x), MICRONS(pts[i].y)); if (i == numpts-1) fprintf(so_fp, "]\n"); else if (j == 4) { fprintf(so_fp, ",\\\n "); j = 0; } else fprintf(so_fp, ", "); } CDp *p0 = objProperties(odesc); if (p0) { fprintf(so_fp, "mkscr_h = WireH(%.5f, %d, mkscr_ary, %d)\n", MICRONS(w->wire_width()), numpts, w->wire_style()); while (p0) { fprintf(so_fp, "PrptyAdd(mkscr_h, %d, \"%s\")\n", p0->value(), p0->string()); CDp *px = p0; p0 = p0->next_prp(); delete px; } ret = fprintf(so_fp, "Close(mkscr_h)\n"); } else { ret = fprintf(so_fp, "Wire(%.5f, %d, mkscr_ary, %d)\n", MICRONS(w->wire_width()), numpts, w->wire_style()); } return (ret >= 0); } bool CDscriptOut::writeLabel(const CDo *odesc) { if (!odesc) return (false); CDla *l = (CDla*)odesc; if (so_sdesc->isElectrical() && l->prpty(P_LABRF)) return (true); if (so_newlyr) { CDl *ld = odesc->ldesc(); fprintf(so_fp, "SetCurLayerFast(\"%s\")\n", ld->name()); so_newlyr = false; } char *text = hyList::string(l->label(), HYcvPlain, false); int ret = 0; CDp *p0 = objProperties(odesc); if (p0) { fprintf(so_fp, "mkscr_h = LabelH(\"%s\", %.5f, %.5f, %.5f, 0, %d)\n", text, MICRONS(l->xpos()), MICRONS(l->ypos()), MICRONS(l->width()), l->xform()); while (p0) { fprintf(so_fp, "PrptyAdd(mkscr_h, %d, \"%s\")\n", p0->value(), p0->string()); CDp *px = p0; p0 = p0->next_prp(); delete px; } ret = fprintf(so_fp, "Close(mkscr_h)\n"); } else { ret = fprintf(so_fp, "Label(\"%s\", %.5f, %.5f, %.5f, 0, %d)\n", text, MICRONS(l->xpos()), MICRONS(l->ypos()), MICRONS(l->width()), l->xform()); } delete [] text; return (ret >= 0); } bool CDscriptOut::writeInst(const CDo *odesc) { if (!odesc) return (false); CDc *c = (CDc*)odesc; CDs *msdesc = c->masterCell(); if (!msdesc) return (true); if (so_newlyr) so_newlyr = false; CDap ap(c); CDtx tx(c); int xpos, ypos; getRefPt(msdesc, c, &xpos, &ypos); const BBox *pBB = msdesc->BB(); const char *cn = Tstring(c->cellname()); if (ap.nx > 1 || ap.ny > 1) { fprintf(so_fp, "mkscr_ary[0] = [%d, %d, %.5f, %.5f]\n", ap.nx, ap.ny, MICRONS(ap.dx - pBB->width()), MICRONS(ap.dy - pBB->height())); } int ret = 0; char *tfstring = tx.tfstring(); CDp *p0 = objProperties(odesc); if (msdesc->isPCellSubMaster()) { if (msdesc->pcType() == CDpcXic) { // Xic native PCell CDp *pd = msdesc->prpty(XICP_PC); if (pd) { const char *pcname = pd->string(); pd = msdesc->prpty(XICP_PC_PARAMS); const char *params = pd ? pd->string() : 0; fprintf(so_fp, "PlaceSetPCellParams(0, %s, 0, \"%s\")\n", pcname, params); cn = pcname; } } else { // OpenAccess PCell //XXX fixme } // Instantiation should generate correct instance // properties (?) CDp::destroy(p0); ret = fprintf(so_fp, "Place(\"%s\", %.5f, %.5f, 0, %s, FALSE, FALSE, \"%s\")\n", cn, MICRONS(xpos), MICRONS(ypos), ap.nx > 1 || ap.ny > 1 ? "mkscr_ary" : "0", tfstring); } else { bool libdev = msdesc->isElectrical() && msdesc->isLibrary() && msdesc->isDevice(); if (!libdev) { if (so_pfx && *so_pfx) fprintf(so_fp, "TouchCell(%s + \"%s\", FALSE)\n", so_pfx, cn); else fprintf(so_fp, "TouchCell(\"%s\", FALSE)\n", cn); } if (!libdev && (so_pfx && *so_pfx)) { if (p0) fprintf(so_fp, "mkscr_h = PlaceH(%s + ", so_pfx); else fprintf(so_fp, "Place(%s + ", so_pfx); } else { if (p0) fprintf(so_fp, "mkscr_h = PlaceH("); else fprintf(so_fp, "Place("); } ret = fprintf(so_fp, "\"%s\", %.5f, %.5f, 0, %s, FALSE, FALSE, \"%s\")\n", cn, MICRONS(xpos), MICRONS(ypos), ap.nx > 1 || ap.ny > 1 ? "mkscr_ary" : "0", tfstring); bool hadp0 = p0; while (p0) { fprintf(so_fp, "PrptyAdd(mkscr_h, %d, \"%s\")\n", p0->value(), p0->string()); CDp *px = p0; p0 = p0->next_prp(); delete px; } if (hadp0) ret = fprintf(so_fp, "Close(mkscr_h)\n"); } delete [] tfstring; return (ret >= 0); } // Return list of properties of sdesc, as strings. CDp * CDscriptOut::cellProperties() { CDp *p0 = 0, *pe = 0; for (CDp *pd = so_sdesc->prptyList(); pd; pd = pd->next_prp()) { if (prpty_reserved(pd->value())) continue; char *s; if (pd->string(&s)) { if (strchr(s, '"') || strchr(s, '\n')) { sLstr lstr; for (const char *t = s; *t; t++) { if (*t == '"') { lstr.add_c('\\'); lstr.add_c(*t); } else if (*t == '\n') { lstr.add_c('\\'); lstr.add_c('n'); } else lstr.add_c(*t); } delete [] s; s = lstr.string_trim(); } CDp *pn = new CDp(s, pd->value()); delete [] s; if (!p0) p0 = pe = pn; else { pe->set_next_prp(pn); pe = pe->next_prp(); } } } return (p0); } // Return a list of properties to create in the new object. // CDp * CDscriptOut::objProperties(const CDo *odesc) { CDp *p0 = 0, *pe = 0; for (CDp *pd = odesc->prpty_list(); pd; pd = pd->next_prp()) { if (prpty_reserved(pd->value())) continue; if (so_sdesc->isElectrical()) { switch (pd->value()) { case P_MODEL: case P_VALUE: case P_PARAM: case P_OTHER: case P_NOPHYS: case P_SYMBLC: // There are handled directly. break; case P_NODE: // Grab the user-set name, skip if none. { char *s; if (pd->string(&s)) { char *t = s; char *tok = lstring::gettok(&t); delete [] s; t = strchr(tok, ':'); if (t) { t++; CDp *pn = new CDp(t, pd->value()); delete [] tok; if (!p0) p0 = pe = pn; else { pe->set_next_prp(pn); pe = pe->next_prp(); } } } } // fall thru default: continue; } } char *s; if (pd->string(&s)) { if (strchr(s, '"')) { sLstr lstr; for (const char *t = s; *t; t++) { if (*t == '"') { lstr.add_c('\\'); lstr.add_c(*t); } else if (*t == '\n') { lstr.add_c('\\'); lstr.add_c('n'); } else lstr.add_c(*t); } delete [] s; s = lstr.string_trim(); } CDp *pn = new CDp(s, pd->value()); delete [] s; if (!p0) p0 = pe = pn; else { pe->set_next_prp(pn); pe = pe->next_prp(); } } } // Add the NODRC property if necessary if (!so_sdesc->isElectrical() && odesc->type() != CDINSTANCE && odesc->type() != CDLABEL && (odesc->flags() & CDnoDRC)) { CDp *pn = new CDp("NODRC", XICP_NODRC); if (!p0) p0 = pe = pn; else { pe->set_next_prp(pn); pe = pe->next_prp(); } } return (p0); } // The placement position is relative to the coordinate of the 0'th // terminal for electrical mode subcircuits and devices. We need to // find this location and offset the placement accordingly. // void CDscriptOut::getRefPt(const CDs *sdesc, const CDc *cdesc, int *x, int *y) { if (so_sdesc->isElectrical()) { if (sdesc->owner()) sdesc = sdesc->owner(); // Index 0 is the reference point. CDp_snode *pn = (CDp_snode*)sdesc->prpty(P_NODE); for ( ; pn; pn = pn->next()) { if (pn->index() == 0) { if (sdesc->symbolicRep(cdesc)) { if (!pn->get_pos(0, x, y)) continue; } else pn->get_schem_pos(x, y); cTfmStack stk; stk.TPush(); stk.TApplyTransform(cdesc); stk.TPoint(x, y); return; } } } *x = cdesc->posX(); *y = cdesc->posY(); }
[ "stevew@wrcad.com" ]
stevew@wrcad.com
b33f1a640cbf67d20fff9932cae9f70b96a4583c
65330758b4197fc2005293a23a6a09a87e9ea055
/3.cpp
721b02e56f20de3092de286877f24e58524b55da
[]
no_license
J44D17/Trabajo_Laboratorio_2
6343c32775d133bd3309dae4463e2412e9265298
3381aa8db6436c27ebc474052e2bd5906d4f41c2
refs/heads/master
2022-11-06T13:28:34.870785
2020-06-18T16:31:30
2020-06-18T16:31:30
265,361,903
0
0
null
null
null
null
ISO-8859-10
C++
false
false
601
cpp
#include<iostream> using namespace std; int *ordenar(int *,int); int main(){ int *array,*ordenado,size; cout<<"Ingresar el tamaņo del arreglo: ";cin>>size; array=new int[size]; for(int i=0;i<size;i++){ cout<<"Ingrese un elemento al arreglo: ";cin>>array[i]; } ordenar(array,size); for(int j=0;j<size;j++) cout<<array[j]<<","; return 0; } int *ordenar(int *ar,int tamano){ int i,pos,x; for(i=0;i<tamano;i++){ pos = i; x = ar[i]; while((pos>0) && (ar[pos-1] > x)){ ar[pos] = ar[pos-1]; pos--; } ar[pos] = x; } return ar; }
[ "jdiegodiego@outlook.com" ]
jdiegodiego@outlook.com
7487aa5adda7f9149fe2120a0a134da16bcfed21
bd498cbbb28e33370298a84b693f93a3058d3138
/Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/common/primitive_attr.cpp
51e5b1bc8b2a8ee53ea7055b50555cb670b75390
[ "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Zlib", "BSD-2-Clause-Views", "NCSA", "OFL-1.0", "Unlicense", "BSL-1.0", "BSD-2-Clause", "MIT", "Intel" ]
permissive
piyushghai/training_results_v0.7
afb303446e75e3e9789b0f6c40ce330b6b83a70c
e017c9359f66e2d814c6990d1ffa56654a73f5b0
refs/heads/master
2022-12-19T16:50:17.372320
2020-09-24T01:02:00
2020-09-24T18:01:01
298,127,245
0
1
Apache-2.0
2020-09-24T00:27:21
2020-09-24T00:27:21
null
UTF-8
C++
false
false
8,067
cpp
/******************************************************************************* * Copyright 2017-2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "mkldnn.h" #include "c_types_map.hpp" #include "primitive_attr.hpp" #include "type_helpers.hpp" #include "utils.hpp" using namespace mkldnn::impl; using namespace mkldnn::impl::status; using namespace mkldnn::impl::utils; namespace mkldnn { namespace impl { status_t scales_t::set(dim_t count, int mask, const float *scales) { cleanup(); count_ = count; mask_ = mask; if (count_ == 1) { scales_ = scales_buf_; utils::array_set(scales_, scales[0], scales_buf_size); } else { scales_ = (float *)impl::malloc(count_ * sizeof(*scales_), 64); if (scales_ == nullptr) return status::out_of_memory; for (dim_t c = 0; c < count_; ++c) scales_[c] = scales[c]; } return status::success; } } } status_t post_ops_t::append_sum(float scale) { if (len_ == capacity) return out_of_memory; entry_[len_].kind = primitive_kind::sum; entry_[len_].sum.scale = scale; len_++; return success; } status_t post_ops_t::append_eltwise(float scale, alg_kind_t alg, float alpha, float beta) { using namespace mkldnn::impl::alg_kind; bool known_alg = one_of(alg, eltwise_relu, eltwise_tanh, eltwise_elu, eltwise_square, eltwise_abs, eltwise_sqrt, eltwise_linear, eltwise_bounded_relu, eltwise_soft_relu, eltwise_logistic, eltwise_exp, eltwise_gelu); if (!known_alg) return invalid_arguments; if (len_ == capacity) return out_of_memory; entry_[len_].kind = primitive_kind::eltwise; entry_[len_].eltwise.scale = scale; entry_[len_].eltwise.alg = alg; entry_[len_].eltwise.alpha = alpha; entry_[len_].eltwise.beta = beta; len_++; return success; } status_t primitive_attr_t::set_scratchpad_mode( scratchpad_mode_t scratchpad_mode) { using namespace mkldnn::impl::scratchpad_mode; const bool ok = one_of(scratchpad_mode, library, user); if (!ok) return invalid_arguments; scratchpad_mode_ = scratchpad_mode; return success; } status_t primitive_attr_t::set_post_ops(const post_ops_t &post_ops) { this->post_ops_ = post_ops; return success; } /* Public C API */ status_t mkldnn_primitive_attr_create(primitive_attr_t **attr) { if (attr == nullptr) return invalid_arguments; return safe_ptr_assign<mkldnn_primitive_attr>(*attr, new mkldnn_primitive_attr); } status_t mkldnn_primitive_attr_clone(primitive_attr_t **attr, const primitive_attr_t *existing_attr) { if (any_null(attr, existing_attr)) return invalid_arguments; return safe_ptr_assign<mkldnn_primitive_attr>(*attr, existing_attr->clone()); } status_t mkldnn_primitive_attr_destroy(primitive_attr_t *attr) { if (attr) delete attr; return success; } status_t mkldnn_primitive_attr_get_scratchpad_mode( const primitive_attr_t *attr, scratchpad_mode_t *scratchpad_mode) { if (any_null(attr, scratchpad_mode)) return invalid_arguments; *scratchpad_mode = attr->scratchpad_mode_; return success; } status_t mkldnn_primitive_attr_set_scratchpad_mode( primitive_attr_t *attr, scratchpad_mode_t scratchpad_mode) { if (any_null(attr)) return invalid_arguments; return attr->set_scratchpad_mode(scratchpad_mode); } status_t mkldnn_primitive_attr_get_output_scales(const primitive_attr_t *attr, dim_t *count, int *mask, const float **scales) { if (any_null(attr, count, mask, scales)) return invalid_arguments; *count = attr->output_scales_.count_; *mask = attr->output_scales_.mask_; *scales = attr->output_scales_.scales_; return success; } status_t mkldnn_primitive_attr_set_output_scales(primitive_attr_t *attr, dim_t count, int mask, const float *scales) { bool ok = !any_null(attr, scales) && count > 0 && mask >= 0; if (!ok) return invalid_arguments; return attr->output_scales_.set(count, mask, scales); } status_t mkldnn_primitive_attr_get_post_ops(const primitive_attr_t *attr, const post_ops_t **post_ops) { if (any_null(attr, post_ops)) return invalid_arguments; *post_ops = &attr->post_ops_; return success; } status_t mkldnn_primitive_attr_set_post_ops(primitive_attr_t *attr, const post_ops_t *post_ops) { if (any_null(attr, post_ops)) return invalid_arguments; return attr->set_post_ops(*post_ops); } status_t mkldnn_post_ops_create(post_ops_t **post_ops) { if (post_ops == nullptr) return invalid_arguments; return safe_ptr_assign<mkldnn_post_ops>(*post_ops, new mkldnn_post_ops); } status_t mkldnn_post_ops_destroy(post_ops_t *post_ops) { if (post_ops) delete post_ops; return success; } int mkldnn_post_ops_len(const post_ops_t *post_ops) { if (post_ops) return post_ops->len_; return 0; } primitive_kind_t mkldnn_post_ops_get_kind(const post_ops_t *post_ops, int index) { bool ok = post_ops && 0 <= index && index < post_ops->len_; if (!ok) return primitive_kind::undefined; return post_ops->entry_[index].kind; } status_t mkldnn_post_ops_append_sum(post_ops_t *post_ops, float scale) { if (post_ops == nullptr) return invalid_arguments; return post_ops->append_sum(scale); } namespace { bool simple_get_params_check(const post_ops_t *post_ops, int index, primitive_kind_t kind) { bool ok = true && post_ops != nullptr && 0 <= index && index < post_ops->len_ && post_ops->entry_[index].kind == kind; return ok; } } status_t mkldnn_post_ops_get_params_sum(const post_ops_t *post_ops, int index, float *scale) { bool ok = true && simple_get_params_check(post_ops, index, primitive_kind::sum) && !any_null(scale); if (!ok) return invalid_arguments; *scale = post_ops->entry_[index].sum.scale; return success; } status_t mkldnn_post_ops_append_eltwise(post_ops_t *post_ops, float scale, alg_kind_t kind, float alpha, float beta) { if (post_ops == nullptr) return invalid_arguments; return post_ops->append_eltwise(scale, kind, alpha, beta); } status_t mkldnn_post_ops_get_params_eltwise(const post_ops_t *post_ops, int index, float *scale, alg_kind_t *alg, float *alpha, float *beta) { bool ok = true && simple_get_params_check(post_ops, index, primitive_kind::eltwise) && !any_null(scale, alpha, beta); if (!ok) return invalid_arguments; const auto &e = post_ops->entry_[index].eltwise; *scale = e.scale; *alg = e.alg; *alpha = e.alpha; *beta = e.beta; return success; } status_t mkldnn_primitive_attr_set_rnn_data_qparams( primitive_attr_t *attr, const float scale, const float shift) { if (attr == nullptr) return invalid_arguments; return attr->rnn_data_qparams_.set(scale, shift); } status_t mkldnn_primitive_attr_set_rnn_weights_qparams( primitive_attr_t *attr, dim_t count, int mask, const float *scales) { bool ok = !any_null(attr, scales) && count > 0 && mask >= 0; if (!ok) return invalid_arguments; return attr->rnn_weights_qparams_.set(count, mask, scales); }
[ "vbittorf@google.com" ]
vbittorf@google.com
e9cc735ee42c6d0fbbafc72e2a35d695be701438
1caadb05ab160a685f6a3ac7066d9a52df099052
/webview.cpp
499567c0b125eccdb4b9333544076825fe4019a9
[]
no_license
dselig11235/webview
0d5e529d35f40e3d9147ab52d56dbb557b9d7ec6
53af7c6352300d8f427ab2313c19a4076a5173ce
refs/heads/master
2021-01-23T08:20:39.060323
2017-04-05T18:55:08
2017-04-05T18:55:08
86,499,158
0
0
null
null
null
null
UTF-8
C++
false
false
834
cpp
#include "webview.h" #include <QNetworkReply> #include <QtDebug> #include <QSslError> #include <stdlib.h> WebView::WebView(QWidget *parent) : QWebView(parent) { load(QUrl("https://gmail.com")); connect(this, SIGNAL(loadFinished(bool)), this, SLOT(handleLoadFinished(bool))); connect(page()->networkAccessManager(), SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> & )), this, SLOT(handleSslErrors(QNetworkReply*, const QList<QSslError> & ))); } void WebView::handleLoadFinished(bool ok) { printf("LOADED\n"); } void WebView::handleSslErrors(QNetworkReply* reply, const QList<QSslError> &errors) { qDebug() << "handleSslErrors: "; foreach (QSslError e, errors) { qDebug() << "ssl error: " << e; } reply->ignoreSslErrors(); }
[ "root@localhost.localdomain" ]
root@localhost.localdomain
a4b38b68eac86af0fcf605a79344fc46a6862ddd
394dcf6c5c9f3aeaeb514d1d2f1ec01e6eea6425
/src/cryptonote_core/blockchain.cpp
b0fd5fbdac1f5728f7d1893162feb6c4f810d9ed
[ "BSD-3-Clause" ]
permissive
mihailafix/test
41103cccfdce76a25fe6a77537df2824078f3593
98921747cf5dde0bebe1eec20bff43bb53ccff83
refs/heads/master
2020-04-13T05:42:54.335020
2018-12-26T14:22:33
2018-12-26T14:22:33
163,000,718
0
0
null
null
null
null
UTF-8
C++
false
false
176,282
cpp
// Copyright (c) 2014-2018, The Monero Project // Copyright (c) 2018, The Koson Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include <algorithm> #include <cstdio> #include <boost/filesystem.hpp> #include <boost/range/adaptor/reversed.hpp> #include "common/rules.h" #include "include_base_utils.h" #include "cryptonote_basic/cryptonote_basic_impl.h" #include "tx_pool.h" #include "blockchain.h" #include "blockchain_db/blockchain_db.h" #include "cryptonote_basic/cryptonote_boost_serialization.h" #include "cryptonote_core/service_node_deregister.h" #include "cryptonote_config.h" #include "cryptonote_basic/miner.h" #include "misc_language.h" #include "profile_tools.h" #include "file_io_utils.h" #include "common/int-util.h" #include "common/threadpool.h" #include "common/boost_serialization_helper.h" #include "warnings.h" #include "crypto/hash.h" #include "cryptonote_core.h" #include "ringct/rctSigs.h" #include "common/perf_timer.h" #include "common/notify.h" #include "service_node_deregister.h" #include "service_node_list.h" #undef KOSON_DEFAULT_LOG_CATEGORY #define KOSON_DEFAULT_LOG_CATEGORY "blockchain" #define FIND_BLOCKCHAIN_SUPPLEMENT_MAX_SIZE (100*1024*1024) // 100 MB using namespace crypto; //#include "serialization/json_archive.h" /* TODO: * Clean up code: * Possibly change how outputs are referred to/indexed in blockchain and wallets * */ using namespace cryptonote; using epee::string_tools::pod_to_hex; DISABLE_VS_WARNINGS(4267) #define MERROR_VER(x) MCERROR("verify", x) // used to overestimate the block reward when estimating a per kB to use #define BLOCK_REWARD_OVERESTIMATE (10 * 1000000000000) static const struct { uint8_t version; uint64_t height; uint8_t threshold; time_t time; } mainnet_hard_forks[] = { // version 7 from the start of the blockchain, inhereted from Monero mainnet { network_version_7, 1, 0, 1503046577 }, { network_version_8, 3, 0, 1533006000 }, { network_version_9_service_nodes, 10000, 0, 1544743800 }, { network_version_10_bulletproofs, 11000, 0, 1554743800 }, // 2018-12-13 23:30UTC }; static const struct { uint8_t version; uint64_t height; uint8_t threshold; time_t time; } testnet_hard_forks[] = { // version 7 from the start of the blockchain, inhereted from Monero testnet { network_version_7, 1, 0, 1533631121 }, { network_version_8, 3, 0, 1533631122 }, { network_version_9_service_nodes, 5, 0, 1533631123 }, { network_version_10_bulletproofs, 9, 0, 1542681077 }, // 2018-11-20 13:30 AEDT }; static const struct { uint8_t version; uint64_t height; uint8_t threshold; time_t time; } stagenet_hard_forks[] = { // version 7 from the start of the blockchain, inhereted from Monero testnet { network_version_7, 1, 0, 1341378000 }, { network_version_8, 3, 0, 1533006000 }, { network_version_9_service_nodes, 10000, 0, 1536840000 }, { network_version_10_bulletproofs, 11000, 0, 1536840120 }, }; //------------------------------------------------------------------ Blockchain::Blockchain(tx_memory_pool& tx_pool, service_nodes::service_node_list& service_node_list, koson::deregister_vote_pool& deregister_vote_pool): m_db(), m_tx_pool(tx_pool), m_hardfork(NULL), m_timestamps_and_difficulties_height(0), m_current_block_cumul_weight_limit(0), m_current_block_cumul_weight_median(0), m_enforce_dns_checkpoints(false), m_max_prepare_blocks_threads(4), m_db_sync_on_blocks(true), m_db_sync_threshold(1), m_db_sync_mode(db_async), m_db_default_sync(false), m_fast_sync(true), m_show_time_stats(false), m_sync_counter(0), m_bytes_to_sync(0), m_cancel(false), m_difficulty_for_next_block_top_hash(crypto::null_hash), m_difficulty_for_next_block(1), m_service_node_list(service_node_list), m_deregister_vote_pool(deregister_vote_pool), m_btc_valid(false) { LOG_PRINT_L3("Blockchain::" << __func__); } //------------------------------------------------------------------ bool Blockchain::have_tx(const crypto::hash &id) const { LOG_PRINT_L3("Blockchain::" << __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must // lock if it is otherwise needed. return m_db->tx_exists(id); } //------------------------------------------------------------------ bool Blockchain::have_tx_keyimg_as_spent(const crypto::key_image &key_im) const { LOG_PRINT_L3("Blockchain::" << __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must // lock if it is otherwise needed. return m_db->has_key_image(key_im); } //------------------------------------------------------------------ // This function makes sure that each "input" in an input (mixins) exists // and collects the public key for each from the transaction it was included in // via the visitor passed to it. template <class visitor_t> bool Blockchain::scan_outputkeys_for_indexes(size_t tx_version, const txin_to_key& tx_in_to_key, visitor_t &vis, const crypto::hash &tx_prefix_hash, uint64_t* pmax_related_block_height) const { LOG_PRINT_L3("Blockchain::" << __func__); // ND: Disable locking and make method private. //CRITICAL_REGION_LOCAL(m_blockchain_lock); // verify that the input has key offsets (that it exists properly, really) if(!tx_in_to_key.key_offsets.size()) return false; // cryptonote_format_utils uses relative offsets for indexing to the global // outputs list. that is to say that absolute offset #2 is absolute offset // #1 plus relative offset #2. // TODO: Investigate if this is necessary / why this is done. std::vector<uint64_t> absolute_offsets = relative_output_offsets_to_absolute(tx_in_to_key.key_offsets); std::vector<output_data_t> outputs; bool found = false; auto it = m_scan_table.find(tx_prefix_hash); if (it != m_scan_table.end()) { auto its = it->second.find(tx_in_to_key.k_image); if (its != it->second.end()) { outputs = its->second; found = true; } } if (!found) { try { m_db->get_output_key(tx_in_to_key.amount, absolute_offsets, outputs, true); if (absolute_offsets.size() != outputs.size()) { MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount); return false; } } catch (...) { MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount); return false; } } else { // check for partial results and add the rest if needed; if (outputs.size() < absolute_offsets.size() && outputs.size() > 0) { MDEBUG("Additional outputs needed: " << absolute_offsets.size() - outputs.size()); std::vector < uint64_t > add_offsets; std::vector<output_data_t> add_outputs; add_outputs.reserve(absolute_offsets.size() - outputs.size()); for (size_t i = outputs.size(); i < absolute_offsets.size(); i++) add_offsets.push_back(absolute_offsets[i]); try { m_db->get_output_key(tx_in_to_key.amount, add_offsets, add_outputs, true); if (add_offsets.size() != add_outputs.size()) { MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount); return false; } } catch (...) { MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount); return false; } outputs.insert(outputs.end(), add_outputs.begin(), add_outputs.end()); } } size_t count = 0; for (const uint64_t& i : absolute_offsets) { try { output_data_t output_index; try { // get tx hash and output index for output if (count < outputs.size()) output_index = outputs.at(count); else output_index = m_db->get_output_key(tx_in_to_key.amount, i); // call to the passed boost visitor to grab the public key for the output if (!vis.handle_output(output_index.unlock_time, output_index.pubkey, output_index.commitment)) { MERROR_VER("Failed to handle_output for output no = " << count << ", with absolute offset " << i); return false; } } catch (...) { MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount << ", absolute_offset = " << i); return false; } // if on last output and pmax_related_block_height not null pointer if(++count == absolute_offsets.size() && pmax_related_block_height) { // set *pmax_related_block_height to tx block height for this output auto h = output_index.height; if(*pmax_related_block_height < h) { *pmax_related_block_height = h; } } } catch (const OUTPUT_DNE& e) { MERROR_VER("Output does not exist: " << e.what()); return false; } catch (const TX_DNE& e) { MERROR_VER("Transaction does not exist: " << e.what()); return false; } } return true; } //------------------------------------------------------------------ uint64_t Blockchain::get_current_blockchain_height() const { LOG_PRINT_L3("Blockchain::" << __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must // lock if it is otherwise needed. return m_db->height(); } //------------------------------------------------------------------ //FIXME: possibly move this into the constructor, to avoid accidentally // dereferencing a null BlockchainDB pointer bool Blockchain::init(BlockchainDB* db, const network_type nettype, bool offline, const cryptonote::test_options *test_options, difficulty_type fixed_difficulty, const GetCheckpointsCallback& get_checkpoints/* = nullptr*/) { LOG_PRINT_L3("Blockchain::" << __func__); CHECK_AND_ASSERT_MES(nettype != FAKECHAIN || test_options, false, "fake chain network type used without options"); CRITICAL_REGION_LOCAL(m_tx_pool); CRITICAL_REGION_LOCAL1(m_blockchain_lock); if (db == nullptr) { LOG_ERROR("Attempted to init Blockchain with null DB"); return false; } if (!db->is_open()) { LOG_ERROR("Attempted to init Blockchain with unopened DB"); delete db; return false; } m_db = db; m_nettype = test_options != NULL ? FAKECHAIN : nettype; m_offline = offline; m_fixed_difficulty = fixed_difficulty; if (m_hardfork == nullptr) { if (m_nettype == FAKECHAIN || m_nettype == STAGENET) m_hardfork = new HardFork(*db, 7); else if (m_nettype == TESTNET) m_hardfork = new HardFork(*db, 7); else m_hardfork = new HardFork(*db, 7); } if (m_nettype == FAKECHAIN) { for (auto n = 0u; n < test_options->hard_forks.size(); ++n) { const auto& hf = test_options->hard_forks.at(n); m_hardfork->add_fork(hf.first, hf.second, 0, n + 1); } } else if (m_nettype == TESTNET) { for (size_t n = 0; n < sizeof(testnet_hard_forks) / sizeof(testnet_hard_forks[0]); ++n) m_hardfork->add_fork(testnet_hard_forks[n].version, testnet_hard_forks[n].height, testnet_hard_forks[n].threshold, testnet_hard_forks[n].time); } else if (m_nettype == STAGENET) { for (size_t n = 0; n < sizeof(stagenet_hard_forks) / sizeof(stagenet_hard_forks[0]); ++n) m_hardfork->add_fork(stagenet_hard_forks[n].version, stagenet_hard_forks[n].height, stagenet_hard_forks[n].threshold, stagenet_hard_forks[n].time); } else { for (size_t n = 0; n < sizeof(mainnet_hard_forks) / sizeof(mainnet_hard_forks[0]); ++n) m_hardfork->add_fork(mainnet_hard_forks[n].version, mainnet_hard_forks[n].height, mainnet_hard_forks[n].threshold, mainnet_hard_forks[n].time); } m_hardfork->init(); m_db->set_hard_fork(m_hardfork); // if the blockchain is new, add the genesis block // this feels kinda kludgy to do it this way, but can be looked at later. // TODO: add function to create and store genesis block, // taking testnet into account if(!m_db->height()) { MINFO("Blockchain not loaded, generating genesis block."); block bl = boost::value_initialized<block>(); block_verification_context bvc = boost::value_initialized<block_verification_context>(); generate_genesis_block(bl, get_config(m_nettype).GENESIS_TX, get_config(m_nettype).GENESIS_NONCE); add_new_block(bl, bvc); CHECK_AND_ASSERT_MES(!bvc.m_verifivation_failed, false, "Failed to add genesis block to blockchain"); } // TODO: if blockchain load successful, verify blockchain against both // hard-coded and runtime-loaded (and enforced) checkpoints. else { } if (m_nettype != FAKECHAIN) { // ensure we fixup anything we found and fix in the future m_db->fixup(); } m_db->block_txn_start(true); // check how far behind we are uint64_t top_block_timestamp = m_db->get_top_block_timestamp(); uint64_t timestamp_diff = time(NULL) - top_block_timestamp; // genesis block has no timestamp, could probably change it to have timestamp of 1341378000... if(!top_block_timestamp) timestamp_diff = time(NULL) - 1341378000; // create general purpose async service queue m_async_work_idle = std::unique_ptr < boost::asio::io_service::work > (new boost::asio::io_service::work(m_async_service)); // we only need 1 m_async_pool.create_thread(boost::bind(&boost::asio::io_service::run, &m_async_service)); #if defined(PER_BLOCK_CHECKPOINT) if (m_nettype != FAKECHAIN) load_compiled_in_block_hashes(get_checkpoints); #endif MINFO("Blockchain initialized. last block: " << m_db->height() - 1 << ", " << epee::misc_utils::get_time_interval_string(timestamp_diff) << " time ago, current difficulty: " << get_difficulty_for_next_block()); m_db->block_txn_stop(); uint64_t num_popped_blocks = 0; while (!m_db->is_read_only()) { const uint64_t top_height = m_db->height() - 1; const crypto::hash top_id = m_db->top_block_hash(); const block top_block = m_db->get_top_block(); const uint8_t ideal_hf_version = get_ideal_hard_fork_version(top_height); if (ideal_hf_version <= 1 || ideal_hf_version == top_block.major_version) { if (num_popped_blocks > 0) MGINFO("Initial popping done, top block: " << top_id << ", top height: " << top_height << ", block version: " << (uint64_t)top_block.major_version); break; } else { if (num_popped_blocks == 0) MGINFO("Current top block " << top_id << " at height " << top_height << " has version " << (uint64_t)top_block.major_version << " which disagrees with the ideal version " << (uint64_t)ideal_hf_version); if (num_popped_blocks % 100 == 0) MGINFO("Popping blocks... " << top_height); ++num_popped_blocks; block popped_block; std::vector<transaction> popped_txs; try { m_db->pop_block(popped_block, popped_txs); } // anything that could cause this to throw is likely catastrophic, // so we re-throw catch (const std::exception& e) { MERROR("Error popping block from blockchain: " << e.what()); throw; } catch (...) { MERROR("Error popping block from blockchain, throwing!"); throw; } } } if (num_popped_blocks > 0) { m_timestamps_and_difficulties_height = 0; m_hardfork->reorganize_from_chain_height(get_current_blockchain_height()); m_tx_pool.on_blockchain_dec(m_db->height()-1, get_tail_id()); } update_next_cumulative_weight_limit(); for (InitHook* hook : m_init_hooks) hook->init(); return true; } //------------------------------------------------------------------ bool Blockchain::init(BlockchainDB* db, HardFork*& hf, const network_type nettype, bool offline) { if (hf != nullptr) m_hardfork = hf; bool res = init(db, nettype, offline, NULL); if (hf == nullptr) hf = m_hardfork; return res; } //------------------------------------------------------------------ bool Blockchain::store_blockchain() { LOG_PRINT_L3("Blockchain::" << __func__); // lock because the rpc_thread command handler also calls this CRITICAL_REGION_LOCAL(m_db->m_synchronization_lock); TIME_MEASURE_START(save); // TODO: make sure sync(if this throws that it is not simply ignored higher // up the call stack try { m_db->sync(); } catch (const std::exception& e) { MERROR(std::string("Error syncing blockchain db: ") + e.what() + "-- shutting down now to prevent issues!"); throw; } catch (...) { MERROR("There was an issue storing the blockchain, shutting down now to prevent issues!"); throw; } TIME_MEASURE_FINISH(save); if(m_show_time_stats) MINFO("Blockchain stored OK, took: " << save << " ms"); return true; } //------------------------------------------------------------------ bool Blockchain::deinit() { LOG_PRINT_L3("Blockchain::" << __func__); MTRACE("Stopping blockchain read/write activity"); m_service_node_list.store(); m_service_node_list.set_db_pointer(nullptr); // stop async service m_async_work_idle.reset(); m_async_pool.join_all(); m_async_service.stop(); // as this should be called if handling a SIGSEGV, need to check // if m_db is a NULL pointer (and thus may have caused the illegal // memory operation), otherwise we may cause a loop. if (m_db == NULL) { throw DB_ERROR("The db pointer is null in Blockchain, the blockchain may be corrupt!"); } try { m_db->close(); MTRACE("Local blockchain read/write activity stopped successfully"); } catch (const std::exception& e) { LOG_ERROR(std::string("Error closing blockchain db: ") + e.what()); } catch (...) { LOG_ERROR("There was an issue closing/storing the blockchain, shutting down now to prevent issues!"); } delete m_hardfork; m_hardfork = NULL; delete m_db; m_db = NULL; return true; } //------------------------------------------------------------------ // This function tells BlockchainDB to remove the top block from the // blockchain and then returns all transactions (except the miner tx, of course) // from it to the tx_pool block Blockchain::pop_block_from_blockchain() { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); m_timestamps_and_difficulties_height = 0; block popped_block; std::vector<transaction> popped_txs; try { m_db->pop_block(popped_block, popped_txs); } // anything that could cause this to throw is likely catastrophic, // so we re-throw catch (const std::exception& e) { LOG_ERROR("Error popping block from blockchain: " << e.what()); throw; } catch (...) { LOG_ERROR("Error popping block from blockchain, throwing!"); throw; } // return transactions from popped block to the tx_pool for (transaction& tx : popped_txs) { if (!is_coinbase(tx)) { cryptonote::tx_verification_context tvc = AUTO_VAL_INIT(tvc); // FIXME: HardFork // Besides the below, popping a block should also remove the last entry // in hf_versions. // // FIXME: HardFork // This is not quite correct, as we really want to add the txes // to the pool based on the version determined after all blocks // are popped. uint8_t version = get_current_hard_fork_version(); // We assume that if they were in a block, the transactions are already // known to the network as a whole. However, if we had mined that block, // that might not be always true. Unlikely though, and always relaying // these again might cause a spike of traffic as many nodes re-relay // all the transactions in a popped block when a reorg happens. bool r = m_tx_pool.add_tx(tx, tvc, true, true, false, version); if (!r) { LOG_ERROR("Error returning transaction to tx_pool"); } } } m_blocks_longhash_table.clear(); m_scan_table.clear(); m_blocks_txs_check.clear(); m_check_txin_table.clear(); update_next_cumulative_weight_limit(); m_tx_pool.on_blockchain_dec(m_db->height()-1, get_tail_id()); invalidate_block_template_cache(); return popped_block; } //------------------------------------------------------------------ bool Blockchain::reset_and_set_genesis_block(const block& b) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); m_timestamps_and_difficulties_height = 0; m_alternative_chains.clear(); invalidate_block_template_cache(); m_db->reset(); m_hardfork->init(); for (InitHook* hook : m_init_hooks) hook->init(); block_verification_context bvc = boost::value_initialized<block_verification_context>(); add_new_block(b, bvc); update_next_cumulative_weight_limit(); return bvc.m_added_to_main_chain && !bvc.m_verifivation_failed; } //------------------------------------------------------------------ crypto::hash Blockchain::get_tail_id(uint64_t& height) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); height = m_db->height() - 1; return get_tail_id(); } //------------------------------------------------------------------ crypto::hash Blockchain::get_tail_id() const { LOG_PRINT_L3("Blockchain::" << __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must // lock if it is otherwise needed. return m_db->top_block_hash(); } //------------------------------------------------------------------ /*TODO: this function was...poorly written. As such, I'm not entirely * certain on what it was supposed to be doing. Need to look into this, * but it doesn't seem terribly important just yet. * * puts into list <ids> a list of hashes representing certain blocks * from the blockchain in reverse chronological order * * the blocks chosen, at the time of this writing, are: * the most recent 11 * powers of 2 less recent from there, so 13, 17, 25, etc... * */ bool Blockchain::get_short_chain_history(std::list<crypto::hash>& ids) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); uint64_t i = 0; uint64_t current_multiplier = 1; uint64_t sz = m_db->height(); if(!sz) return true; m_db->block_txn_start(true); bool genesis_included = false; uint64_t current_back_offset = 1; while(current_back_offset < sz) { ids.push_back(m_db->get_block_hash_from_height(sz - current_back_offset)); if(sz-current_back_offset == 0) { genesis_included = true; } if(i < 10) { ++current_back_offset; } else { current_multiplier *= 2; current_back_offset += current_multiplier; } ++i; } if (!genesis_included) { ids.push_back(m_db->get_block_hash_from_height(0)); } m_db->block_txn_stop(); return true; } //------------------------------------------------------------------ crypto::hash Blockchain::get_block_id_by_height(uint64_t height) const { LOG_PRINT_L3("Blockchain::" << __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must // lock if it is otherwise needed. try { return m_db->get_block_hash_from_height(height); } catch (const BLOCK_DNE& e) { } catch (const std::exception& e) { MERROR(std::string("Something went wrong fetching block hash by height: ") + e.what()); throw; } catch (...) { MERROR(std::string("Something went wrong fetching block hash by height")); throw; } return null_hash; } //------------------------------------------------------------------ bool Blockchain::get_block_by_hash(const crypto::hash &h, block &blk, bool *orphan) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); // try to find block in main chain try { blk = m_db->get_block(h); if (orphan) *orphan = false; return true; } // try to find block in alternative chain catch (const BLOCK_DNE& e) { blocks_ext_by_hash::const_iterator it_alt = m_alternative_chains.find(h); if (m_alternative_chains.end() != it_alt) { blk = it_alt->second.bl; if (orphan) *orphan = true; return true; } } catch (const std::exception& e) { MERROR(std::string("Something went wrong fetching block by hash: ") + e.what()); throw; } catch (...) { MERROR(std::string("Something went wrong fetching block hash by hash")); throw; } return false; } //------------------------------------------------------------------ // This function aggregates the cumulative difficulties and timestamps of the // last DIFFICULTY_BLOCKS_COUNT blocks and passes them to next_difficulty, // returning the result of that call. Ignores the genesis block, and can use // less blocks than desired if there aren't enough. difficulty_type Blockchain::get_difficulty_for_next_block() { if (m_fixed_difficulty) { return m_db->height() ? m_fixed_difficulty : 1; } LOG_PRINT_L3("Blockchain::" << __func__); crypto::hash top_hash = get_tail_id(); { CRITICAL_REGION_LOCAL(m_difficulty_lock); // we can call this without the blockchain lock, it might just give us // something a bit out of date, but that's fine since anything which // requires the blockchain lock will have acquired it in the first place, // and it will be unlocked only when called from the getinfo RPC if (top_hash == m_difficulty_for_next_block_top_hash) return m_difficulty_for_next_block; } CRITICAL_REGION_LOCAL(m_blockchain_lock); std::vector<uint64_t> timestamps; std::vector<difficulty_type> difficulties; auto height = m_db->height(); uint8_t version = get_current_hard_fork_version(); size_t difficulty_blocks_count = DIFFICULTY_BLOCKS_COUNT_V2; // ND: Speedup // 1. Keep a list of the last 735 (or less) blocks that is used to compute difficulty, // then when the next block difficulty is queried, push the latest height data and // pop the oldest one from the list. This only requires 1x read per height instead // of doing 735 (DIFFICULTY_BLOCKS_COUNT). if (m_timestamps_and_difficulties_height != 0 && ((height - m_timestamps_and_difficulties_height) == 1) && m_timestamps.size() >= difficulty_blocks_count) { uint64_t index = height - 1; m_timestamps.push_back(m_db->get_block_timestamp(index)); m_difficulties.push_back(m_db->get_block_cumulative_difficulty(index)); while (m_timestamps.size() > difficulty_blocks_count) m_timestamps.erase(m_timestamps.begin()); while (m_difficulties.size() > difficulty_blocks_count) m_difficulties.erase(m_difficulties.begin()); m_timestamps_and_difficulties_height = height; timestamps = m_timestamps; difficulties = m_difficulties; } else { size_t offset = height - std::min < size_t > (height, static_cast<size_t>(difficulty_blocks_count)); if (offset == 0) ++offset; timestamps.clear(); difficulties.clear(); if (height > offset) { timestamps.reserve(height - offset); difficulties.reserve(height - offset); } for (; offset < height; offset++) { timestamps.push_back(m_db->get_block_timestamp(offset)); difficulties.push_back(m_db->get_block_cumulative_difficulty(offset)); } m_timestamps_and_difficulties_height = height; m_timestamps = timestamps; m_difficulties = difficulties; } size_t target = get_difficulty_target(); difficulty_type diff; if (version < 8) { diff = next_difficulty_v2(timestamps, difficulties, target); } else { diff = next_difficulty_v3(timestamps, difficulties, target); } CRITICAL_REGION_LOCAL1(m_difficulty_lock); m_difficulty_for_next_block_top_hash = top_hash; m_difficulty_for_next_block = diff; return diff; } //------------------------------------------------------------------ std::vector<time_t> Blockchain::get_last_block_timestamps(unsigned int blocks) const { std::vector<time_t> timestamps(blocks); uint64_t height = m_db->height(); while (blocks--) timestamps[blocks] = m_db->get_block_timestamp(height - blocks - 1); return timestamps; } //------------------------------------------------------------------ // This function removes blocks from the blockchain until it gets to the // position where the blockchain switch started and then re-adds the blocks // that had been removed. bool Blockchain::rollback_blockchain_switching(std::list<block>& original_chain, uint64_t rollback_height) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); // fail if rollback_height passed is too high if (rollback_height > m_db->height()) { return true; } m_timestamps_and_difficulties_height = 0; // remove blocks from blockchain until we get back to where we should be. while (m_db->height() != rollback_height) { pop_block_from_blockchain(); } // Revert all changes from switching to the alt chain before adding the original chain back in for (BlockchainDetachedHook* hook : m_blockchain_detached_hooks) hook->blockchain_detached(rollback_height); // make sure the hard fork object updates its current version m_hardfork->reorganize_from_chain_height(rollback_height); //return back original chain for (auto& bl : original_chain) { block_verification_context bvc = boost::value_initialized<block_verification_context>(); bool r = handle_block_to_main_chain(bl, bvc); CHECK_AND_ASSERT_MES(r && bvc.m_added_to_main_chain, false, "PANIC! failed to add (again) block while chain switching during the rollback!"); } m_hardfork->reorganize_from_chain_height(rollback_height); MINFO("Rollback to height " << rollback_height << " was successful."); if (original_chain.size()) { MINFO("Restoration to previous blockchain successful as well."); } return true; } //------------------------------------------------------------------ // This function attempts to switch to an alternate chain, returning // boolean based on success therein. bool Blockchain::switch_to_alternative_blockchain(std::list<blocks_ext_by_hash::iterator>& alt_chain, bool discard_disconnected_chain) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); m_timestamps_and_difficulties_height = 0; // if empty alt chain passed (not sure how that could happen), return false CHECK_AND_ASSERT_MES(alt_chain.size(), false, "switch_to_alternative_blockchain: empty chain passed"); // verify that main chain has front of alt chain's parent block if (!m_db->block_exists(alt_chain.front()->second.bl.prev_id)) { LOG_ERROR("Attempting to move to an alternate chain, but it doesn't appear to connect to the main chain!"); return false; } // pop blocks from the blockchain until the top block is the parent // of the front block of the alt chain. std::list<block> disconnected_chain; while (m_db->top_block_hash() != alt_chain.front()->second.bl.prev_id) { block b = pop_block_from_blockchain(); disconnected_chain.push_front(b); } auto split_height = m_db->height(); for (BlockchainDetachedHook* hook : m_blockchain_detached_hooks) hook->blockchain_detached(split_height); //connecting new alternative chain for(auto alt_ch_iter = alt_chain.begin(); alt_ch_iter != alt_chain.end(); alt_ch_iter++) { auto ch_ent = *alt_ch_iter; block_verification_context bvc = boost::value_initialized<block_verification_context>(); // add block to main chain bool r = handle_block_to_main_chain(ch_ent->second.bl, bvc); // if adding block to main chain failed, rollback to previous state and // return false if(!r || !bvc.m_added_to_main_chain) { MERROR("Failed to switch to alternative blockchain"); // rollback_blockchain_switching should be moved to two different // functions: rollback and apply_chain, but for now we pretend it is // just the latter (because the rollback was done above). rollback_blockchain_switching(disconnected_chain, split_height); // FIXME: Why do we keep invalid blocks around? Possibly in case we hear // about them again so we can immediately dismiss them, but needs some // looking into. add_block_as_invalid(ch_ent->second, get_block_hash(ch_ent->second.bl)); MERROR("The block was inserted as invalid while connecting new alternative chain, block_id: " << get_block_hash(ch_ent->second.bl)); m_alternative_chains.erase(*alt_ch_iter++); for(auto alt_ch_to_orph_iter = alt_ch_iter; alt_ch_to_orph_iter != alt_chain.end(); ) { add_block_as_invalid((*alt_ch_to_orph_iter)->second, (*alt_ch_to_orph_iter)->first); m_alternative_chains.erase(*alt_ch_to_orph_iter++); } return false; } } // if we're to keep the disconnected blocks, add them as alternates if(!discard_disconnected_chain) { //pushing old chain as alternative chain for (auto& old_ch_ent : disconnected_chain) { block_verification_context bvc = boost::value_initialized<block_verification_context>(); bool r = handle_alternative_block(old_ch_ent, get_block_hash(old_ch_ent), bvc); if(!r) { MERROR("Failed to push ex-main chain blocks to alternative chain "); // previously this would fail the blockchain switching, but I don't // think this is bad enough to warrant that. } } } //removing alt_chain entries from alternative chains container for (auto ch_ent: alt_chain) { m_alternative_chains.erase(ch_ent); } m_hardfork->reorganize_from_chain_height(split_height); MGINFO_GREEN("REORGANIZE SUCCESS! on height: " << split_height << ", new blockchain size: " << m_db->height()); return true; } //------------------------------------------------------------------ // This function calculates the difficulty target for the block being added to // an alternate chain. difficulty_type Blockchain::get_next_difficulty_for_alternative_chain(const std::list<blocks_ext_by_hash::iterator>& alt_chain, block_extended_info& bei) const { if (m_fixed_difficulty) { return m_db->height() ? m_fixed_difficulty : 1; } LOG_PRINT_L3("Blockchain::" << __func__); std::vector<uint64_t> timestamps; std::vector<difficulty_type> cumulative_difficulties; size_t difficulty_blocks_count = DIFFICULTY_BLOCKS_COUNT_V2; // if the alt chain isn't long enough to calculate the difficulty target // based on its blocks alone, need to get more blocks from the main chain if(alt_chain.size()< difficulty_blocks_count) { CRITICAL_REGION_LOCAL(m_blockchain_lock); // Figure out start and stop offsets for main chain blocks size_t main_chain_stop_offset = alt_chain.size() ? alt_chain.front()->second.height : bei.height; size_t main_chain_count = difficulty_blocks_count - std::min(static_cast<size_t>(difficulty_blocks_count), alt_chain.size()); main_chain_count = std::min(main_chain_count, main_chain_stop_offset); size_t main_chain_start_offset = main_chain_stop_offset - main_chain_count; if(!main_chain_start_offset) ++main_chain_start_offset; //skip genesis block // get difficulties and timestamps from relevant main chain blocks for(; main_chain_start_offset < main_chain_stop_offset; ++main_chain_start_offset) { timestamps.push_back(m_db->get_block_timestamp(main_chain_start_offset)); cumulative_difficulties.push_back(m_db->get_block_cumulative_difficulty(main_chain_start_offset)); } // make sure we haven't accidentally grabbed too many blocks...maybe don't need this check? CHECK_AND_ASSERT_MES((alt_chain.size() + timestamps.size()) <= difficulty_blocks_count, false, "Internal error, alt_chain.size()[" << alt_chain.size() << "] + vtimestampsec.size()[" << timestamps.size() << "] NOT <= DIFFICULTY_WINDOW[]" << DIFFICULTY_BLOCKS_COUNT_V2); for (auto it : alt_chain) { timestamps.push_back(it->second.bl.timestamp); cumulative_difficulties.push_back(it->second.cumulative_difficulty); } } // if the alt chain is long enough for the difficulty calc, grab difficulties // and timestamps from it alone else { timestamps.resize(static_cast<size_t>(difficulty_blocks_count)); cumulative_difficulties.resize(static_cast<size_t>(difficulty_blocks_count)); size_t count = 0; size_t max_i = timestamps.size()-1; // get difficulties and timestamps from most recent blocks in alt chain for(auto it: boost::adaptors::reverse(alt_chain)) { timestamps[max_i - count] = it->second.bl.timestamp; cumulative_difficulties[max_i - count] = it->second.cumulative_difficulty; count++; if(count >= difficulty_blocks_count) break; } } // FIXME: This will fail if fork activation heights are subject to voting size_t target = DIFFICULTY_TARGET_V2; // calculate the difficulty target for the block and return it if (get_current_hard_fork_version() < cryptonote::network_version_8) { return next_difficulty_v2(timestamps, cumulative_difficulties, target); } else { return next_difficulty_v3(timestamps, cumulative_difficulties, target); } } //------------------------------------------------------------------ // This function does a sanity check on basic things that all miner // transactions have in common, such as: // one input, of type txin_gen, with height set to the block's height // correct miner tx unlock time // a non-overflowing tx amount (dubious necessity on this check) bool Blockchain::prevalidate_miner_transaction(const block& b, uint64_t height) { LOG_PRINT_L3("Blockchain::" << __func__); CHECK_AND_ASSERT_MES(b.miner_tx.vin.size() == 1, false, "coinbase transaction in the block has no inputs"); CHECK_AND_ASSERT_MES(b.miner_tx.vin[0].type() == typeid(txin_gen), false, "coinbase transaction in the block has the wrong type"); if(boost::get<txin_gen>(b.miner_tx.vin[0]).height != height) { MWARNING("The miner transaction in block has invalid height: " << boost::get<txin_gen>(b.miner_tx.vin[0]).height << ", expected: " << height); return false; } MDEBUG("Miner tx hash: " << get_transaction_hash(b.miner_tx)); CHECK_AND_ASSERT_MES(b.miner_tx.unlock_time == height + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW, false, "coinbase transaction transaction has the wrong unlock time=" << b.miner_tx.unlock_time << ", expected " << height + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW); //check outs overflow //NOTE: not entirely sure this is necessary, given that this function is // designed simply to make sure the total amount for a transaction // does not overflow a uint64_t, and this transaction *is* a uint64_t... if(!check_outs_overflow(b.miner_tx)) { MERROR("miner transaction has money overflow in block " << get_block_hash(b)); return false; } return true; } //------------------------------------------------------------------ // This function validates the miner transaction reward bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_block_weight, uint64_t fee, uint64_t& base_reward, uint64_t already_generated_coins, bool &partial_block_reward, uint8_t version) { LOG_PRINT_L3("Blockchain::" << __func__); //validate reward uint64_t money_in_use = 0; for (auto& o: b.miner_tx.vout) money_in_use += o.amount; partial_block_reward = false; if (b.miner_tx.vout.size() == 0) { MERROR_VER("miner tx has no outputs"); return false; } uint64_t height = cryptonote::get_block_height(b); std::vector<size_t> last_blocks_weights; get_last_n_blocks_weights(last_blocks_weights, CRYPTONOTE_REWARD_BLOCKS_WINDOW); koson_block_reward_context block_reward_context = {}; block_reward_context.fee = fee; block_reward_context.height = height; if (!calc_batched_governance_reward(height, block_reward_context.batched_governance)) { MERROR_VER("Failed to calculate batched governance reward"); return false; } block_reward_parts reward_parts; if (!get_koson_block_reward(epee::misc_utils::median(last_blocks_weights), cumulative_block_weight, already_generated_coins, version, reward_parts, block_reward_context)) { MERROR_VER("block weight " << cumulative_block_weight << " is bigger than allowed for this blockchain"); return false; } for (ValidateMinerTxHook* hook : m_validate_miner_tx_hooks) { if (!hook->validate_miner_tx(b.prev_id, b.miner_tx, m_db->height(), version, reward_parts)) return false; } if (already_generated_coins != 0 && block_has_governance_output(nettype(), b)) { if (version >= network_version_10_bulletproofs && reward_parts.governance == 0) { MERROR("Governance reward should not be 0 after hardfork v10 if this height has a governance output because it is the batched payout height"); return false; } if (b.miner_tx.vout.back().amount != reward_parts.governance) { MERROR("Governance reward amount incorrect. Should be: " << print_money(reward_parts.governance) << ", is: " << print_money(b.miner_tx.vout.back().amount)); return false; } if (!validate_governance_reward_key(m_db->height(), *cryptonote::get_config(m_nettype, version).GOVERNANCE_WALLET_ADDRESS, b.miner_tx.vout.size() - 1, boost::get<txout_to_key>(b.miner_tx.vout.back().target).key, m_nettype)) { MERROR("Governance reward public key incorrect."); return false; } } base_reward = reward_parts.adjusted_base_reward; if(base_reward + fee < money_in_use) { MERROR_VER("coinbase transaction spend too much money (" << print_money(money_in_use) << "). Block reward is " << print_money(base_reward) << "(" << print_money(base_reward) << "+" << print_money(fee) << ")"); return false; } // since a miner can claim less than the full block reward, we update the base_reward // to show the amount of coins that were actually generated, the remainder will be pushed back for later // emission. This modifies the emission curve very slightly. CHECK_AND_ASSERT_MES(money_in_use - fee <= base_reward, false, "base reward calculation bug"); if(base_reward != money_in_use) partial_block_reward = true; base_reward = money_in_use - fee; return true; } //------------------------------------------------------------------ // get the block weights of the last <count> blocks, and return by reference <sz>. void Blockchain::get_last_n_blocks_weights(std::vector<size_t>& weights, size_t count) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); auto h = m_db->height(); // this function is meaningless for an empty blockchain...granted it should never be empty if(h == 0) return; m_db->block_txn_start(true); // add weight of last <count> blocks to vector <weights> (or less, if blockchain size < count) size_t start_offset = h - std::min<size_t>(h, count); weights.reserve(weights.size() + h - start_offset); for(size_t i = start_offset; i < h; i++) { weights.push_back(m_db->get_block_weight(i)); } m_db->block_txn_stop(); } //------------------------------------------------------------------ uint64_t Blockchain::get_current_cumulative_block_weight_limit() const { LOG_PRINT_L3("Blockchain::" << __func__); return m_current_block_cumul_weight_limit; } //------------------------------------------------------------------ uint64_t Blockchain::get_current_cumulative_block_weight_median() const { LOG_PRINT_L3("Blockchain::" << __func__); return m_current_block_cumul_weight_median; } //------------------------------------------------------------------ //TODO: This function only needed minor modification to work with BlockchainDB, // and *works*. As such, to reduce the number of things that might break // in moving to BlockchainDB, this function will remain otherwise // unchanged for the time being. // // This function makes a new block for a miner to mine the hash for // // FIXME: this codebase references #if defined(DEBUG_CREATE_BLOCK_TEMPLATE) // in a lot of places. That flag is not referenced in any of the code // nor any of the makefiles, howeve. Need to look into whether or not it's // necessary at all. bool Blockchain::create_block_template(block& b, const account_public_address& miner_address, difficulty_type& diffic, uint64_t& height, uint64_t& expected_reward, const blobdata& ex_nonce) { LOG_PRINT_L3("Blockchain::" << __func__); size_t median_weight; uint64_t already_generated_coins; uint64_t pool_cookie; CRITICAL_REGION_BEGIN(m_blockchain_lock); height = m_db->height(); if (m_btc_valid) { // The pool cookie is atomic. The lack of locking is OK, as if it changes // just as we compare it, we'll just use a slightly old template, but // this would be the case anyway if we'd lock, and the change happened // just after the block template was created if (!memcmp(&miner_address, &m_btc_address, sizeof(cryptonote::account_public_address)) && m_btc_nonce == ex_nonce && m_btc_pool_cookie == m_tx_pool.cookie()) { MDEBUG("Using cached template"); m_btc.timestamp = time(NULL); // update timestamp unconditionally b = m_btc; diffic = m_btc_difficulty; expected_reward = m_btc_expected_reward; return true; } MDEBUG("Not using cached template: address " << (!memcmp(&miner_address, &m_btc_address, sizeof(cryptonote::account_public_address))) << ", nonce " << (m_btc_nonce == ex_nonce) << ", cookie " << (m_btc_pool_cookie == m_tx_pool.cookie())); invalidate_block_template_cache(); } b.major_version = m_hardfork->get_current_version(); b.minor_version = m_hardfork->get_ideal_version(); b.prev_id = get_tail_id(); b.timestamp = time(NULL); uint64_t median_ts; if (!check_block_timestamp(b, median_ts)) { b.timestamp = median_ts; } diffic = get_difficulty_for_next_block(); CHECK_AND_ASSERT_MES(diffic, false, "difficulty overhead."); median_weight = m_current_block_cumul_weight_limit / 2; already_generated_coins = m_db->get_block_already_generated_coins(height - 1); CRITICAL_REGION_END(); size_t txs_weight; uint64_t fee; if (!m_tx_pool.fill_block_template(b, median_weight, already_generated_coins, txs_weight, fee, expected_reward, m_hardfork->get_current_version(), height)) { return false; } pool_cookie = m_tx_pool.cookie(); #if defined(DEBUG_CREATE_BLOCK_TEMPLATE) size_t real_txs_weight = 0; uint64_t real_fee = 0; CRITICAL_REGION_BEGIN(m_tx_pool.m_transactions_lock); for(crypto::hash &cur_hash: b.tx_hashes) { auto cur_res = m_tx_pool.m_transactions.find(cur_hash); if (cur_res == m_tx_pool.m_transactions.end()) { LOG_ERROR("Creating block template: error: transaction not found"); continue; } tx_memory_pool::tx_details &cur_tx = cur_res->second; real_txs_weight += cur_tx.weight; real_fee += cur_tx.fee; if (cur_tx.weight != get_transaction_weight(cur_tx.tx)) { LOG_ERROR("Creating block template: error: invalid transaction weight"); } if (cur_tx.tx.version == 1) { uint64_t inputs_amount; if (!get_inputs_money_amount(cur_tx.tx, inputs_amount)) { LOG_ERROR("Creating block template: error: cannot get inputs amount"); } else if (cur_tx.fee != inputs_amount - get_outs_money_amount(cur_tx.tx)) { LOG_ERROR("Creating block template: error: invalid fee"); } } else { if (cur_tx.fee != cur_tx.tx.rct_signatures.txnFee) { LOG_ERROR("Creating block template: error: invalid fee"); } } } if (txs_weight != real_txs_weight) { LOG_ERROR("Creating block template: error: wrongly calculated transaction weight"); } if (fee != real_fee) { LOG_ERROR("Creating block template: error: wrongly calculated fee"); } CRITICAL_REGION_END(); MDEBUG("Creating block template: height " << height << ", median weight " << median_weight << ", already generated coins " << already_generated_coins << ", transaction weight " << txs_weight << ", fee " << fee); #endif /* two-phase miner transaction generation: we don't know exact block weight until we prepare block, but we don't know reward until we know block weight, so first miner transaction generated with fake amount of money, and with phase we know think we know expected block weight */ //make blocks coin-base tx looks close to real coinbase tx to get truthful blob weight uint8_t hf_version = m_hardfork->get_current_version(); koson_miner_tx_context miner_tx_context(m_nettype, m_service_node_list.select_winner(b.prev_id), m_service_node_list.get_winner_addresses_and_portions(b.prev_id)); if (!calc_batched_governance_reward(height, miner_tx_context.batched_governance)) { LOG_ERROR("Failed to calculate batched governance reward"); return false; } bool r = construct_miner_tx(height, median_weight, already_generated_coins, txs_weight, fee, miner_address, b.miner_tx, ex_nonce, hf_version, miner_tx_context); CHECK_AND_ASSERT_MES(r, false, "Failed to construct miner tx, first chance"); size_t cumulative_weight = txs_weight + get_transaction_weight(b.miner_tx); #if defined(DEBUG_CREATE_BLOCK_TEMPLATE) MDEBUG("Creating block template: miner tx weight " << get_transaction_weight(b.miner_tx) << ", cumulative weight " << cumulative_weight); #endif for (size_t try_count = 0; try_count != 10; ++try_count) { r = construct_miner_tx(height, median_weight, already_generated_coins, cumulative_weight, fee, miner_address, b.miner_tx, ex_nonce, hf_version, miner_tx_context); CHECK_AND_ASSERT_MES(r, false, "Failed to construct miner tx, second chance"); size_t coinbase_weight = get_transaction_weight(b.miner_tx); if (coinbase_weight > cumulative_weight - txs_weight) { cumulative_weight = txs_weight + coinbase_weight; #if defined(DEBUG_CREATE_BLOCK_TEMPLATE) MDEBUG("Creating block template: miner tx weight " << coinbase_weight << ", cumulative weight " << cumulative_weight << " is greater than before"); #endif continue; } if (coinbase_weight < cumulative_weight - txs_weight) { size_t delta = cumulative_weight - txs_weight - coinbase_weight; #if defined(DEBUG_CREATE_BLOCK_TEMPLATE) MDEBUG("Creating block template: miner tx weight " << coinbase_weight << ", cumulative weight " << txs_weight + coinbase_weight << " is less than before, adding " << delta << " zero bytes"); #endif b.miner_tx.extra.insert(b.miner_tx.extra.end(), delta, 0); //here could be 1 byte difference, because of extra field counter is varint, and it can become from 1-byte len to 2-bytes len. if (cumulative_weight != txs_weight + get_transaction_weight(b.miner_tx)) { CHECK_AND_ASSERT_MES(cumulative_weight + 1 == txs_weight + get_transaction_weight(b.miner_tx), false, "unexpected case: cumulative_weight=" << cumulative_weight << " + 1 is not equal txs_cumulative_weight=" << txs_weight << " + get_transaction_weight(b.miner_tx)=" << get_transaction_weight(b.miner_tx)); b.miner_tx.extra.resize(b.miner_tx.extra.size() - 1); if (cumulative_weight != txs_weight + get_transaction_weight(b.miner_tx)) { //fuck, not lucky, -1 makes varint-counter size smaller, in that case we continue to grow with cumulative_weight MDEBUG("Miner tx creation has no luck with delta_extra size = " << delta << " and " << delta - 1); cumulative_weight += delta - 1; continue; } MDEBUG("Setting extra for block: " << b.miner_tx.extra.size() << ", try_count=" << try_count); } } CHECK_AND_ASSERT_MES(cumulative_weight == txs_weight + get_transaction_weight(b.miner_tx), false, "unexpected case: cumulative_weight=" << cumulative_weight << " is not equal txs_cumulative_weight=" << txs_weight << " + get_transaction_weight(b.miner_tx)=" << get_transaction_weight(b.miner_tx)); #if defined(DEBUG_CREATE_BLOCK_TEMPLATE) MDEBUG("Creating block template: miner tx weight " << coinbase_weight << ", cumulative weight " << cumulative_weight << " is now good"); #endif cache_block_template(b, miner_address, ex_nonce, diffic, expected_reward, pool_cookie); return true; } LOG_ERROR("Failed to create_block_template with " << 10 << " tries"); return false; } //------------------------------------------------------------------ // for an alternate chain, get the timestamps from the main chain to complete // the needed number of timestamps for the BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW. bool Blockchain::complete_timestamps_vector(uint64_t start_top_height, std::vector<uint64_t>& timestamps) { LOG_PRINT_L3("Blockchain::" << __func__); if(timestamps.size() >= BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW) return true; CRITICAL_REGION_LOCAL(m_blockchain_lock); size_t need_elements = BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW - timestamps.size(); CHECK_AND_ASSERT_MES(start_top_height < m_db->height(), false, "internal error: passed start_height not < " << " m_db->height() -- " << start_top_height << " >= " << m_db->height()); size_t stop_offset = start_top_height > need_elements ? start_top_height - need_elements : 0; timestamps.reserve(timestamps.size() + start_top_height - stop_offset); while (start_top_height != stop_offset) { timestamps.push_back(m_db->get_block_timestamp(start_top_height)); --start_top_height; } return true; } //------------------------------------------------------------------ // If a block is to be added and its parent block is not the current // main chain top block, then we need to see if we know about its parent block. // If its parent block is part of a known forked chain, then we need to see // if that chain is long enough to become the main chain and re-org accordingly // if so. If not, we need to hang on to the block in case it becomes part of // a long forked chain eventually. bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id, block_verification_context& bvc) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); m_timestamps_and_difficulties_height = 0; uint64_t block_height = get_block_height(b); if(0 == block_height) { MERROR_VER("Block with id: " << epee::string_tools::pod_to_hex(id) << " (as alternative), but miner tx says height is 0."); bvc.m_verifivation_failed = true; return false; } // this basically says if the blockchain is smaller than the first // checkpoint then alternate blocks are allowed. Alternatively, if the // last checkpoint *before* the end of the current chain is also before // the block to be added, then this is fine. if (!m_checkpoints.is_alternative_block_allowed(get_current_blockchain_height(), block_height)) { MERROR_VER("Block with id: " << id << std::endl << " can't be accepted for alternative chain, block height: " << block_height << std::endl << " blockchain height: " << get_current_blockchain_height()); bvc.m_verifivation_failed = true; return false; } // this is a cheap test if (!m_hardfork->check_for_height(b, block_height)) { LOG_PRINT_L1("Block with id: " << id << std::endl << "has old version for height " << block_height); bvc.m_verifivation_failed = true; return false; } //block is not related with head of main chain //first of all - look in alternative chains container auto it_prev = m_alternative_chains.find(b.prev_id); bool parent_in_main = m_db->block_exists(b.prev_id); if(it_prev != m_alternative_chains.end() || parent_in_main) { //we have new block in alternative chain //build alternative subchain, front -> mainchain, back -> alternative head blocks_ext_by_hash::iterator alt_it = it_prev; //m_alternative_chains.find() std::list<blocks_ext_by_hash::iterator> alt_chain; std::vector<uint64_t> timestamps; while(alt_it != m_alternative_chains.end()) { alt_chain.push_front(alt_it); timestamps.push_back(alt_it->second.bl.timestamp); alt_it = m_alternative_chains.find(alt_it->second.bl.prev_id); } // if block to be added connects to known blocks that aren't part of the // main chain -- that is, if we're adding on to an alternate chain if(alt_chain.size()) { // make sure alt chain doesn't somehow start past the end of the main chain CHECK_AND_ASSERT_MES(m_db->height() > alt_chain.front()->second.height, false, "main blockchain wrong height"); // make sure that the blockchain contains the block that should connect // this alternate chain with it. if (!m_db->block_exists(alt_chain.front()->second.bl.prev_id)) { MERROR("alternate chain does not appear to connect to main chain..."); return false; } // make sure block connects correctly to the main chain auto h = m_db->get_block_hash_from_height(alt_chain.front()->second.height - 1); CHECK_AND_ASSERT_MES(h == alt_chain.front()->second.bl.prev_id, false, "alternative chain has wrong connection to main chain"); complete_timestamps_vector(m_db->get_block_height(alt_chain.front()->second.bl.prev_id), timestamps); } // if block not associated with known alternate chain else { // if block parent is not part of main chain or an alternate chain, // we ignore it CHECK_AND_ASSERT_MES(parent_in_main, false, "internal error: broken imperative condition: parent_in_main"); complete_timestamps_vector(m_db->get_block_height(b.prev_id), timestamps); } // verify that the block's timestamp is within the acceptable range // (not earlier than the median of the last X blocks) if(!check_block_timestamp(timestamps, b)) { MERROR_VER("Block with id: " << id << std::endl << " for alternative chain, has invalid timestamp: " << b.timestamp); bvc.m_verifivation_failed = true; return false; } // FIXME: consider moving away from block_extended_info at some point block_extended_info bei = boost::value_initialized<block_extended_info>(); bei.bl = b; bei.height = alt_chain.size() ? it_prev->second.height + 1 : m_db->get_block_height(b.prev_id) + 1; bool is_a_checkpoint; if(!m_checkpoints.check_block(bei.height, id, is_a_checkpoint)) { LOG_ERROR("CHECKPOINT VALIDATION FAILED"); bvc.m_verifivation_failed = true; return false; } // Check the block's hash against the difficulty target for its alt chain difficulty_type current_diff = get_next_difficulty_for_alternative_chain(alt_chain, bei); CHECK_AND_ASSERT_MES(current_diff, false, "!!!!!!! DIFFICULTY OVERHEAD !!!!!!!"); crypto::hash proof_of_work = null_hash; get_block_longhash(bei.bl, proof_of_work, bei.height); if(!check_hash(proof_of_work, current_diff)) { MERROR_VER("Block with id: " << id << std::endl << " for alternative chain, does not have enough proof of work: " << proof_of_work << std::endl << " expected difficulty: " << current_diff); bvc.m_verifivation_failed = true; return false; } if(!prevalidate_miner_transaction(b, bei.height)) { MERROR_VER("Block with id: " << epee::string_tools::pod_to_hex(id) << " (as alternative) has incorrect miner transaction."); bvc.m_verifivation_failed = true; return false; } // FIXME: // this brings up an interesting point: consider allowing to get block // difficulty both by height OR by hash, not just height. difficulty_type main_chain_cumulative_difficulty = m_db->get_block_cumulative_difficulty(m_db->height() - 1); if (alt_chain.size()) { bei.cumulative_difficulty = it_prev->second.cumulative_difficulty; } else { // passed-in block's previous block's cumulative difficulty, found on the main chain bei.cumulative_difficulty = m_db->get_block_cumulative_difficulty(m_db->get_block_height(b.prev_id)); } bei.cumulative_difficulty += current_diff; // add block to alternate blocks storage, // as well as the current "alt chain" container auto i_res = m_alternative_chains.insert(blocks_ext_by_hash::value_type(id, bei)); CHECK_AND_ASSERT_MES(i_res.second, false, "insertion of new alternative block returned as it already exist"); alt_chain.push_back(i_res.first); // FIXME: is it even possible for a checkpoint to show up not on the main chain? if(is_a_checkpoint) { //do reorganize! MGINFO_GREEN("###### REORGANIZE on height: " << alt_chain.front()->second.height << " of " << m_db->height() - 1 << ", checkpoint is found in alternative chain on height " << bei.height); bool r = switch_to_alternative_blockchain(alt_chain, true); if(r) bvc.m_added_to_main_chain = true; else bvc.m_verifivation_failed = true; return r; } else if(main_chain_cumulative_difficulty < bei.cumulative_difficulty) //check if difficulty bigger then in main chain { //do reorganize! MGINFO_GREEN("###### REORGANIZE on height: " << alt_chain.front()->second.height << " of " << m_db->height() - 1 << " with cum_difficulty " << m_db->get_block_cumulative_difficulty(m_db->height() - 1) << std::endl << " alternative blockchain size: " << alt_chain.size() << " with cum_difficulty " << bei.cumulative_difficulty); bool r = switch_to_alternative_blockchain(alt_chain, false); if (r) bvc.m_added_to_main_chain = true; else bvc.m_verifivation_failed = true; return r; } else { MGINFO_BLUE("----- BLOCK ADDED AS ALTERNATIVE ON HEIGHT " << bei.height << std::endl << "id:\t" << id << std::endl << "PoW:\t" << proof_of_work << std::endl << "difficulty:\t" << current_diff); return true; } } else { //block orphaned bvc.m_marked_as_orphaned = true; MERROR_VER("Block recognized as orphaned and rejected, id = " << id << ", height " << block_height << ", parent in alt " << (it_prev != m_alternative_chains.end()) << ", parent in main " << parent_in_main << " (parent " << b.prev_id << ", current top " << get_tail_id() << ", chain height " << get_current_blockchain_height() << ")"); } return true; } //------------------------------------------------------------------ bool Blockchain::get_blocks(uint64_t start_offset, size_t count, std::vector<std::pair<cryptonote::blobdata,block>>& blocks, std::vector<cryptonote::blobdata>& txs) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); if(start_offset >= m_db->height()) return false; if (!get_blocks(start_offset, count, blocks)) { return false; } for(const auto& blk : blocks) { std::vector<crypto::hash> missed_ids; get_transactions_blobs(blk.second.tx_hashes, txs, missed_ids); CHECK_AND_ASSERT_MES(!missed_ids.size(), false, "has missed transactions in own block in main blockchain"); } return true; } //------------------------------------------------------------------ bool Blockchain::get_blocks(uint64_t start_offset, size_t count, std::vector<std::pair<cryptonote::blobdata,block>>& blocks) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); const uint64_t height = m_db->height(); if(start_offset >= height) return false; blocks.reserve(blocks.size() + height - start_offset); for(size_t i = start_offset; i < start_offset + count && i < height;i++) { blocks.push_back(std::make_pair(m_db->get_block_blob_from_height(i), block())); if (!parse_and_validate_block_from_blob(blocks.back().first, blocks.back().second)) { LOG_ERROR("Invalid block"); return false; } } return true; } //------------------------------------------------------------------ //TODO: This function *looks* like it won't need to be rewritten // to use BlockchainDB, as it calls other functions that were, // but it warrants some looking into later. // //FIXME: This function appears to want to return false if any transactions // that belong with blocks are missing, but not if blocks themselves // are missing. bool Blockchain::handle_get_objects(NOTIFY_REQUEST_GET_OBJECTS::request& arg, NOTIFY_RESPONSE_GET_OBJECTS::request& rsp) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); m_db->block_txn_start(true); rsp.current_blockchain_height = get_current_blockchain_height(); std::vector<std::pair<cryptonote::blobdata,block>> blocks; get_blocks(arg.blocks, blocks, rsp.missed_ids); for (auto& bl: blocks) { std::vector<crypto::hash> missed_tx_ids; std::vector<cryptonote::blobdata> txs; rsp.blocks.push_back(block_complete_entry()); block_complete_entry& e = rsp.blocks.back(); // FIXME: s/rsp.missed_ids/missed_tx_id/ ? Seems like rsp.missed_ids // is for missed blocks, not missed transactions as well. get_transactions_blobs(bl.second.tx_hashes, e.txs, missed_tx_ids); if (missed_tx_ids.size() != 0) { LOG_ERROR("Error retrieving blocks, missed " << missed_tx_ids.size() << " transactions for block with hash: " << get_block_hash(bl.second) << std::endl ); // append missed transaction hashes to response missed_ids field, // as done below if any standalone transactions were requested // and missed. rsp.missed_ids.insert(rsp.missed_ids.end(), missed_tx_ids.begin(), missed_tx_ids.end()); m_db->block_txn_stop(); return false; } //pack block e.block = std::move(bl.first); } //get and pack other transactions, if needed std::vector<cryptonote::blobdata> txs; get_transactions_blobs(arg.txs, rsp.txs, rsp.missed_ids); m_db->block_txn_stop(); return true; } //------------------------------------------------------------------ bool Blockchain::get_alternative_blocks(std::vector<block>& blocks) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); blocks.reserve(m_alternative_chains.size()); for (const auto& alt_bl: m_alternative_chains) { blocks.push_back(alt_bl.second.bl); } return true; } //------------------------------------------------------------------ size_t Blockchain::get_alternative_blocks_count() const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); return m_alternative_chains.size(); } //------------------------------------------------------------------ // This function adds the output specified by <amount, i> to the result_outs container // unlocked and other such checks should be done by here. uint64_t Blockchain::get_num_mature_outputs(uint64_t amount) const { uint64_t num_outs = m_db->get_num_outputs(amount); // ensure we don't include outputs that aren't yet eligible to be used // outpouts are sorted by height while (num_outs > 0) { const tx_out_index toi = m_db->get_output_tx_and_index(amount, num_outs - 1); const uint64_t height = m_db->get_tx_block_height(toi.first); if (height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE <= m_db->height()) break; --num_outs; } return num_outs; } crypto::public_key Blockchain::get_output_key(uint64_t amount, uint64_t global_index) const { output_data_t data = m_db->get_output_key(amount, global_index); return data.pubkey; } //------------------------------------------------------------------ bool Blockchain::get_outs(const COMMAND_RPC_GET_OUTPUTS_BIN::request& req, COMMAND_RPC_GET_OUTPUTS_BIN::response& res) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); res.outs.clear(); res.outs.reserve(req.outputs.size()); try { for (const auto &i: req.outputs) { // get tx_hash, tx_out_index from DB const output_data_t od = m_db->get_output_key(i.amount, i.index); tx_out_index toi = m_db->get_output_tx_and_index(i.amount, i.index); bool unlocked = is_output_spendtime_unlocked(od.unlock_time); res.outs.push_back({od.pubkey, od.commitment, unlocked, od.height, toi.first}); } } catch (const std::exception &e) { return false; } return true; } //------------------------------------------------------------------ void Blockchain::get_output_key_mask_unlocked(const uint64_t& amount, const uint64_t& index, crypto::public_key& key, rct::key& mask, bool& unlocked) const { const auto o_data = m_db->get_output_key(amount, index); key = o_data.pubkey; mask = o_data.commitment; unlocked = is_output_spendtime_unlocked(o_data.unlock_time); } //------------------------------------------------------------------ bool Blockchain::get_output_distribution(uint64_t amount, uint64_t from_height, uint64_t to_height, uint64_t &start_height, std::vector<uint64_t> &distribution, uint64_t &base) const { // rct outputs don't exist before v4, NOTE(koson): we started from v7 so our start is always 0 start_height = 0; base = 0; if (to_height > 0 && to_height < from_height) return false; const uint64_t real_start_height = start_height; if (from_height > start_height) start_height = from_height; distribution.clear(); uint64_t db_height = m_db->height(); if (db_height == 0) return false; if (to_height == 0) to_height = db_height - 1; if (start_height >= db_height || to_height >= db_height) return false; if (amount == 0) { std::vector<uint64_t> heights; heights.reserve(to_height + 1 - start_height); uint64_t real_start_height = start_height > 0 ? start_height-1 : start_height; for (uint64_t h = real_start_height; h <= to_height; ++h) heights.push_back(h); distribution = m_db->get_block_cumulative_rct_outputs(heights); if (start_height > 0) { base = distribution[0]; distribution.erase(distribution.begin()); } return true; } else { return m_db->get_output_distribution(amount, start_height, to_height, distribution, base); } } //------------------------------------------------------------------ // This function takes a list of block hashes from another node // on the network to find where the split point is between us and them. // This is used to see what to send another node that needs to sync. bool Blockchain::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, uint64_t& starter_offset) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); // make sure the request includes at least the genesis block, otherwise // how can we expect to sync from the client that the block list came from? if(!qblock_ids.size()) { MCERROR("net.p2p", "Client sent wrong NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << qblock_ids.size() << ", dropping connection"); return false; } m_db->block_txn_start(true); // make sure that the last block in the request's block list matches // the genesis block auto gen_hash = m_db->get_block_hash_from_height(0); if(qblock_ids.back() != gen_hash) { MCERROR("net.p2p", "Client sent wrong NOTIFY_REQUEST_CHAIN: genesis block mismatch: " << std::endl << "id: " << qblock_ids.back() << ", " << std::endl << "expected: " << gen_hash << "," << std::endl << " dropping connection"); m_db->block_txn_abort(); return false; } // Find the first block the foreign chain has that we also have. // Assume qblock_ids is in reverse-chronological order. auto bl_it = qblock_ids.begin(); uint64_t split_height = 0; for(; bl_it != qblock_ids.end(); bl_it++) { try { if (m_db->block_exists(*bl_it, &split_height)) break; } catch (const std::exception& e) { MWARNING("Non-critical error trying to find block by hash in BlockchainDB, hash: " << *bl_it); m_db->block_txn_abort(); return false; } } m_db->block_txn_stop(); // this should be impossible, as we checked that we share the genesis block, // but just in case... if(bl_it == qblock_ids.end()) { MERROR("Internal error handling connection, can't find split point"); return false; } //we start to put block ids INCLUDING last known id, just to make other side be sure starter_offset = split_height; return true; } //------------------------------------------------------------------ uint64_t Blockchain::block_difficulty(uint64_t i) const { LOG_PRINT_L3("Blockchain::" << __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must // lock if it is otherwise needed. try { return m_db->get_block_difficulty(i); } catch (const BLOCK_DNE& e) { MERROR("Attempted to get block difficulty for height above blockchain height"); } return 0; } //------------------------------------------------------------------ template<typename T> void reserve_container(std::vector<T> &v, size_t N) { v.reserve(N); } template<typename T> void reserve_container(std::list<T> &v, size_t N) { } //------------------------------------------------------------------ //TODO: return type should be void, throw on exception // alternatively, return true only if no blocks missed template<class t_ids_container, class t_blocks_container, class t_missed_container> bool Blockchain::get_blocks(const t_ids_container& block_ids, t_blocks_container& blocks, t_missed_container& missed_bs) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); reserve_container(blocks, block_ids.size()); for (const auto& block_hash : block_ids) { try { uint64_t height = 0; if (m_db->block_exists(block_hash, &height)) { blocks.push_back(std::make_pair(m_db->get_block_blob_from_height(height), block())); if (!parse_and_validate_block_from_blob(blocks.back().first, blocks.back().second)) { LOG_ERROR("Invalid block: " << block_hash); blocks.pop_back(); missed_bs.push_back(block_hash); } } else missed_bs.push_back(block_hash); } catch (const std::exception& e) { return false; } } return true; } //------------------------------------------------------------------ //TODO: return type should be void, throw on exception // alternatively, return true only if no transactions missed template<class t_ids_container, class t_tx_container, class t_missed_container> bool Blockchain::get_transactions_blobs(const t_ids_container& txs_ids, t_tx_container& txs, t_missed_container& missed_txs, bool pruned) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); reserve_container(txs, txs_ids.size()); for (const auto& tx_hash : txs_ids) { try { cryptonote::blobdata tx; if (pruned && m_db->get_pruned_tx_blob(tx_hash, tx)) txs.push_back(std::move(tx)); else if (!pruned && m_db->get_tx_blob(tx_hash, tx)) txs.push_back(std::move(tx)); else missed_txs.push_back(tx_hash); } catch (const std::exception& e) { return false; } } return true; } //------------------------------------------------------------------ template<class t_ids_container, class t_tx_container, class t_missed_container> bool Blockchain::get_transactions(const t_ids_container& txs_ids, t_tx_container& txs, t_missed_container& missed_txs) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); reserve_container(txs, txs_ids.size()); for (const auto& tx_hash : txs_ids) { try { cryptonote::blobdata tx; if (m_db->get_tx_blob(tx_hash, tx)) { txs.push_back(transaction()); if (!parse_and_validate_tx_from_blob(tx, txs.back())) { LOG_ERROR("Invalid transaction"); return false; } } else missed_txs.push_back(tx_hash); } catch (const std::exception& e) { return false; } } return true; } //------------------------------------------------------------------ // Find the split point between us and foreign blockchain and return // (by reference) the most recent common block hash along with up to // BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT additional (more recent) hashes. bool Blockchain::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, std::vector<crypto::hash>& hashes, uint64_t& start_height, uint64_t& current_height) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); // if we can't find the split point, return false if(!find_blockchain_supplement(qblock_ids, start_height)) { return false; } m_db->block_txn_start(true); current_height = get_current_blockchain_height(); size_t count = 0; hashes.reserve(std::max((size_t)(current_height - start_height), (size_t)BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT)); for(size_t i = start_height; i < current_height && count < BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT; i++, count++) { hashes.push_back(m_db->get_block_hash_from_height(i)); } m_db->block_txn_stop(); return true; } bool Blockchain::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); bool result = find_blockchain_supplement(qblock_ids, resp.m_block_ids, resp.start_height, resp.total_height); if (result) resp.cumulative_difficulty = m_db->get_block_cumulative_difficulty(resp.total_height - 1); return result; } //------------------------------------------------------------------ //FIXME: change argument to std::vector, low priority // find split point between ours and foreign blockchain (or start at // blockchain height <req_start_block>), and return up to max_count FULL // blocks by reference. bool Blockchain::find_blockchain_supplement(const uint64_t req_start_block, const std::list<crypto::hash>& qblock_ids, std::vector<std::pair<std::pair<cryptonote::blobdata, crypto::hash>, std::vector<std::pair<crypto::hash, cryptonote::blobdata> > > >& blocks, uint64_t& total_height, uint64_t& start_height, bool pruned, bool get_miner_tx_hash, size_t max_count) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); // if a specific start height has been requested if(req_start_block > 0) { // if requested height is higher than our chain, return false -- we can't help if (req_start_block >= m_db->height()) { return false; } start_height = req_start_block; } else { if(!find_blockchain_supplement(qblock_ids, start_height)) { return false; } } m_db->block_txn_start(true); total_height = get_current_blockchain_height(); size_t count = 0, size = 0; blocks.reserve(std::min(std::min(max_count, (size_t)10000), (size_t)(total_height - start_height))); for(uint64_t i = start_height; i < total_height && count < max_count && (size < FIND_BLOCKCHAIN_SUPPLEMENT_MAX_SIZE || count < 3); i++, count++) { blocks.resize(blocks.size()+1); blocks.back().first.first = m_db->get_block_blob_from_height(i); block b; CHECK_AND_ASSERT_MES(parse_and_validate_block_from_blob(blocks.back().first.first, b), false, "internal error, invalid block"); blocks.back().first.second = get_miner_tx_hash ? cryptonote::get_transaction_hash(b.miner_tx) : crypto::null_hash; std::vector<crypto::hash> mis; std::vector<cryptonote::blobdata> txs; get_transactions_blobs(b.tx_hashes, txs, mis, pruned); CHECK_AND_ASSERT_MES(!mis.size(), false, "internal error, transaction from block not found"); size += blocks.back().first.first.size(); for (const auto &t: txs) size += t.size(); CHECK_AND_ASSERT_MES(txs.size() == b.tx_hashes.size(), false, "mismatched sizes of b.tx_hashes and txs"); blocks.back().second.reserve(txs.size()); for (size_t i = 0; i < txs.size(); ++i) { blocks.back().second.push_back(std::make_pair(b.tx_hashes[i], std::move(txs[i]))); } } m_db->block_txn_stop(); return true; } //------------------------------------------------------------------ bool Blockchain::add_block_as_invalid(const block& bl, const crypto::hash& h) { LOG_PRINT_L3("Blockchain::" << __func__); block_extended_info bei = AUTO_VAL_INIT(bei); bei.bl = bl; return add_block_as_invalid(bei, h); } //------------------------------------------------------------------ bool Blockchain::add_block_as_invalid(const block_extended_info& bei, const crypto::hash& h) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); auto i_res = m_invalid_blocks.insert(std::map<crypto::hash, block_extended_info>::value_type(h, bei)); CHECK_AND_ASSERT_MES(i_res.second, false, "at insertion invalid by tx returned status existed"); MINFO("BLOCK ADDED AS INVALID: " << h << std::endl << ", prev_id=" << bei.bl.prev_id << ", m_invalid_blocks count=" << m_invalid_blocks.size()); return true; } //------------------------------------------------------------------ bool Blockchain::have_block(const crypto::hash& id) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); if(m_db->block_exists(id)) { LOG_PRINT_L2("block " << id << " found in main chain"); return true; } if(m_alternative_chains.count(id)) { LOG_PRINT_L2("block " << id << " found in m_alternative_chains"); return true; } if(m_invalid_blocks.count(id)) { LOG_PRINT_L2("block " << id << " found in m_invalid_blocks"); return true; } return false; } //------------------------------------------------------------------ bool Blockchain::handle_block_to_main_chain(const block& bl, block_verification_context& bvc) { LOG_PRINT_L3("Blockchain::" << __func__); crypto::hash id = get_block_hash(bl); return handle_block_to_main_chain(bl, id, bvc); } //------------------------------------------------------------------ size_t Blockchain::get_total_transactions() const { LOG_PRINT_L3("Blockchain::" << __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must // lock if it is otherwise needed. return m_db->get_tx_count(); } //------------------------------------------------------------------ // This function checks each input in the transaction <tx> to make sure it // has not been used already, and adds its key to the container <keys_this_block>. // // This container should be managed by the code that validates blocks so we don't // have to store the used keys in a given block in the permanent storage only to // remove them later if the block fails validation. bool Blockchain::check_for_double_spend(const transaction& tx, key_images_container& keys_this_block) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); struct add_transaction_input_visitor: public boost::static_visitor<bool> { key_images_container& m_spent_keys; BlockchainDB* m_db; add_transaction_input_visitor(key_images_container& spent_keys, BlockchainDB* db) : m_spent_keys(spent_keys), m_db(db) { } bool operator()(const txin_to_key& in) const { const crypto::key_image& ki = in.k_image; // attempt to insert the newly-spent key into the container of // keys spent this block. If this fails, the key was spent already // in this block, return false to flag that a double spend was detected. // // if the insert into the block-wide spent keys container succeeds, // check the blockchain-wide spent keys container and make sure the // key wasn't used in another block already. auto r = m_spent_keys.insert(ki); if(!r.second || m_db->has_key_image(ki)) { //double spend detected return false; } // if no double-spend detected, return true return true; } bool operator()(const txin_gen& tx) const { return true; } bool operator()(const txin_to_script& tx) const { return false; } bool operator()(const txin_to_scripthash& tx) const { return false; } }; for (const txin_v& in : tx.vin) { if(!boost::apply_visitor(add_transaction_input_visitor(keys_this_block, m_db), in)) { LOG_ERROR("Double spend detected!"); return false; } } return true; } //------------------------------------------------------------------ bool Blockchain::get_tx_outputs_gindexs(const crypto::hash& tx_id, std::vector<uint64_t>& indexs) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); uint64_t tx_index; if (!m_db->tx_exists(tx_id, tx_index)) { MERROR_VER("get_tx_outputs_gindexs failed to find transaction with id = " << tx_id); return false; } // get amount output indexes, currently referred to in parts as "output global indices", but they are actually specific to amounts indexs = m_db->get_tx_amount_output_indices(tx_index); if (indexs.empty()) { // empty indexs is only valid if the vout is empty, which is legal but rare cryptonote::transaction tx = m_db->get_tx(tx_id); CHECK_AND_ASSERT_MES(tx.vout.empty(), false, "internal error: global indexes for transaction " << tx_id << " is empty, and tx vout is not"); } return true; } //------------------------------------------------------------------ void Blockchain::on_new_tx_from_block(const cryptonote::transaction &tx) { #if defined(PER_BLOCK_CHECKPOINT) // check if we're doing per-block checkpointing if (m_db->height() < m_blocks_hash_check.size()) { TIME_MEASURE_START(a); m_blocks_txs_check.push_back(get_transaction_hash(tx)); TIME_MEASURE_FINISH(a); if(m_show_time_stats) { size_t ring_size = !tx.vin.empty() && tx.vin[0].type() == typeid(txin_to_key) ? boost::get<txin_to_key>(tx.vin[0]).key_offsets.size() : 0; MINFO("HASH: " << "-" << " I/M/O: " << tx.vin.size() << "/" << ring_size << "/" << tx.vout.size() << " H: " << 0 << " chcktx: " << a); } } #endif } //------------------------------------------------------------------ //FIXME: it seems this function is meant to be merely a wrapper around // another function of the same name, this one adding one bit of // functionality. Should probably move anything more than that // (getting the hash of the block at height max_used_block_id) // to the other function to keep everything in one place. // This function overloads its sister function with // an extra value (hash of highest block that holds an output used as input) // as a return-by-reference. bool Blockchain::check_tx_inputs(transaction& tx, uint64_t& max_used_block_height, crypto::hash& max_used_block_id, tx_verification_context &tvc, bool kept_by_block) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); #if defined(PER_BLOCK_CHECKPOINT) // check if we're doing per-block checkpointing if (m_db->height() < m_blocks_hash_check.size() && kept_by_block) { max_used_block_id = null_hash; max_used_block_height = 0; return true; } #endif TIME_MEASURE_START(a); bool res = check_tx_inputs(tx, tvc, &max_used_block_height); TIME_MEASURE_FINISH(a); if(m_show_time_stats) { size_t ring_size = !tx.vin.empty() && tx.vin[0].type() == typeid(txin_to_key) ? boost::get<txin_to_key>(tx.vin[0]).key_offsets.size() : 0; MINFO("HASH: " << get_transaction_hash(tx) << " I/M/O: " << tx.vin.size() << "/" << ring_size << "/" << tx.vout.size() << " H: " << max_used_block_height << " ms: " << a + m_fake_scan_time << " B: " << get_object_blobsize(tx) << " W: " << get_transaction_weight(tx)); } if (!res) return false; CHECK_AND_ASSERT_MES(max_used_block_height < m_db->height(), false, "internal error: max used block index=" << max_used_block_height << " is not less then blockchain size = " << m_db->height()); max_used_block_id = m_db->get_block_hash_from_height(max_used_block_height); return true; } //------------------------------------------------------------------ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context &tvc) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); const uint8_t hf_version = m_hardfork->get_current_version(); // from hard fork 2, we forbid dust and compound outputs if (hf_version >= 2) { for (auto &o: tx.vout) { if (tx.version == 1) { if (!is_valid_decomposed_amount(o.amount)) { tvc.m_invalid_output = true; return false; } } } } // in a v2 tx, all outputs must have 0 amount if (hf_version >= 3) { if (tx.version >= 2) { for (auto &o: tx.vout) { if (o.amount != 0) { tvc.m_invalid_output = true; return false; } } } } // from v4, forbid invalid pubkeys if (hf_version >= 4) { for (const auto &o: tx.vout) { if (o.target.type() == typeid(txout_to_key)) { const txout_to_key& out_to_key = boost::get<txout_to_key>(o.target); if (!crypto::check_key(out_to_key.key)) { tvc.m_invalid_output = true; return false; } } } } // from v10, allow bulletproofs if (hf_version < 10) { const bool bulletproof = rct::is_rct_bulletproof(tx.rct_signatures.type); if (bulletproof || !tx.rct_signatures.p.bulletproofs.empty()) { MERROR_VER("Bulletproofs are not allowed before v10"); tvc.m_invalid_output = true; return false; } } else { const bool borromean = rct::is_rct_borromean(tx.rct_signatures.type); if (borromean) { uint64_t hf10_height = m_hardfork->get_earliest_ideal_height_for_version(network_version_10_bulletproofs); uint64_t curr_height = this->get_current_blockchain_height(); if (curr_height == hf10_height) { // NOTE(koson): Allow the hardforking block to contain a borromean proof // incase there were some transactions in the TX Pool that were // generated pre-HF10 rules. Note, this isn't bulletproof. If there were // more than 1 blocks worth of borromean proof TX's sitting in the pool // this isn't going to work. } else { MERROR_VER("Borromean range proofs are not allowed after v10"); tvc.m_invalid_output = true; return false; } } } return true; } //------------------------------------------------------------------ bool Blockchain::have_tx_keyimges_as_spent(const transaction &tx) const { LOG_PRINT_L3("Blockchain::" << __func__); for (const txin_v& in: tx.vin) { CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, in_to_key, true); if(have_tx_keyimg_as_spent(in_to_key.k_image)) return true; } return false; } bool Blockchain::expand_transaction_2(transaction &tx, const crypto::hash &tx_prefix_hash, const std::vector<std::vector<rct::ctkey>> &pubkeys) { PERF_TIMER(expand_transaction_2); CHECK_AND_ASSERT_MES(tx.version >= 2, false, "Transaction version is not greater than 2"); rct::rctSig &rv = tx.rct_signatures; // message - hash of the transaction prefix rv.message = rct::hash2rct(tx_prefix_hash); // mixRing - full and simple store it in opposite ways if (rv.type == rct::RCTTypeFull) { CHECK_AND_ASSERT_MES(!pubkeys.empty() && !pubkeys[0].empty(), false, "empty pubkeys"); rv.mixRing.resize(pubkeys[0].size()); for (size_t m = 0; m < pubkeys[0].size(); ++m) rv.mixRing[m].clear(); for (size_t n = 0; n < pubkeys.size(); ++n) { CHECK_AND_ASSERT_MES(pubkeys[n].size() <= pubkeys[0].size(), false, "More inputs that first ring"); for (size_t m = 0; m < pubkeys[n].size(); ++m) { rv.mixRing[m].push_back(pubkeys[n][m]); } } } else if (rv.type == rct::RCTTypeSimple || rv.type == rct::RCTTypeBulletproof) { CHECK_AND_ASSERT_MES(!pubkeys.empty() && !pubkeys[0].empty(), false, "empty pubkeys"); rv.mixRing.resize(pubkeys.size()); for (size_t n = 0; n < pubkeys.size(); ++n) { rv.mixRing[n].clear(); for (size_t m = 0; m < pubkeys[n].size(); ++m) { rv.mixRing[n].push_back(pubkeys[n][m]); } } } else { CHECK_AND_ASSERT_MES(false, false, "Unsupported rct tx type: " + boost::lexical_cast<std::string>(rv.type)); } // II if (rv.type == rct::RCTTypeFull) { rv.p.MGs.resize(1); rv.p.MGs[0].II.resize(tx.vin.size()); for (size_t n = 0; n < tx.vin.size(); ++n) rv.p.MGs[0].II[n] = rct::ki2rct(boost::get<txin_to_key>(tx.vin[n]).k_image); } else if (rv.type == rct::RCTTypeSimple || rv.type == rct::RCTTypeBulletproof) { CHECK_AND_ASSERT_MES(rv.p.MGs.size() == tx.vin.size(), false, "Bad MGs size"); for (size_t n = 0; n < tx.vin.size(); ++n) { rv.p.MGs[n].II.resize(1); rv.p.MGs[n].II[0] = rct::ki2rct(boost::get<txin_to_key>(tx.vin[n]).k_image); } } else { CHECK_AND_ASSERT_MES(false, false, "Unsupported rct tx type: " + boost::lexical_cast<std::string>(rv.type)); } // outPk was already done by handle_incoming_tx return true; } //------------------------------------------------------------------ // This function validates transaction inputs and their keys. // FIXME: consider moving functionality specific to one input into // check_tx_input() rather than here, and use this function simply // to iterate the inputs as necessary (splitting the task // using threads, etc.) bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, uint64_t* pmax_used_block_height) { PERF_TIMER(check_tx_inputs); LOG_PRINT_L3("Blockchain::" << __func__); size_t sig_index = 0; if(pmax_used_block_height) *pmax_used_block_height = 0; crypto::hash tx_prefix_hash = get_transaction_prefix_hash(tx); const uint8_t hf_version = m_hardfork->get_current_version(); if (hf_version >= 9 && tx.version < 2) { tvc.m_invalid_version = true; return false; } else if (hf_version < 9 && tx.version > 2) { tvc.m_invalid_version = true; return false; } // from hard fork 2, we require mixin at least 2 unless one output cannot mix with 2 others // if one output cannot mix with 2 others, we accept at most 1 output that can mix if (hf_version >= 2 && !tx.is_deregister_tx()) { size_t n_unmixable = 0, n_mixable = 0; // TODO(jcktm) - remove mixin var if safe after fork size_t mixin = std::numeric_limits<size_t>::max(); const size_t min_mixin = hf_version >= HF_VERSION_MIN_MIXIN_9 ? 9 : 2; for (const auto& txin : tx.vin) { // non txin_to_key inputs will be rejected below if (txin.type() == typeid(txin_to_key)) { const txin_to_key& in_to_key = boost::get<txin_to_key>(txin); if (in_to_key.amount == 0) { // always consider rct inputs mixable. Even if there's not enough rct // inputs on the chain to mix with, this is going to be the case for // just a few blocks right after the fork at most ++n_mixable; } else { MDEBUG("Found unmixable output! This should never happen in Koson!"); uint64_t n_outputs = m_db->get_num_outputs(in_to_key.amount); MDEBUG("output size " << print_money(in_to_key.amount) << ": " << n_outputs << " available"); // n_outputs includes the output we're considering if (n_outputs <= min_mixin) ++n_unmixable; else ++n_mixable; } // TODO(jcktm) - remove branch if safe after fork if (in_to_key.key_offsets.size() - 1 < mixin) mixin = in_to_key.key_offsets.size() - 1; if (hf_version >= 9 && in_to_key.key_offsets.size() - 1 != min_mixin) { MERROR_VER("Tx " << get_transaction_hash(tx) << " has incorrect ring size (" << in_to_key.key_offsets.size() - 1 << ")"); tvc.m_low_mixin = true; return false; } } } // TODO(jcktm) - remove branch if safe after fork if (mixin != min_mixin) { if (n_unmixable == 0) { MERROR_VER("Tx " << get_transaction_hash(tx) << " has incorrect ring size (" << (mixin + 1) << "), and no unmixable inputs"); tvc.m_low_mixin = true; return false; } if (n_mixable > 1) { MERROR_VER("Tx " << get_transaction_hash(tx) << " has incorrect ring size (" << (mixin + 1) << "), and more than one mixable input with unmixable inputs"); tvc.m_low_mixin = true; return false; } } // min/max tx version based on HF, and we accept v1 txes if having a non mixable const size_t max_tx_version = (hf_version < 9) ? transaction::version_2 : transaction::version_3_per_output_unlock_times; if (tx.version > max_tx_version) { MERROR_VER("transaction version " << (unsigned)tx.version << " is higher than max accepted version " << max_tx_version); tvc.m_verifivation_failed = true; return false; } const size_t min_tx_version = (n_unmixable > 0 ? 1 : (hf_version >= HF_VERSION_ENFORCE_RCT) ? 2 : 1); if (tx.version < min_tx_version) { MERROR_VER("transaction version " << (unsigned)tx.version << " is lower than min accepted version " << min_tx_version); tvc.m_verifivation_failed = true; return false; } } // from v7, sorted ins if (hf_version >= 7) { const crypto::key_image *last_key_image = NULL; for (size_t n = 0; n < tx.vin.size(); ++n) { const txin_v &txin = tx.vin[n]; if (txin.type() == typeid(txin_to_key)) { const txin_to_key& in_to_key = boost::get<txin_to_key>(txin); if (last_key_image && memcmp(&in_to_key.k_image, last_key_image, sizeof(*last_key_image)) >= 0) { MERROR_VER("transaction has unsorted inputs"); tvc.m_verifivation_failed = true; return false; } last_key_image = &in_to_key.k_image; } } } auto it = m_check_txin_table.find(tx_prefix_hash); if(it == m_check_txin_table.end()) { m_check_txin_table.emplace(tx_prefix_hash, std::unordered_map<crypto::key_image, bool>()); it = m_check_txin_table.find(tx_prefix_hash); assert(it != m_check_txin_table.end()); } std::vector<std::vector<rct::ctkey>> pubkeys(tx.vin.size()); std::vector < uint64_t > results; results.resize(tx.vin.size(), 0); tools::threadpool& tpool = tools::threadpool::getInstance(); tools::threadpool::waiter waiter; const auto waiter_guard = epee::misc_utils::create_scope_leave_handler([&]() { waiter.wait(&tpool); }); int threads = tpool.get_max_concurrency(); for (const auto& txin : tx.vin) { // make sure output being spent is of type txin_to_key, rather than // e.g. txin_gen, which is only used for miner transactions CHECK_AND_ASSERT_MES(txin.type() == typeid(txin_to_key), false, "wrong type id in tx input at Blockchain::check_tx_inputs"); const txin_to_key& in_to_key = boost::get<txin_to_key>(txin); // make sure tx output has key offset(s) (is signed to be used) CHECK_AND_ASSERT_MES(in_to_key.key_offsets.size(), false, "empty in_to_key.key_offsets in transaction with id " << get_transaction_hash(tx)); if(have_tx_keyimg_as_spent(in_to_key.k_image)) { MERROR_VER("Key image already spent in blockchain: " << epee::string_tools::pod_to_hex(in_to_key.k_image)); tvc.m_double_spend = true; return false; } if (tx.version == 1) { // basically, make sure number of inputs == number of signatures CHECK_AND_ASSERT_MES(sig_index < tx.signatures.size(), false, "wrong transaction: not signature entry for input with index= " << sig_index); #if defined(CACHE_VIN_RESULTS) auto itk = it->second.find(in_to_key.k_image); if(itk != it->second.end()) { if(!itk->second) { MERROR_VER("Failed ring signature for tx " << get_transaction_hash(tx) << " vin key with k_image: " << in_to_key.k_image << " sig_index: " << sig_index); return false; } // txin has been verified already, skip sig_index++; continue; } #endif } // make sure that output being spent matches up correctly with the // signature spending it. if (!check_tx_input(tx.version, in_to_key, tx_prefix_hash, tx.version == 1 ? tx.signatures[sig_index] : std::vector<crypto::signature>(), tx.rct_signatures, pubkeys[sig_index], pmax_used_block_height)) { it->second[in_to_key.k_image] = false; MERROR_VER("Failed to check ring signature for tx " << get_transaction_hash(tx) << " vin key with k_image: " << in_to_key.k_image << " sig_index: " << sig_index); if (pmax_used_block_height) // a default value of NULL is used when called from Blockchain::handle_block_to_main_chain() { MERROR_VER(" *pmax_used_block_height: " << *pmax_used_block_height); } return false; } if (tx.version == 1) { if (threads > 1) { // ND: Speedup // 1. Thread ring signature verification if possible. tpool.submit(&waiter, boost::bind(&Blockchain::check_ring_signature, this, std::cref(tx_prefix_hash), std::cref(in_to_key.k_image), std::cref(pubkeys[sig_index]), std::cref(tx.signatures[sig_index]), std::ref(results[sig_index])), true); } else { check_ring_signature(tx_prefix_hash, in_to_key.k_image, pubkeys[sig_index], tx.signatures[sig_index], results[sig_index]); if (!results[sig_index]) { it->second[in_to_key.k_image] = false; MERROR_VER("Failed to check ring signature for tx " << get_transaction_hash(tx) << " vin key with k_image: " << in_to_key.k_image << " sig_index: " << sig_index); if (pmax_used_block_height) // a default value of NULL is used when called from Blockchain::handle_block_to_main_chain() { MERROR_VER("*pmax_used_block_height: " << *pmax_used_block_height); } return false; } it->second[in_to_key.k_image] = true; } } sig_index++; } if (tx.version == 1 && threads > 1) waiter.wait(&tpool); if (tx.version == 1) { if (threads > 1) { // save results to table, passed or otherwise bool failed = false; for (size_t i = 0; i < tx.vin.size(); i++) { const txin_to_key& in_to_key = boost::get<txin_to_key>(tx.vin[i]); it->second[in_to_key.k_image] = results[i]; if(!failed && !results[i]) failed = true; } if (failed) { MERROR_VER("Failed to check ring signatures!"); return false; } } } else if (!tx.is_deregister_tx()) { if (!expand_transaction_2(tx, tx_prefix_hash, pubkeys)) { MERROR_VER("Failed to expand rct signatures!"); return false; } // from version 2, check ringct signatures // obviously, the original and simple rct APIs use a mixRing that's indexes // in opposite orders, because it'd be too simple otherwise... const rct::rctSig &rv = tx.rct_signatures; switch (rv.type) { case rct::RCTTypeNull: { // we only accept no signatures for coinbase txes MERROR_VER("Null rct signature on non-coinbase tx"); return false; } case rct::RCTTypeSimple: case rct::RCTTypeBulletproof: { // check all this, either reconstructed (so should really pass), or not { if (pubkeys.size() != rv.mixRing.size()) { MERROR_VER("Failed to check ringct signatures: mismatched pubkeys/mixRing size"); return false; } for (size_t i = 0; i < pubkeys.size(); ++i) { if (pubkeys[i].size() != rv.mixRing[i].size()) { MERROR_VER("Failed to check ringct signatures: mismatched pubkeys/mixRing size"); return false; } } for (size_t n = 0; n < pubkeys.size(); ++n) { for (size_t m = 0; m < pubkeys[n].size(); ++m) { if (pubkeys[n][m].dest != rct::rct2pk(rv.mixRing[n][m].dest)) { MERROR_VER("Failed to check ringct signatures: mismatched pubkey at vin " << n << ", index " << m); return false; } if (pubkeys[n][m].mask != rct::rct2pk(rv.mixRing[n][m].mask)) { MERROR_VER("Failed to check ringct signatures: mismatched commitment at vin " << n << ", index " << m); return false; } } } } if (rv.p.MGs.size() != tx.vin.size()) { MERROR_VER("Failed to check ringct signatures: mismatched MGs/vin sizes"); return false; } for (size_t n = 0; n < tx.vin.size(); ++n) { if (rv.p.MGs[n].II.empty() || memcmp(&boost::get<txin_to_key>(tx.vin[n]).k_image, &rv.p.MGs[n].II[0], 32)) { MERROR_VER("Failed to check ringct signatures: mismatched key image"); return false; } } if (!rct::verRctNonSemanticsSimple(rv)) { MERROR_VER("Failed to check ringct signatures!"); return false; } break; } case rct::RCTTypeFull: { // check all this, either reconstructed (so should really pass), or not { bool size_matches = true; for (size_t i = 0; i < pubkeys.size(); ++i) size_matches &= pubkeys[i].size() == rv.mixRing.size(); for (size_t i = 0; i < rv.mixRing.size(); ++i) size_matches &= pubkeys.size() == rv.mixRing[i].size(); if (!size_matches) { MERROR_VER("Failed to check ringct signatures: mismatched pubkeys/mixRing size"); return false; } for (size_t n = 0; n < pubkeys.size(); ++n) { for (size_t m = 0; m < pubkeys[n].size(); ++m) { if (pubkeys[n][m].dest != rct::rct2pk(rv.mixRing[m][n].dest)) { MERROR_VER("Failed to check ringct signatures: mismatched pubkey at vin " << n << ", index " << m); return false; } if (pubkeys[n][m].mask != rct::rct2pk(rv.mixRing[m][n].mask)) { MERROR_VER("Failed to check ringct signatures: mismatched commitment at vin " << n << ", index " << m); return false; } } } } if (rv.p.MGs.size() != 1) { MERROR_VER("Failed to check ringct signatures: Bad MGs size"); return false; } if (rv.p.MGs.empty() || rv.p.MGs[0].II.size() != tx.vin.size()) { MERROR_VER("Failed to check ringct signatures: mismatched II/vin sizes"); return false; } for (size_t n = 0; n < tx.vin.size(); ++n) { if (memcmp(&boost::get<txin_to_key>(tx.vin[n]).k_image, &rv.p.MGs[0].II[n], 32)) { MERROR_VER("Failed to check ringct signatures: mismatched II/vin sizes"); return false; } } if (!rct::verRct(rv, false)) { MERROR_VER("Failed to check ringct signatures!"); return false; } break; } default: MERROR_VER("Unsupported rct type: " << rv.type); return false; } // for bulletproofs, check they're only multi-output after v8 if (rct::is_rct_bulletproof(rv.type)) { if (hf_version < 10) { for (const rct::Bulletproof &proof: rv.p.bulletproofs) { if (proof.V.size() > 1) { MERROR_VER("Multi output bulletproofs are invalid before v8"); return false; } } } } } if (tx.is_deregister_tx()) { if (tx.rct_signatures.txnFee != 0) { tvc.m_invalid_input = true; tvc.m_verifivation_failed = true; MERROR_VER("TX version deregister should have 0 fee!"); return false; } // Check the inputs (votes) of the transaction have not already been // submitted to the blockchain under another transaction using a different // combination of votes. tx_extra_service_node_deregister deregister; if (!get_service_node_deregister_from_tx_extra(tx.extra, deregister)) { MERROR_VER("TX version deregister did not have the deregister metadata in the tx_extra"); return false; } const std::shared_ptr<const service_nodes::quorum_state> quorum_state = m_service_node_list.get_quorum_state(deregister.block_height); if (!quorum_state) { MERROR_VER("TX version 3 deregister_tx could not get quorum for height: " << deregister.block_height); return false; } if (!koson::service_node_deregister::verify_deregister(nettype(), deregister, tvc.m_vote_ctx, *quorum_state)) { tvc.m_verifivation_failed = true; MERROR_VER("tx " << get_transaction_hash(tx) << ": version 3 deregister_tx could not be completely verified reason: " << print_vote_verification_context(tvc.m_vote_ctx)); return false; } // Check if deregister is too old or too new to hold onto { const uint64_t curr_height = get_current_blockchain_height(); if (deregister.block_height >= curr_height) { LOG_PRINT_L1("Received deregister tx for height: " << deregister.block_height << " and service node: " << deregister.service_node_index << ", is newer than current height: " << curr_height << " blocks and has been rejected."); tvc.m_vote_ctx.m_invalid_block_height = true; tvc.m_verifivation_failed = true; return false; } uint64_t delta_height = curr_height - deregister.block_height; if (delta_height >= koson::service_node_deregister::DEREGISTER_LIFETIME_BY_HEIGHT) { LOG_PRINT_L1("Received deregister tx for height: " << deregister.block_height << " and service node: " << deregister.service_node_index << ", is older than: " << koson::service_node_deregister::DEREGISTER_LIFETIME_BY_HEIGHT << " blocks and has been rejected. The current height is: " << curr_height); tvc.m_vote_ctx.m_invalid_block_height = true; tvc.m_verifivation_failed = true; return false; } } const uint64_t height = deregister.block_height; const size_t num_blocks_to_check = koson::service_node_deregister::DEREGISTER_LIFETIME_BY_HEIGHT; std::vector<std::pair<cryptonote::blobdata,block>> blocks; std::vector<cryptonote::blobdata> txs; if (get_blocks(height, num_blocks_to_check, blocks, txs)) { for (blobdata const &blob : txs) { transaction existing_tx; if (!parse_and_validate_tx_from_blob(blob, existing_tx)) { MERROR_VER("tx could not be validated from blob, possibly corrupt blockchain"); continue; } if (!existing_tx.is_deregister_tx()) continue; tx_extra_service_node_deregister existing_deregister; if (!get_service_node_deregister_from_tx_extra(existing_tx.extra, existing_deregister)) { MERROR_VER("could not get service node deregister from tx extra, possibly corrupt tx"); continue; } const std::shared_ptr<const service_nodes::quorum_state> existing_deregister_quorum_state = m_service_node_list.get_quorum_state(existing_deregister.block_height); if (!existing_deregister_quorum_state) { MERROR_VER("could not get quorum state for recent deregister tx"); continue; } if (existing_deregister_quorum_state->nodes_to_test[existing_deregister.service_node_index] == quorum_state->nodes_to_test[deregister.service_node_index]) { MERROR_VER("Already seen this deregister tx (aka double spend)"); tvc.m_double_spend = true; return false; } } } else { return false; } } return true; } //------------------------------------------------------------------ void Blockchain::check_ring_signature(const crypto::hash &tx_prefix_hash, const crypto::key_image &key_image, const std::vector<rct::ctkey> &pubkeys, const std::vector<crypto::signature>& sig, uint64_t &result) { std::vector<const crypto::public_key *> p_output_keys; p_output_keys.reserve(pubkeys.size()); for (auto &key : pubkeys) { // rct::key and crypto::public_key have the same structure, avoid object ctor/memcpy p_output_keys.push_back(&(const crypto::public_key&)key.dest); } result = crypto::check_ring_signature(tx_prefix_hash, key_image, p_output_keys, sig.data()) ? 1 : 0; } //------------------------------------------------------------------ uint64_t Blockchain::get_fee_quantization_mask() { static uint64_t mask = 0; if (mask == 0) { mask = 1; for (size_t n = PER_KB_FEE_QUANTIZATION_DECIMALS; n < CRYPTONOTE_DISPLAY_DECIMAL_POINT; ++n) mask *= 10; } return mask; } //------------------------------------------------------------------ uint64_t Blockchain::get_dynamic_base_fee(uint64_t block_reward, size_t median_block_weight, uint8_t version) { const uint64_t min_block_weight = get_min_block_weight(version); if (median_block_weight < min_block_weight) median_block_weight = min_block_weight; uint64_t hi, lo; if (version >= HF_VERSION_PER_BYTE_FEE) { lo = mul128(block_reward, DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT, &hi); div128_32(hi, lo, min_block_weight, &hi, &lo); div128_32(hi, lo, median_block_weight, &hi, &lo); assert(hi == 0); lo /= 5; return lo; } const uint64_t fee_base = version >= 5 ? DYNAMIC_FEE_PER_KB_BASE_FEE_V5 : DYNAMIC_FEE_PER_KB_BASE_FEE; uint64_t unscaled_fee_base = (fee_base * min_block_weight / median_block_weight); lo = mul128(unscaled_fee_base, block_reward, &hi); static_assert(DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD % 1000000 == 0, "DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD must be divisible by 1000000"); static_assert(DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD / 1000000 <= std::numeric_limits<uint32_t>::max(), "DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD is too large"); // divide in two steps, since the divisor must be 32 bits, but DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD isn't div128_32(hi, lo, DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD / 1000000, &hi, &lo); div128_32(hi, lo, 1000000, &hi, &lo); assert(hi == 0); // quantize fee up to 8 decimals uint64_t mask = get_fee_quantization_mask(); uint64_t qlo = (lo + mask - 1) / mask * mask; MDEBUG("lo " << print_money(lo) << ", qlo " << print_money(qlo) << ", mask " << mask); return qlo; } //------------------------------------------------------------------ bool Blockchain::check_fee(size_t tx_weight, uint64_t fee) const { const uint8_t version = get_current_hard_fork_version(); uint64_t median = 0; uint64_t already_generated_coins = 0; uint64_t base_reward = 0; if (version >= HF_VERSION_DYNAMIC_FEE) { median = m_current_block_cumul_weight_limit / 2; already_generated_coins = m_db->height() ? m_db->get_block_already_generated_coins(m_db->height() - 1) : 0; if (!get_base_block_reward(median, 1, already_generated_coins, base_reward, version, m_db->height())) return false; } uint64_t needed_fee; if (version >= HF_VERSION_PER_BYTE_FEE) { uint64_t fee_per_byte = get_dynamic_base_fee(base_reward, median, version); MDEBUG("Using " << print_money(fee_per_byte) << "/byte fee"); needed_fee = tx_weight * fee_per_byte; // quantize fee up to 8 decimals const uint64_t mask = get_fee_quantization_mask(); needed_fee = (needed_fee + mask - 1) / mask * mask; } else { uint64_t fee_per_kb; if (version < HF_VERSION_DYNAMIC_FEE) { fee_per_kb = FEE_PER_KB; } else { fee_per_kb = get_dynamic_base_fee(base_reward, median, version); } MDEBUG("Using " << print_money(fee_per_kb) << "/kB fee"); needed_fee = tx_weight / 1024; needed_fee += (tx_weight % 1024) ? 1 : 0; needed_fee *= fee_per_kb; } if (fee < needed_fee - needed_fee / 50) // keep a little 2% buffer on acceptance - no integer overflow { MERROR_VER("transaction fee is not enough: " << print_money(fee) << ", minimum fee: " << print_money(needed_fee)); return false; } return true; } //------------------------------------------------------------------ uint64_t Blockchain::get_dynamic_base_fee_estimate(uint64_t grace_blocks) const { const uint8_t version = get_current_hard_fork_version(); if (version < HF_VERSION_DYNAMIC_FEE) return FEE_PER_KB; if (grace_blocks >= CRYPTONOTE_REWARD_BLOCKS_WINDOW) grace_blocks = CRYPTONOTE_REWARD_BLOCKS_WINDOW - 1; const uint64_t min_block_weight = get_min_block_weight(version); std::vector<size_t> weights; get_last_n_blocks_weights(weights, CRYPTONOTE_REWARD_BLOCKS_WINDOW - grace_blocks); weights.reserve(grace_blocks); for (size_t i = 0; i < grace_blocks; ++i) weights.push_back(min_block_weight); uint64_t median = epee::misc_utils::median(weights); if(median <= min_block_weight) median = min_block_weight; uint64_t already_generated_coins = m_db->height() ? m_db->get_block_already_generated_coins(m_db->height() - 1) : 0; uint64_t base_reward; if (!get_base_block_reward(median, 1, already_generated_coins, base_reward, version, m_db->height())) { MERROR("Failed to determine block reward, using placeholder " << print_money(BLOCK_REWARD_OVERESTIMATE) << " as a high bound"); base_reward = BLOCK_REWARD_OVERESTIMATE; } uint64_t fee = get_dynamic_base_fee(base_reward, median, version); const bool per_byte = version < HF_VERSION_PER_BYTE_FEE; MDEBUG("Estimating " << grace_blocks << "-block fee at " << print_money(fee) << "/" << (per_byte ? "byte" : "kB")); return fee; } //------------------------------------------------------------------ // This function checks to see if a tx is unlocked. unlock_time is either // a block index or a unix time. bool Blockchain::is_output_spendtime_unlocked(uint64_t unlock_time) const { LOG_PRINT_L3("Blockchain::" << __func__); return cryptonote::rules::is_output_unlocked(unlock_time, m_db->height()); } //------------------------------------------------------------------ // This function locates all outputs associated with a given input (mixins) // and validates that they exist and are usable. It also checks the ring // signature for each input. bool Blockchain::check_tx_input(size_t tx_version, const txin_to_key& txin, const crypto::hash& tx_prefix_hash, const std::vector<crypto::signature>& sig, const rct::rctSig &rct_signatures, std::vector<rct::ctkey> &output_keys, uint64_t* pmax_related_block_height) { LOG_PRINT_L3("Blockchain::" << __func__); // ND: // 1. Disable locking and make method private. //CRITICAL_REGION_LOCAL(m_blockchain_lock); struct outputs_visitor { std::vector<rct::ctkey >& m_output_keys; const Blockchain& m_bch; outputs_visitor(std::vector<rct::ctkey>& output_keys, const Blockchain& bch) : m_output_keys(output_keys), m_bch(bch) { } bool handle_output(uint64_t unlock_time, const crypto::public_key &pubkey, const rct::key &commitment) { //check tx unlock time if (!m_bch.is_output_spendtime_unlocked(unlock_time)) { MERROR_VER("One of outputs for one of inputs has wrong tx.unlock_time = " << unlock_time); return false; } // The original code includes a check for the output corresponding to this input // to be a txout_to_key. This is removed, as the database does not store this info, // but only txout_to_key outputs are stored in the DB in the first place, done in // Blockchain*::add_output m_output_keys.push_back(rct::ctkey({rct::pk2rct(pubkey), commitment})); return true; } }; output_keys.clear(); // collect output keys outputs_visitor vi(output_keys, *this); if (!scan_outputkeys_for_indexes(tx_version, txin, vi, tx_prefix_hash, pmax_related_block_height)) { MERROR_VER("Failed to get output keys for tx with amount = " << print_money(txin.amount) << " and count indexes " << txin.key_offsets.size()); return false; } if(txin.key_offsets.size() != output_keys.size()) { MERROR_VER("Output keys for tx with amount = " << txin.amount << " and count indexes " << txin.key_offsets.size() << " returned wrong keys count " << output_keys.size()); return false; } if (tx_version == 1) { CHECK_AND_ASSERT_MES(sig.size() == output_keys.size(), false, "internal error: tx signatures count=" << sig.size() << " mismatch with outputs keys count for inputs=" << output_keys.size()); } // rct_signatures will be expanded after this return true; } //------------------------------------------------------------------ //TODO: Is this intended to do something else? Need to look into the todo there. uint64_t Blockchain::get_adjusted_time() const { LOG_PRINT_L3("Blockchain::" << __func__); //TODO: add collecting median time return time(NULL); } //------------------------------------------------------------------ //TODO: revisit, has changed a bit on upstream bool Blockchain::check_block_timestamp(std::vector<uint64_t>& timestamps, const block& b, uint64_t& median_ts) const { LOG_PRINT_L3("Blockchain::" << __func__); median_ts = epee::misc_utils::median(timestamps); if(b.timestamp < median_ts) { MERROR_VER("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", less than median of last " << BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW << " blocks, " << median_ts); return false; } return true; } //------------------------------------------------------------------ // This function grabs the timestamps from the most recent <n> blocks, // where n = BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW. If there are not those many // blocks in the blockchain, the timestap is assumed to be valid. If there // are, this function returns: // true if the block's timestamp is not less than the timestamp of the // median of the selected blocks // false otherwise bool Blockchain::check_block_timestamp(const block& b, uint64_t& median_ts) const { LOG_PRINT_L3("Blockchain::" << __func__); uint64_t cryptonote_block_future_time_limit = CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT_V2; if(b.timestamp > get_adjusted_time() + cryptonote_block_future_time_limit) { MERROR_VER("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", bigger than adjusted time + 2 hours"); return false; } // if not enough blocks, no proper median yet, return true if(m_db->height() < BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW) { return true; } std::vector<uint64_t> timestamps; auto h = m_db->height(); // need most recent 60 blocks, get index of first of those size_t offset = h - BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW; timestamps.reserve(h - offset); for(;offset < h; ++offset) { timestamps.push_back(m_db->get_block_timestamp(offset)); } return check_block_timestamp(timestamps, b, median_ts); } //------------------------------------------------------------------ void Blockchain::return_tx_to_pool(std::vector<transaction> &txs) { uint8_t version = get_current_hard_fork_version(); for (auto& tx : txs) { cryptonote::tx_verification_context tvc = AUTO_VAL_INIT(tvc); // We assume that if they were in a block, the transactions are already // known to the network as a whole. However, if we had mined that block, // that might not be always true. Unlikely though, and always relaying // these again might cause a spike of traffic as many nodes re-relay // all the transactions in a popped block when a reorg happens. if (!m_tx_pool.add_tx(tx, tvc, true, true, false, version)) { MERROR("Failed to return taken transaction with hash: " << get_transaction_hash(tx) << " to tx_pool"); } } } //------------------------------------------------------------------ bool Blockchain::flush_txes_from_pool(const std::vector<crypto::hash> &txids) { CRITICAL_REGION_LOCAL(m_tx_pool); bool res = true; for (const auto &txid: txids) { cryptonote::transaction tx; size_t tx_weight; uint64_t fee; bool relayed, do_not_relay, double_spend_seen; MINFO("Removing txid " << txid << " from the pool"); if(m_tx_pool.have_tx(txid) && !m_tx_pool.take_tx(txid, tx, tx_weight, fee, relayed, do_not_relay, double_spend_seen)) { MERROR("Failed to remove txid " << txid << " from the pool"); res = false; } } return res; } //------------------------------------------------------------------ // Needs to validate the block and acquire each transaction from the // transaction mem_pool, then pass the block and transactions to // m_db->add_block() bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& id, block_verification_context& bvc) { LOG_PRINT_L3("Blockchain::" << __func__); TIME_MEASURE_START(block_processing_time); CRITICAL_REGION_LOCAL(m_blockchain_lock); TIME_MEASURE_START(t1); static bool seen_future_version = false; m_db->block_txn_start(true); if(bl.prev_id != get_tail_id()) { MERROR_VER("Block with id: " << id << std::endl << "has wrong prev_id: " << bl.prev_id << std::endl << "expected: " << get_tail_id()); bvc.m_verifivation_failed = true; leave: m_db->block_txn_stop(); return false; } // warn users if they're running an old version if (!seen_future_version && bl.major_version > m_hardfork->get_ideal_version()) { seen_future_version = true; const el::Level level = el::Level::Warning; MCLOG_RED(level, "global", "**********************************************************************"); MCLOG_RED(level, "global", "A block was seen on the network with a version higher than the last"); MCLOG_RED(level, "global", "known one. This may be an old version of the daemon, and a software"); MCLOG_RED(level, "global", "update may be required to sync further. Try running: update check"); MCLOG_RED(level, "global", "**********************************************************************"); } // this is a cheap test if (!m_hardfork->check(bl)) { MERROR_VER("Block with id: " << id << std::endl << "has old version: " << (unsigned)bl.major_version << std::endl << "current: " << (unsigned)m_hardfork->get_current_version()); bvc.m_verifivation_failed = true; goto leave; } TIME_MEASURE_FINISH(t1); TIME_MEASURE_START(t2); // make sure block timestamp is not less than the median timestamp // of a set number of the most recent blocks. if(!check_block_timestamp(bl)) { MERROR_VER("Block with id: " << id << std::endl << "has invalid timestamp: " << bl.timestamp); bvc.m_verifivation_failed = true; goto leave; } TIME_MEASURE_FINISH(t2); //check proof of work TIME_MEASURE_START(target_calculating_time); // get the target difficulty for the block. // the calculation can overflow, among other failure cases, // so we need to check the return type. // FIXME: get_difficulty_for_next_block can also assert, look into // changing this to throwing exceptions instead so we can clean up. difficulty_type current_diffic = get_difficulty_for_next_block(); CHECK_AND_ASSERT_MES(current_diffic, false, "!!!!!!!!! difficulty overhead !!!!!!!!!"); TIME_MEASURE_FINISH(target_calculating_time); TIME_MEASURE_START(longhash_calculating_time); crypto::hash proof_of_work = null_hash; // Formerly the code below contained an if loop with the following condition // !m_checkpoints.is_in_checkpoint_zone(get_current_blockchain_height()) // however, this caused the daemon to not bother checking PoW for blocks // before checkpoints, which is very dangerous behaviour. We moved the PoW // validation out of the next chunk of code to make sure that we correctly // check PoW now. // FIXME: height parameter is not used...should it be used or should it not // be a parameter? // validate proof_of_work versus difficulty target bool precomputed = false; bool fast_check = false; #if defined(PER_BLOCK_CHECKPOINT) if (m_db->height() < m_blocks_hash_check.size()) { auto hash = get_block_hash(bl); const auto &expected_hash = m_blocks_hash_check[m_db->height()]; if (expected_hash != crypto::null_hash) { if (memcmp(&hash, &expected_hash, sizeof(hash)) != 0) { MERROR_VER("Block with id is INVALID: " << id); bvc.m_verifivation_failed = true; goto leave; } fast_check = true; } else { MCINFO("verify", "No pre-validated hash at height " << m_db->height() << ", verifying fully"); } } else #endif { auto it = m_blocks_longhash_table.find(id); if (it != m_blocks_longhash_table.end()) { precomputed = true; proof_of_work = it->second; } else proof_of_work = get_block_longhash(bl, m_db->height()); // validate proof_of_work versus difficulty target if(!check_hash(proof_of_work, current_diffic)) { MERROR_VER("Block with id: " << id << std::endl << "does not have enough proof of work: " << proof_of_work << std::endl << "unexpected difficulty: " << current_diffic); bvc.m_verifivation_failed = true; goto leave; } } // If we're at a checkpoint, ensure that our hardcoded checkpoint hash // is correct. if(m_checkpoints.is_in_checkpoint_zone(get_current_blockchain_height())) { if(!m_checkpoints.check_block(get_current_blockchain_height(), id)) { LOG_ERROR("CHECKPOINT VALIDATION FAILED"); bvc.m_verifivation_failed = true; goto leave; } } TIME_MEASURE_FINISH(longhash_calculating_time); if (precomputed) longhash_calculating_time += m_fake_pow_calc_time; TIME_MEASURE_START(t3); // sanity check basic miner tx properties; if(!prevalidate_miner_transaction(bl, m_db->height())) { MERROR_VER("Block with id: " << id << " failed to pass prevalidation"); bvc.m_verifivation_failed = true; goto leave; } size_t coinbase_weight = get_transaction_weight(bl.miner_tx); size_t cumulative_block_weight = coinbase_weight; std::vector<transaction> txs; key_images_container keys; uint64_t fee_summary = 0; uint64_t t_checktx = 0; uint64_t t_exists = 0; uint64_t t_pool = 0; uint64_t t_dblspnd = 0; TIME_MEASURE_FINISH(t3); // XXX old code adds miner tx here size_t tx_index = 0; // Iterate over the block's transaction hashes, grabbing each // from the tx_pool and validating them. Each is then added // to txs. Keys spent in each are added to <keys> by the double spend check. txs.reserve(bl.tx_hashes.size()); for (const crypto::hash& tx_id : bl.tx_hashes) { transaction tx; size_t tx_weight = 0; uint64_t fee = 0; bool relayed = false, do_not_relay = false, double_spend_seen = false; TIME_MEASURE_START(aa); // XXX old code does not check whether tx exists if (m_db->tx_exists(tx_id)) { MERROR("Block with id: " << id << " attempting to add transaction already in blockchain with id: " << tx_id); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); goto leave; } TIME_MEASURE_FINISH(aa); t_exists += aa; TIME_MEASURE_START(bb); // get transaction with hash <tx_id> from tx_pool if(!m_tx_pool.take_tx(tx_id, tx, tx_weight, fee, relayed, do_not_relay, double_spend_seen)) { MERROR_VER("Block with id: " << id << " has at least one unknown transaction with id: " << tx_id); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); goto leave; } TIME_MEASURE_FINISH(bb); t_pool += bb; // add the transaction to the temp list of transactions, so we can either // store the list of transactions all at once or return the ones we've // taken from the tx_pool back to it if the block fails verification. txs.push_back(tx); TIME_MEASURE_START(dd); // FIXME: the storage should not be responsible for validation. // If it does any, it is merely a sanity check. // Validation is the purview of the Blockchain class // - TW // // ND: this is not needed, db->add_block() checks for duplicate k_images and fails accordingly. // if (!check_for_double_spend(tx, keys)) // { // LOG_PRINT_L0("Double spend detected in transaction (id: " << tx_id); // bvc.m_verifivation_failed = true; // break; // } TIME_MEASURE_FINISH(dd); t_dblspnd += dd; TIME_MEASURE_START(cc); #if defined(PER_BLOCK_CHECKPOINT) if (!fast_check) #endif { // validate that transaction inputs and the keys spending them are correct. tx_verification_context tvc = AUTO_VAL_INIT(tvc); if(!check_tx_inputs(tx, tvc)) { MERROR_VER("Block with id: " << id << " has at least one transaction (id: " << tx_id << ") with wrong inputs."); //TODO: why is this done? make sure that keeping invalid blocks makes sense. add_block_as_invalid(bl, id); MERROR_VER("Block with id " << id << " added as invalid because of wrong inputs in transactions"); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); goto leave; } } #if defined(PER_BLOCK_CHECKPOINT) else { // ND: if fast_check is enabled for blocks, there is no need to check // the transaction inputs, but do some sanity checks anyway. if (tx_index >= m_blocks_txs_check.size() || memcmp(&m_blocks_txs_check[tx_index++], &tx_id, sizeof(tx_id)) != 0) { MERROR_VER("Block with id: " << id << " has at least one transaction (id: " << tx_id << ") with wrong inputs."); //TODO: why is this done? make sure that keeping invalid blocks makes sense. add_block_as_invalid(bl, id); MERROR_VER("Block with id " << id << " added as invalid because of wrong inputs in transactions"); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); goto leave; } } #endif TIME_MEASURE_FINISH(cc); t_checktx += cc; fee_summary += fee; cumulative_block_weight += tx_weight; } m_blocks_txs_check.clear(); TIME_MEASURE_START(vmt); uint64_t base_reward = 0; uint64_t already_generated_coins = m_db->height() ? m_db->get_block_already_generated_coins(m_db->height() - 1) : 0; if(!validate_miner_transaction(bl, cumulative_block_weight, fee_summary, base_reward, already_generated_coins, bvc.m_partial_block_reward, m_hardfork->get_current_version())) { MERROR_VER("Block with id: " << id << " has incorrect miner transaction"); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); goto leave; } TIME_MEASURE_FINISH(vmt); size_t block_weight; difficulty_type cumulative_difficulty; // populate various metadata about the block to be stored alongside it. block_weight = cumulative_block_weight; cumulative_difficulty = current_diffic; // In the "tail" state when the minimum subsidy (implemented in get_block_reward) is in effect, the number of // coins will eventually exceed MONEY_SUPPLY and overflow a uint64. To prevent overflow, cap already_generated_coins // at MONEY_SUPPLY. already_generated_coins is only used to compute the block subsidy and MONEY_SUPPLY yields a // subsidy of 0 under the base formula and therefore the minimum subsidy >0 in the tail state. already_generated_coins = base_reward < (MONEY_SUPPLY-already_generated_coins) ? already_generated_coins + base_reward : MONEY_SUPPLY; if(m_db->height()) cumulative_difficulty += m_db->get_block_cumulative_difficulty(m_db->height() - 1); TIME_MEASURE_FINISH(block_processing_time); if(precomputed) block_processing_time += m_fake_pow_calc_time; m_db->block_txn_stop(); TIME_MEASURE_START(addblock); uint64_t new_height = 0; if (!bvc.m_verifivation_failed) { try { new_height = m_db->add_block(bl, block_weight, cumulative_difficulty, already_generated_coins, txs); } catch (const KEY_IMAGE_EXISTS& e) { LOG_ERROR("Error adding block with hash: " << id << " to blockchain, what = " << e.what()); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; } catch (const std::exception& e) { //TODO: figure out the best way to deal with this failure LOG_ERROR("Error adding block with hash: " << id << " to blockchain, what = " << e.what()); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; } } else { LOG_ERROR("Blocks that failed verification should not reach here"); } for (BlockAddedHook* hook : m_block_added_hooks) hook->block_added(bl, txs); TIME_MEASURE_FINISH(addblock); // do this after updating the hard fork state since the weight limit may change due to fork update_next_cumulative_weight_limit(); MINFO("+++++ BLOCK SUCCESSFULLY ADDED" << std::endl << "id:\t" << id << std::endl << "PoW:\t" << proof_of_work << std::endl << "HEIGHT " << new_height-1 << ", difficulty:\t" << current_diffic << std::endl << "block reward: " << print_money(fee_summary + base_reward) << "(" << print_money(base_reward) << " + " << print_money(fee_summary) << "), coinbase_weight: " << coinbase_weight << ", cumulative weight: " << cumulative_block_weight << ", " << block_processing_time << "(" << target_calculating_time << "/" << longhash_calculating_time << ")ms"); if(m_show_time_stats) { MINFO("Height: " << new_height << " coinbase weight: " << coinbase_weight << " cumm: " << cumulative_block_weight << " p/t: " << block_processing_time << " (" << target_calculating_time << "/" << longhash_calculating_time << "/" << t1 << "/" << t2 << "/" << t3 << "/" << t_exists << "/" << t_pool << "/" << t_checktx << "/" << t_dblspnd << "/" << vmt << "/" << addblock << ")ms"); } bvc.m_added_to_main_chain = true; ++m_sync_counter; // appears to be a NOP *and* is called elsewhere. wat? m_tx_pool.on_blockchain_inc(new_height, id); get_difficulty_for_next_block(); // just to cache it invalidate_block_template_cache(); // New height is the height of the block we just mined. We want (new_height // + 1) because our age checks for deregister votes is now (age >= // DEREGISTER_VOTE_LIFETIME_BY_HEIGHT) where age is derived from // get_current_blockchain_height() which gives you the height that you are // currently mining for, i.e. (new_height + 1). Otherwise peers will silently // drop connection from each other when they go around P2Ping votes. m_deregister_vote_pool.remove_expired_votes(new_height + 1); m_deregister_vote_pool.remove_used_votes(txs); std::shared_ptr<tools::Notify> block_notify = m_block_notify; if (block_notify) block_notify->notify(epee::string_tools::pod_to_hex(id).c_str()); return true; } //------------------------------------------------------------------ bool Blockchain::update_next_cumulative_weight_limit() { uint64_t full_reward_zone = get_min_block_weight(get_current_hard_fork_version()); LOG_PRINT_L3("Blockchain::" << __func__); std::vector<size_t> weights; get_last_n_blocks_weights(weights, CRYPTONOTE_REWARD_BLOCKS_WINDOW); uint64_t median = epee::misc_utils::median(weights); m_current_block_cumul_weight_median = median; if(median <= full_reward_zone) median = full_reward_zone; m_current_block_cumul_weight_limit = median*2; return true; } //------------------------------------------------------------------ bool Blockchain::add_new_block(const block& bl_, block_verification_context& bvc) { LOG_PRINT_L3("Blockchain::" << __func__); //copy block here to let modify block.target block bl = bl_; crypto::hash id = get_block_hash(bl); CRITICAL_REGION_LOCAL(m_tx_pool);//to avoid deadlock lets lock tx_pool for whole add/reorganize process CRITICAL_REGION_LOCAL1(m_blockchain_lock); m_db->block_txn_start(true); if(have_block(id)) { LOG_PRINT_L3("block with id = " << id << " already exists"); bvc.m_already_exists = true; m_db->block_txn_stop(); m_blocks_txs_check.clear(); return false; } //check that block refers to chain tail if(!(bl.prev_id == get_tail_id())) { //chain switching or wrong block bvc.m_added_to_main_chain = false; m_db->block_txn_stop(); bool r = handle_alternative_block(bl, id, bvc); m_blocks_txs_check.clear(); return r; //never relay alternative blocks } m_db->block_txn_stop(); return handle_block_to_main_chain(bl, id, bvc); } //------------------------------------------------------------------ //TODO: Refactor, consider returning a failure height and letting // caller decide course of action. void Blockchain::check_against_checkpoints(const checkpoints& points, bool enforce) { const auto& pts = points.get_points(); bool stop_batch; CRITICAL_REGION_LOCAL(m_blockchain_lock); stop_batch = m_db->batch_start(); for (const auto& pt : pts) { // if the checkpoint is for a block we don't have yet, move on if (pt.first >= m_db->height()) { continue; } if (!points.check_block(pt.first, m_db->get_block_hash_from_height(pt.first))) { // if asked to enforce checkpoints, roll back to a couple of blocks before the checkpoint if (enforce) { LOG_ERROR("Local blockchain failed to pass a checkpoint, rolling back!"); std::list<block> empty; rollback_blockchain_switching(empty, pt.first - 2); } else { LOG_ERROR("WARNING: local blockchain failed to pass a MoneroPulse checkpoint, and you could be on a fork. You should either sync up from scratch, OR download a fresh blockchain bootstrap, OR enable checkpoint enforcing with the --enforce-dns-checkpointing command-line option"); } } } if (stop_batch) m_db->batch_stop(); } //------------------------------------------------------------------ // returns false if any of the checkpoints loading returns false. // That should happen only if a checkpoint is added that conflicts // with an existing checkpoint. bool Blockchain::update_checkpoints(const std::string& file_path, bool check_dns) { if (!m_checkpoints.load_checkpoints_from_json(file_path)) { return false; } // if we're checking both dns and json, load checkpoints from dns. // if we're not hard-enforcing dns checkpoints, handle accordingly if (m_enforce_dns_checkpoints && check_dns && !m_offline) { if (!m_checkpoints.load_checkpoints_from_dns()) { return false; } } else if (check_dns && !m_offline) { checkpoints dns_points; dns_points.load_checkpoints_from_dns(); if (m_checkpoints.check_for_conflicts(dns_points)) { check_against_checkpoints(dns_points, false); } else { MERROR("One or more checkpoints fetched from DNS conflicted with existing checkpoints!"); } } check_against_checkpoints(m_checkpoints, true); return true; } //------------------------------------------------------------------ void Blockchain::set_enforce_dns_checkpoints(bool enforce_checkpoints) { m_enforce_dns_checkpoints = enforce_checkpoints; } //------------------------------------------------------------------ void Blockchain::block_longhash_worker(uint64_t height, const std::vector<block> &blocks, std::unordered_map<crypto::hash, crypto::hash> &map) const { TIME_MEASURE_START(t); for (const auto & block : blocks) { if (m_cancel) break; crypto::hash id = get_block_hash(block); crypto::hash pow = get_block_longhash(block, height++); map.emplace(id, pow); } TIME_MEASURE_FINISH(t); } //------------------------------------------------------------------ bool Blockchain::cleanup_handle_incoming_blocks(bool force_sync) { bool success = false; MTRACE("Blockchain::" << __func__); CRITICAL_REGION_BEGIN(m_blockchain_lock); TIME_MEASURE_START(t1); try { m_db->batch_stop(); success = true; } catch (const std::exception &e) { MERROR("Exception in cleanup_handle_incoming_blocks: " << e.what()); } if (success && m_sync_counter > 0) { if (force_sync) { if(m_db_sync_mode != db_nosync) store_blockchain(); m_sync_counter = 0; } else if (m_db_sync_threshold && ((m_db_sync_on_blocks && m_sync_counter >= m_db_sync_threshold) || (!m_db_sync_on_blocks && m_bytes_to_sync >= m_db_sync_threshold))) { MDEBUG("Sync threshold met, syncing"); if(m_db_sync_mode == db_async) { m_sync_counter = 0; m_bytes_to_sync = 0; m_async_service.dispatch(boost::bind(&Blockchain::store_blockchain, this)); } else if(m_db_sync_mode == db_sync) { store_blockchain(); } else // db_nosync { // DO NOTHING, not required to call sync. } } } TIME_MEASURE_FINISH(t1); m_blocks_longhash_table.clear(); m_scan_table.clear(); m_blocks_txs_check.clear(); m_check_txin_table.clear(); // when we're well clear of the precomputed hashes, free the memory if (!m_blocks_hash_check.empty() && m_db->height() > m_blocks_hash_check.size() + 4096) { MINFO("Dumping block hashes, we're now 4k past " << m_blocks_hash_check.size()); m_blocks_hash_check.clear(); m_blocks_hash_check.shrink_to_fit(); } CRITICAL_REGION_END(); m_tx_pool.unlock(); return success; } //------------------------------------------------------------------ //FIXME: unused parameter txs void Blockchain::output_scan_worker(const uint64_t amount, const std::vector<uint64_t> &offsets, std::vector<output_data_t> &outputs, std::unordered_map<crypto::hash, cryptonote::transaction> &txs) const { try { m_db->get_output_key(amount, offsets, outputs, true); } catch (const std::exception& e) { MERROR_VER("EXCEPTION: " << e.what()); } catch (...) { } } uint64_t Blockchain::prevalidate_block_hashes(uint64_t height, const std::vector<crypto::hash> &hashes) { // new: . . . . . X X X X X . . . . . . // pre: A A A A B B B B C C C C D D D D // easy case: height >= hashes if (height >= m_blocks_hash_of_hashes.size() * HASH_OF_HASHES_STEP) return hashes.size(); // if we're getting old blocks, we might have jettisoned the hashes already if (m_blocks_hash_check.empty()) return hashes.size(); // find hashes encompassing those block size_t first_index = height / HASH_OF_HASHES_STEP; size_t last_index = (height + hashes.size() - 1) / HASH_OF_HASHES_STEP; MDEBUG("Blocks " << height << " - " << (height + hashes.size() - 1) << " start at " << first_index << " and end at " << last_index); // case of not enough to calculate even a single hash if (first_index == last_index && hashes.size() < HASH_OF_HASHES_STEP && (height + hashes.size()) % HASH_OF_HASHES_STEP) return hashes.size(); // build hashes vector to hash hashes together std::vector<crypto::hash> data; data.reserve(hashes.size() + HASH_OF_HASHES_STEP - 1); // may be a bit too much // we expect height to be either equal or a bit below db height bool disconnected = (height > m_db->height()); size_t pop; if (disconnected && height % HASH_OF_HASHES_STEP) { ++first_index; pop = HASH_OF_HASHES_STEP - height % HASH_OF_HASHES_STEP; } else { // we might need some already in the chain for the first part of the first hash for (uint64_t h = first_index * HASH_OF_HASHES_STEP; h < height; ++h) { data.push_back(m_db->get_block_hash_from_height(h)); } pop = 0; } // push the data to check for (const auto &h: hashes) { if (pop) --pop; else data.push_back(h); } // hash and check uint64_t usable = first_index * HASH_OF_HASHES_STEP - height; // may start negative, but unsigned under/overflow is not UB for (size_t n = first_index; n <= last_index; ++n) { if (n < m_blocks_hash_of_hashes.size()) { // if the last index isn't fully filled, we can't tell if valid if (data.size() < (n - first_index) * HASH_OF_HASHES_STEP + HASH_OF_HASHES_STEP) break; crypto::hash hash; cn_fast_hash(data.data() + (n - first_index) * HASH_OF_HASHES_STEP, HASH_OF_HASHES_STEP * sizeof(crypto::hash), hash); bool valid = hash == m_blocks_hash_of_hashes[n]; // add to the known hashes array if (!valid) { MDEBUG("invalid hash for blocks " << n * HASH_OF_HASHES_STEP << " - " << (n * HASH_OF_HASHES_STEP + HASH_OF_HASHES_STEP - 1)); break; } size_t end = n * HASH_OF_HASHES_STEP + HASH_OF_HASHES_STEP; for (size_t i = n * HASH_OF_HASHES_STEP; i < end; ++i) { CHECK_AND_ASSERT_MES(m_blocks_hash_check[i] == crypto::null_hash || m_blocks_hash_check[i] == data[i - first_index * HASH_OF_HASHES_STEP], 0, "Consistency failure in m_blocks_hash_check construction"); m_blocks_hash_check[i] = data[i - first_index * HASH_OF_HASHES_STEP]; } usable += HASH_OF_HASHES_STEP; } else { // if after the end of the precomputed blocks, accept anything usable += HASH_OF_HASHES_STEP; if (usable > hashes.size()) usable = hashes.size(); } } MDEBUG("usable: " << usable << " / " << hashes.size()); CHECK_AND_ASSERT_MES(usable < std::numeric_limits<uint64_t>::max() / 2, 0, "usable is negative"); return usable; } bool Blockchain::calc_batched_governance_reward(uint64_t height, uint64_t &reward) const { reward = 0; int hard_fork_version = get_ideal_hard_fork_version(height); if (hard_fork_version <= network_version_9_service_nodes) { return true; } if (!height_has_governance_output(nettype(), hard_fork_version, height)) { return true; } // Ignore governance reward and payout instead the last // GOVERNANCE_BLOCK_REWARD_INTERVAL number of blocks governance rewards. We // come back for this height's rewards in the next interval. The reward is // 0 if it's not time to pay out the batched payments const cryptonote::config_t &network = cryptonote::get_config(nettype(), hard_fork_version); size_t num_blocks = network.GOVERNANCE_REWARD_INTERVAL_IN_BLOCKS; uint64_t start_height = height - num_blocks; if (height < num_blocks) { start_height = 0; num_blocks = height; } std::vector<std::pair<cryptonote::blobdata, cryptonote::block>> blocks; if (!get_blocks(start_height, num_blocks, blocks)) { LOG_ERROR("Unable to get historical blocks to calculated batched governance payment"); return false; } for (const auto &it : blocks) { cryptonote::block const &block = it.second; if (block.major_version >= network_version_10_bulletproofs) reward += derive_governance_from_block_reward(nettype(), block); } return true; } //------------------------------------------------------------------ // ND: Speedups: // 1. Thread long_hash computations if possible (m_max_prepare_blocks_threads = nthreads, default = 4) // 2. Group all amounts (from txs) and related absolute offsets and form a table of tx_prefix_hash // vs [k_image, output_keys] (m_scan_table). This is faster because it takes advantage of bulk queries // and is threaded if possible. The table (m_scan_table) will be used later when querying output // keys. bool Blockchain::prepare_handle_incoming_blocks(const std::vector<block_complete_entry> &blocks_entry) { MTRACE("Blockchain::" << __func__); TIME_MEASURE_START(prepare); bool stop_batch; uint64_t bytes = 0; size_t total_txs = 0; // Order of locking must be: // m_incoming_tx_lock (optional) // m_tx_pool lock // blockchain lock // // Something which takes the blockchain lock may never take the txpool lock // if it has not provably taken the txpool lock earlier // // The txpool lock is now taken in prepare_handle_incoming_blocks // and released in cleanup_handle_incoming_blocks. This avoids issues // when something uses the pool, which now uses the blockchain and // needs a batch, since a batch could otherwise be active while the // txpool and blockchain locks were not held m_tx_pool.lock(); CRITICAL_REGION_LOCAL1(m_blockchain_lock); if(blocks_entry.size() == 0) return false; for (const auto &entry : blocks_entry) { bytes += entry.block.size(); for (const auto &tx_blob : entry.txs) { bytes += tx_blob.size(); } total_txs += entry.txs.size(); } m_bytes_to_sync += bytes; while (!(stop_batch = m_db->batch_start(blocks_entry.size(), bytes))) { m_blockchain_lock.unlock(); m_tx_pool.unlock(); epee::misc_utils::sleep_no_w(1000); m_tx_pool.lock(); m_blockchain_lock.lock(); } if ((m_db->height() + blocks_entry.size()) < m_blocks_hash_check.size()) return true; bool blocks_exist = false; tools::threadpool& tpool = tools::threadpool::getInstance(); uint64_t threads = tpool.get_max_concurrency(); if (blocks_entry.size() > 1 && threads > 1 && m_max_prepare_blocks_threads > 1) { // limit threads, default limit = 4 if(threads > m_max_prepare_blocks_threads) threads = m_max_prepare_blocks_threads; uint64_t height = m_db->height(); int batches = blocks_entry.size() / threads; int extra = blocks_entry.size() % threads; MDEBUG("block_batches: " << batches); std::vector<std::unordered_map<crypto::hash, crypto::hash>> maps(threads); std::vector < std::vector < block >> blocks(threads); auto it = blocks_entry.begin(); for (uint64_t i = 0; i < threads; i++) { blocks[i].reserve(batches + 1); for (int j = 0; j < batches; j++) { block block; if (!parse_and_validate_block_from_blob(it->block, block)) { std::advance(it, 1); continue; } // check first block and skip all blocks if its not chained properly if (i == 0 && j == 0) { crypto::hash tophash = m_db->top_block_hash(); if (block.prev_id != tophash) { MDEBUG("Skipping prepare blocks. New blocks don't belong to chain."); return true; } } if (have_block(get_block_hash(block))) { blocks_exist = true; break; } blocks[i].push_back(std::move(block)); std::advance(it, 1); } } for (int i = 0; i < extra && !blocks_exist; i++) { block block; if (!parse_and_validate_block_from_blob(it->block, block)) { std::advance(it, 1); continue; } if (have_block(get_block_hash(block))) { blocks_exist = true; break; } blocks[i].push_back(std::move(block)); std::advance(it, 1); } if (!blocks_exist) { m_blocks_longhash_table.clear(); uint64_t thread_height = height; tools::threadpool::waiter waiter; for (uint64_t i = 0; i < threads; i++) { tpool.submit(&waiter, boost::bind(&Blockchain::block_longhash_worker, this, thread_height, std::cref(blocks[i]), std::ref(maps[i])), true); thread_height += blocks[i].size(); } waiter.wait(&tpool); if (m_cancel) return false; for (const auto & map : maps) { m_blocks_longhash_table.insert(map.begin(), map.end()); } } } if (m_cancel) return false; if (blocks_exist) { MDEBUG("Skipping prepare blocks. Blocks exist."); return true; } m_fake_scan_time = 0; m_fake_pow_calc_time = 0; m_scan_table.clear(); m_check_txin_table.clear(); TIME_MEASURE_FINISH(prepare); m_fake_pow_calc_time = prepare / blocks_entry.size(); if (blocks_entry.size() > 1 && threads > 1 && m_show_time_stats) MDEBUG("Prepare blocks took: " << prepare << " ms"); TIME_MEASURE_START(scantable); // [input] stores all unique amounts found std::vector < uint64_t > amounts; // [input] stores all absolute_offsets for each amount std::map<uint64_t, std::vector<uint64_t>> offset_map; // [output] stores all output_data_t for each absolute_offset std::map<uint64_t, std::vector<output_data_t>> tx_map; std::vector<std::pair<cryptonote::transaction, crypto::hash>> txes(total_txs); #define SCAN_TABLE_QUIT(m) \ do { \ MERROR_VER(m) ;\ m_scan_table.clear(); \ return false; \ } while(0); \ // generate sorted tables for all amounts and absolute offsets size_t tx_index = 0; for (const auto &entry : blocks_entry) { if (m_cancel) return false; for (const auto &tx_blob : entry.txs) { if (tx_index >= txes.size()) SCAN_TABLE_QUIT("tx_index is out of sync"); transaction &tx = txes[tx_index].first; crypto::hash &tx_prefix_hash = txes[tx_index].second; ++tx_index; if (!parse_and_validate_tx_base_from_blob(tx_blob, tx)) SCAN_TABLE_QUIT("Could not parse tx from incoming blocks."); cryptonote::get_transaction_prefix_hash(tx, tx_prefix_hash); auto its = m_scan_table.find(tx_prefix_hash); if (its != m_scan_table.end()) SCAN_TABLE_QUIT("Duplicate tx found from incoming blocks."); m_scan_table.emplace(tx_prefix_hash, std::unordered_map<crypto::key_image, std::vector<output_data_t>>()); its = m_scan_table.find(tx_prefix_hash); assert(its != m_scan_table.end()); // get all amounts from tx.vin(s) for (const auto &txin : tx.vin) { const txin_to_key &in_to_key = boost::get < txin_to_key > (txin); // check for duplicate auto it = its->second.find(in_to_key.k_image); if (it != its->second.end()) SCAN_TABLE_QUIT("Duplicate key_image found from incoming blocks."); amounts.push_back(in_to_key.amount); } // sort and remove duplicate amounts from amounts list std::sort(amounts.begin(), amounts.end()); auto last = std::unique(amounts.begin(), amounts.end()); amounts.erase(last, amounts.end()); // add amount to the offset_map and tx_map for (const uint64_t &amount : amounts) { if (offset_map.find(amount) == offset_map.end()) offset_map.emplace(amount, std::vector<uint64_t>()); if (tx_map.find(amount) == tx_map.end()) tx_map.emplace(amount, std::vector<output_data_t>()); } // add new absolute_offsets to offset_map for (const auto &txin : tx.vin) { const txin_to_key &in_to_key = boost::get < txin_to_key > (txin); // no need to check for duplicate here. auto absolute_offsets = relative_output_offsets_to_absolute(in_to_key.key_offsets); for (const auto & offset : absolute_offsets) offset_map[in_to_key.amount].push_back(offset); } } } // sort and remove duplicate absolute_offsets in offset_map for (auto &offsets : offset_map) { std::sort(offsets.second.begin(), offsets.second.end()); auto last = std::unique(offsets.second.begin(), offsets.second.end()); offsets.second.erase(last, offsets.second.end()); } // [output] stores all transactions for each tx_out_index::hash found std::vector<std::unordered_map<crypto::hash, cryptonote::transaction>> transactions(amounts.size()); threads = tpool.get_max_concurrency(); if (!m_db->can_thread_bulk_indices()) threads = 1; if (threads > 1) { tools::threadpool::waiter waiter; for (size_t i = 0; i < amounts.size(); i++) { uint64_t amount = amounts[i]; tpool.submit(&waiter, boost::bind(&Blockchain::output_scan_worker, this, amount, std::cref(offset_map[amount]), std::ref(tx_map[amount]), std::ref(transactions[i])), true); } waiter.wait(&tpool); } else { for (size_t i = 0; i < amounts.size(); i++) { uint64_t amount = amounts[i]; output_scan_worker(amount, offset_map[amount], tx_map[amount], transactions[i]); } } // now generate a table for each tx_prefix and k_image hashes tx_index = 0; for (const auto &entry : blocks_entry) { if (m_cancel) return false; for (const auto &tx_blob : entry.txs) { if (tx_index >= txes.size()) SCAN_TABLE_QUIT("tx_index is out of sync"); const transaction &tx = txes[tx_index].first; const crypto::hash &tx_prefix_hash = txes[tx_index].second; ++tx_index; auto its = m_scan_table.find(tx_prefix_hash); if (its == m_scan_table.end()) SCAN_TABLE_QUIT("Tx not found on scan table from incoming blocks."); for (const auto &txin : tx.vin) { const txin_to_key &in_to_key = boost::get < txin_to_key > (txin); auto needed_offsets = relative_output_offsets_to_absolute(in_to_key.key_offsets); std::vector<output_data_t> outputs; for (const uint64_t & offset_needed : needed_offsets) { size_t pos = 0; bool found = false; for (const uint64_t &offset_found : offset_map[in_to_key.amount]) { if (offset_needed == offset_found) { found = true; break; } ++pos; } if (found && pos < tx_map[in_to_key.amount].size()) outputs.push_back(tx_map[in_to_key.amount].at(pos)); else break; } its->second.emplace(in_to_key.k_image, outputs); } } } TIME_MEASURE_FINISH(scantable); if (total_txs > 0) { m_fake_scan_time = scantable / total_txs; if(m_show_time_stats) MDEBUG("Prepare scantable took: " << scantable << " ms"); } return true; } void Blockchain::add_txpool_tx(transaction &tx, const txpool_tx_meta_t &meta) { m_db->add_txpool_tx(tx, meta); } void Blockchain::update_txpool_tx(const crypto::hash &txid, const txpool_tx_meta_t &meta) { m_db->update_txpool_tx(txid, meta); } void Blockchain::remove_txpool_tx(const crypto::hash &txid) { m_db->remove_txpool_tx(txid); } uint64_t Blockchain::get_txpool_tx_count(bool include_unrelayed_txes) const { return m_db->get_txpool_tx_count(include_unrelayed_txes); } bool Blockchain::get_txpool_tx_meta(const crypto::hash& txid, txpool_tx_meta_t &meta) const { return m_db->get_txpool_tx_meta(txid, meta); } bool Blockchain::get_txpool_tx_blob(const crypto::hash& txid, cryptonote::blobdata &bd) const { return m_db->get_txpool_tx_blob(txid, bd); } cryptonote::blobdata Blockchain::get_txpool_tx_blob(const crypto::hash& txid) const { return m_db->get_txpool_tx_blob(txid); } bool Blockchain::for_all_txpool_txes(std::function<bool(const crypto::hash&, const txpool_tx_meta_t&, const cryptonote::blobdata*)> f, bool include_blob, bool include_unrelayed_txes) const { return m_db->for_all_txpool_txes(f, include_blob, include_unrelayed_txes); } void Blockchain::set_user_options(uint64_t maxthreads, bool sync_on_blocks, uint64_t sync_threshold, blockchain_db_sync_mode sync_mode, bool fast_sync) { if (sync_mode == db_defaultsync) { m_db_default_sync = true; sync_mode = db_async; } m_db_sync_mode = sync_mode; m_fast_sync = fast_sync; m_db_sync_on_blocks = sync_on_blocks; m_db_sync_threshold = sync_threshold; m_max_prepare_blocks_threads = maxthreads; } void Blockchain::safesyncmode(const bool onoff) { /* all of this is no-op'd if the user set a specific * --db-sync-mode at startup. */ if (m_db_default_sync) { m_db->safesyncmode(onoff); m_db_sync_mode = onoff ? db_nosync : db_async; } } HardFork::State Blockchain::get_hard_fork_state() const { return m_hardfork->get_state(); } const std::vector<HardFork::Params>& Blockchain::get_hard_fork_heights(network_type nettype) { static const std::vector<HardFork::Params> mainnet_heights = []() { std::vector<HardFork::Params> heights; for (const auto& i : mainnet_hard_forks) heights.emplace_back(i.version, i.height, i.threshold, i.time); return heights; }(); static const std::vector<HardFork::Params> testnet_heights = []() { std::vector<HardFork::Params> heights; for (const auto& i : testnet_hard_forks) heights.emplace_back(i.version, i.height, i.threshold, i.time); return heights; }(); static const std::vector<HardFork::Params> stagenet_heights = []() { std::vector<HardFork::Params> heights; for (const auto& i : stagenet_hard_forks) heights.emplace_back(i.version, i.height, i.threshold, i.time); return heights; }(); static const std::vector<HardFork::Params> dummy; switch (nettype) { case MAINNET: return mainnet_heights; case TESTNET: return testnet_heights; case STAGENET: return stagenet_heights; default: return dummy; } } bool Blockchain::get_hard_fork_voting_info(uint8_t version, uint32_t &window, uint32_t &votes, uint32_t &threshold, uint64_t &earliest_height, uint8_t &voting) const { return m_hardfork->get_voting_info(version, window, votes, threshold, earliest_height, voting); } uint64_t Blockchain::get_difficulty_target() const { return DIFFICULTY_TARGET_V2; } std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>> Blockchain:: get_output_histogram(const std::vector<uint64_t> &amounts, bool unlocked, uint64_t recent_cutoff, uint64_t min_count) const { return m_db->get_output_histogram(amounts, unlocked, recent_cutoff, min_count); } std::list<std::pair<Blockchain::block_extended_info,std::vector<crypto::hash>>> Blockchain::get_alternative_chains() const { std::list<std::pair<Blockchain::block_extended_info,std::vector<crypto::hash>>> chains; for (const auto &i: m_alternative_chains) { const crypto::hash &top = i.first; bool found = false; for (const auto &j: m_alternative_chains) { if (j.second.bl.prev_id == top) { found = true; break; } } if (!found) { std::vector<crypto::hash> chain; auto h = i.second.bl.prev_id; chain.push_back(top); blocks_ext_by_hash::const_iterator prev; while ((prev = m_alternative_chains.find(h)) != m_alternative_chains.end()) { chain.push_back(h); h = prev->second.bl.prev_id; } chains.push_back(std::make_pair(i.second, chain)); } } return chains; } void Blockchain::cancel() { m_cancel = true; } #if defined(PER_BLOCK_CHECKPOINT) static const char expected_block_hashes_hash[] = "63b6445540c13f74d73fd753906e80bb84328c57b5a5a90c73353ed8405e7043"; void Blockchain::load_compiled_in_block_hashes(const GetCheckpointsCallback& get_checkpoints) { if (get_checkpoints == nullptr || !m_fast_sync) { return; } const epee::span<const unsigned char> &checkpoints = get_checkpoints(m_nettype); if (!checkpoints.empty()) { MINFO("Loading precomputed blocks (" << checkpoints.size() << " bytes)"); if (m_nettype == MAINNET) { // first check hash crypto::hash hash; if (!tools::sha256sum(checkpoints.data(), checkpoints.size(), hash)) { MERROR("Failed to hash precomputed blocks data"); return; } MINFO("precomputed blocks hash: " << hash << ", expected " << expected_block_hashes_hash); cryptonote::blobdata expected_hash_data; if (!epee::string_tools::parse_hexstr_to_binbuff(std::string(expected_block_hashes_hash), expected_hash_data) || expected_hash_data.size() != sizeof(crypto::hash)) { MERROR("Failed to parse expected block hashes hash"); return; } const crypto::hash expected_hash = *reinterpret_cast<const crypto::hash*>(expected_hash_data.data()); if (hash != expected_hash) { MERROR("Block hash data does not match expected hash"); return; } } if (checkpoints.size() > 4) { const unsigned char *p = checkpoints.data(); const uint32_t nblocks = *p | ((*(p+1))<<8) | ((*(p+2))<<16) | ((*(p+3))<<24); if (nblocks > (std::numeric_limits<uint32_t>::max() - 4) / sizeof(hash)) { MERROR("Block hash data is too large"); return; } const size_t size_needed = 4 + nblocks * sizeof(crypto::hash); if(nblocks > 0 && nblocks > (m_db->height() + HASH_OF_HASHES_STEP - 1) / HASH_OF_HASHES_STEP && checkpoints.size() >= size_needed) { p += sizeof(uint32_t); m_blocks_hash_of_hashes.reserve(nblocks); for (uint32_t i = 0; i < nblocks; i++) { crypto::hash hash; memcpy(hash.data, p, sizeof(hash.data)); p += sizeof(hash.data); m_blocks_hash_of_hashes.push_back(hash); } m_blocks_hash_check.resize(m_blocks_hash_of_hashes.size() * HASH_OF_HASHES_STEP, crypto::null_hash); MINFO(nblocks << " block hashes loaded"); // FIXME: clear tx_pool because the process might have been // terminated and caused it to store txs kept by blocks. // The core will not call check_tx_inputs(..) for these // transactions in this case. Consequently, the sanity check // for tx hashes will fail in handle_block_to_main_chain(..) CRITICAL_REGION_LOCAL(m_tx_pool); std::vector<transaction> txs; m_tx_pool.get_transactions(txs); size_t tx_weight; uint64_t fee; bool relayed, do_not_relay, double_spend_seen; transaction pool_tx; for(const transaction &tx : txs) { crypto::hash tx_hash = get_transaction_hash(tx); m_tx_pool.take_tx(tx_hash, pool_tx, tx_weight, fee, relayed, do_not_relay, double_spend_seen); } } } } } #endif bool Blockchain::is_within_compiled_block_hash_area(uint64_t height) const { #if defined(PER_BLOCK_CHECKPOINT) return height < m_blocks_hash_of_hashes.size() * HASH_OF_HASHES_STEP; #else return false; #endif } void Blockchain::lock() { m_blockchain_lock.lock(); } void Blockchain::unlock() { m_blockchain_lock.unlock(); } bool Blockchain::for_all_key_images(std::function<bool(const crypto::key_image&)> f) const { return m_db->for_all_key_images(f); } bool Blockchain::for_blocks_range(const uint64_t& h1, const uint64_t& h2, std::function<bool(uint64_t, const crypto::hash&, const block&)> f) const { return m_db->for_blocks_range(h1, h2, f); } bool Blockchain::for_all_transactions(std::function<bool(const crypto::hash&, const cryptonote::transaction&)> f, bool pruned) const { return m_db->for_all_transactions(f, pruned); } bool Blockchain::for_all_outputs(std::function<bool(uint64_t amount, const crypto::hash &tx_hash, uint64_t height, size_t tx_idx)> f) const { return m_db->for_all_outputs(f);; } bool Blockchain::for_all_outputs(uint64_t amount, std::function<bool(uint64_t height)> f) const { return m_db->for_all_outputs(amount, f);; } void Blockchain::hook_init(Blockchain::InitHook& init_hook) { m_init_hooks.push_back(&init_hook); } void Blockchain::hook_block_added(Blockchain::BlockAddedHook& block_added_hook) { m_block_added_hooks.push_back(&block_added_hook); } void Blockchain::hook_blockchain_detached(Blockchain::BlockchainDetachedHook& blockchain_detached_hook) { m_blockchain_detached_hooks.push_back(&blockchain_detached_hook); } void Blockchain::hook_validate_miner_tx(Blockchain::ValidateMinerTxHook& validate_miner_tx_hook) { m_validate_miner_tx_hooks.push_back(&validate_miner_tx_hook); } void Blockchain::invalidate_block_template_cache() { MDEBUG("Invalidating block template cache"); m_btc_valid = false; } void Blockchain::cache_block_template(const block &b, const cryptonote::account_public_address &address, const blobdata &nonce, const difficulty_type &diff, uint64_t expected_reward, uint64_t pool_cookie) { MDEBUG("Setting block template cache"); m_btc = b; m_btc_address = address; m_btc_nonce = nonce; m_btc_difficulty = diff; m_btc_expected_reward = expected_reward; m_btc_pool_cookie = pool_cookie; m_btc_valid = true; } namespace cryptonote { template bool Blockchain::get_transactions(const std::vector<crypto::hash>&, std::vector<transaction>&, std::vector<crypto::hash>&) const; template bool Blockchain::get_transactions_blobs(const std::vector<crypto::hash>&, std::vector<cryptonote::blobdata>&, std::vector<crypto::hash>&, bool) const; }
[ "mihai@lafix.online" ]
mihai@lafix.online
39124e258e5ea7d135ec8f3b23536bfb886bbf2f
b5afcffda86ae8c666e56fdae44587e27eadf28e
/src/kidtab.cpp
a8fd887845a8c04f751c03c04bf94a52c0c5ecad
[]
no_license
Karandaras/scene-reconstruction-gui
1a27e35a80f4d76a4eeed3ee5c14c7adedb827c9
108edcdfb7a4439f2d67c7a52e2395dcb3dcd0d6
refs/heads/master
2020-05-04T20:35:38.324271
2013-01-28T17:54:06
2013-01-28T17:54:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,218
cpp
#include "kidtab.h" #include "converter.h" #include <fstream> #include <gazebo/common/Image.hh> #include <boost/filesystem/path.hpp> using namespace SceneReconstruction; /** @class KIDTab "kidtab.h" * Tab for the GUI that builds and represents the KID Graph. * @author Bastian Klingen */ KIDTab::KIDTab(gazebo::transport::NodePtr& _node, LoggerTab* _logger, Glib::RefPtr<Gtk::Builder>& builder) : SceneTab::SceneTab(builder) { node = _node; logger = _logger; this->responseMutex = new boost::mutex(); _builder->get_widget("kid_toolbutton_new", btn_new); btn_new->signal_clicked().connect(sigc::mem_fun(*this,&KIDTab::on_new_clicked)); _builder->get_widget("kid_toolbutton_load", btn_load); btn_load->signal_clicked().connect(sigc::mem_fun(*this,&KIDTab::on_load_clicked)); _builder->get_widget("kid_toolbutton_save", btn_save); btn_save->signal_clicked().connect(sigc::mem_fun(*this,&KIDTab::on_save_clicked)); _builder->get_widget("kid_toolbutton_close", btn_close); btn_close->signal_clicked().connect(sigc::mem_fun(*this,&KIDTab::on_close_clicked)); _builder->get_widget("kid_combobox_graphs", com_graphs); com_graphs->signal_changed().connect(sigc::mem_fun(*this,&KIDTab::on_graphs_changed)); gra_store = Glib::RefPtr<Gtk::ListStore>::cast_dynamic(_builder->get_object("kid_liststore_graphs")); gra_store->clear(); Gtk::Box *box_type; _builder->get_widget("kid_box_top_left", box_type); com_type = Gtk::manage(new Gtk::ComboBoxText(false)); com_type->append("Node"); com_type->append("Edge"); com_type->set_active(0); box_type->pack_end(*com_type, false, true); com_type->signal_changed().connect(sigc::mem_fun(*this,&KIDTab::on_type_changed)); _builder->get_widget("kid_label_top_center_left", lbl_left); Gtk::Box *box_left; _builder->get_widget("kid_box_top_center_left", box_left); com_left = Gtk::manage(new Gtk::ComboBoxText(true)); com_left->append("Knowledge"); com_left->append("Information"); com_left->append("Data"); com_left->set_active(0); box_left->pack_end(*com_left, true, true); cpl_left = Glib::RefPtr<Gtk::EntryCompletion>::cast_dynamic(_builder->get_object("kid_entrycompletion_level_from")); cpl_left->set_model(com_left->get_model()); com_left->get_entry()->set_completion(cpl_left); _builder->get_widget("kid_label_top_center_right", lbl_right); Gtk::Box *box_right; _builder->get_widget("kid_box_top_center_right", box_right); com_right = Gtk::manage(new Gtk::ComboBoxText(true)); box_right->pack_end(*com_right, true, true); cpl_right = Glib::RefPtr<Gtk::EntryCompletion>::cast_dynamic(_builder->get_object("kid_entrycompletion_name_to")); cpl_right->set_model(com_right->get_model()); com_right->get_entry()->set_completion(cpl_right); _builder->get_widget("kid_entry_top_right", ent_label); ent_label->set_sensitive(false); _builder->get_widget("kid_toolbutton_top_add", btn_add); btn_add->signal_clicked().connect(sigc::mem_fun(*this,&KIDTab::on_add_clicked)); _builder->get_widget("kid_treeview_nodes", trv_nodes); nds_store = Glib::RefPtr<Gtk::ListStore>::cast_dynamic(_builder->get_object("kid_liststore_nodes")); nds_store->clear(); _builder->get_widget("kid_toolbutton_nodes_delete", btn_nodes_remove); btn_nodes_remove->signal_clicked().connect(sigc::mem_fun(*this,&KIDTab::on_nodes_remove_clicked)); _builder->get_widget("kid_toolbutton_unmark", btn_unmark); btn_unmark->signal_clicked().connect(sigc::mem_fun(*this,&KIDTab::on_unmark_clicked)); _builder->get_widget("kid_treeview_edges", trv_edges); edg_store = Glib::RefPtr<Gtk::ListStore>::cast_dynamic(_builder->get_object("kid_liststore_edges")); edg_store->clear(); _builder->get_widget("kid_toolbutton_edges_delete", btn_edges_remove); btn_edges_remove->signal_clicked().connect(sigc::mem_fun(*this,&KIDTab::on_edges_remove_clicked)); _builder->get_widget("kid_scrolledwindow_graph", scw_graph); gda_graph = Gtk::manage(new GraphDrawingArea()); scw_graph->add(*gda_graph); gda_graph->show(); gda_graph->signal_button_release_event().connect(sigc::mem_fun(*this,&KIDTab::on_graph_release)); _builder->get_widget("kid_toolbutton_zoom_in", btn_zoomin); btn_zoomin->signal_clicked().connect(sigc::mem_fun(*this,&KIDTab::on_zoom_in_clicked)); _builder->get_widget("kid_toolbutton_zoom_out", btn_zoomout); btn_zoomout->signal_clicked().connect(sigc::mem_fun(*this,&KIDTab::on_zoom_out_clicked)); _builder->get_widget("kid_toolbutton_zoom_fit", btn_zoomfit); btn_zoomfit->signal_clicked().connect(sigc::mem_fun(*this,&KIDTab::on_zoom_fit_clicked)); _builder->get_widget("kid_toolbutton_zoom_reset", btn_zoomreset); btn_zoomreset->signal_clicked().connect(sigc::mem_fun(*this,&KIDTab::on_zoom_reset_clicked)); _builder->get_widget("kid_toolbutton_export", btn_export); btn_export->signal_clicked().connect(sigc::mem_fun(*this,&KIDTab::on_export_clicked)); _builder->get_widget("kid_document_window", win_show); _builder->get_widget("kid_document_combobox", win_combo); win_combo->signal_changed().connect(sigc::mem_fun(*this,&KIDTab::on_document_changed)); _builder->get_widget("kid_document_image", win_image); missing_image = Gdk::Pixbuf::create_from_file("res/noimg.png"); _builder->get_widget("kid_document_textview", win_textview); win_textbuffer = Glib::RefPtr<Gtk::TextBuffer>::cast_dynamic(_builder->get_object("kid_document_textbuffer")); win_store = Glib::RefPtr<Gtk::ListStore>::cast_dynamic(_builder->get_object("kid_document_liststore")); fcd_save = new Gtk::FileChooserDialog("Save Graph", Gtk::FILE_CHOOSER_ACTION_SAVE); fcd_open = new Gtk::FileChooserDialog("Load Graph", Gtk::FILE_CHOOSER_ACTION_OPEN); fcd_save->add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL); fcd_save->add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK); fcd_open->add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL); fcd_open->add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK); filter_kgf = Gtk::FileFilter::create(); filter_kgf->set_name("KID Graph File (KGF)"); filter_kgf->add_pattern("*.kgf"); fcd_save->add_filter(filter_kgf); fcd_save->set_filter(filter_kgf); fcd_open->add_filter(filter_kgf); fcd_open->set_filter(filter_kgf); _builder->get_widget("kid_dialog_newgraph", dia_new); _builder->get_widget("kid_dialog_newgraph_entry", dia_new_entry); resSub = node->Subscribe("~/SceneReconstruction/GUI/MongoDB", &KIDTab::OnResponseMsg, this); framePub = node->Advertise<gazebo::msgs::Request>("~/SceneReconstruction/Framework/Request"); pclPub = node->Advertise<gazebo::msgs::Drawing>("~/SceneReconstruction/RobotController/Draw"); on_response_msg.connect( sigc::mem_fun( *this , &KIDTab::ProcessResponseMsg )); } KIDTab::~KIDTab() { } void KIDTab::OnResponseMsg(ConstResponsePtr& _msg) { { boost::mutex::scoped_lock lock(*this->responseMutex); this->responseMsgs.push_back(*_msg); } on_response_msg(); } void KIDTab::ProcessResponseMsg() { boost::mutex::scoped_lock lock(*this->responseMutex); std::list<gazebo::msgs::Response>::iterator _msg; for(_msg = responseMsgs.begin(); _msg != responseMsgs.end(); _msg++) { if(_msg->response() == "success" || _msg->response() == "part") { if(_msg->request() == "collection_names") { logger->log("kid", "received collections for nodelist"); gazebo::msgs::GzString_V src; if(_msg->has_type() && _msg->type() == src.GetTypeName()) { src.ParseFromString(_msg->serialized_data()); int n = src.data_size(); db_collections.clear(); for(int i=0; i<n; i++) { db_collections.push_back(src.data(i)); } if(com_type->get_active_text() == "Node") { logger->log("kid", "updating nodelist"); com_right->remove_all(); std::list<std::string>::iterator iter; for(iter = db_collections.begin(); iter != db_collections.end(); iter++) com_right->append(*iter); } } } else if(_msg->request() == "documents" && docreq->id() == _msg->id()) { logger->log("kid", "received documents for selected node: "+docreq->data()); gazebo::msgs::Message_V docs; if(_msg->has_type() && _msg->type() == docs.GetTypeName()) { docs.ParseFromString(_msg->serialized_data()); gazebo::msgs::SceneDocument doc; if(docs.msgtype() == doc.GetTypeName()) { int n = docs.msgsdata_size(); for(int i=0; i<n; i++) { logger->log("kid", "processing document for selected node: "+docreq->data()); doc.ParseFromString(docs.msgsdata(i)); Gtk::TreeModel::Row row; row = *(win_store->append()); row.set_value(0, "Time: "+Converter::to_ustring_time(doc.timestamp())); Glib::RefPtr<Gdk::Pixbuf> img; if(doc.has_image()) { gazebo::common::Image tmpimg; gazebo::msgs::Set(tmpimg, doc.image()); tmpimg.SavePNG("tmp_img.png"); img = Gdk::Pixbuf::create_from_file("tmp_img.png"); } else { img = missing_image; } gazebo::msgs::Drawing pcl; if(doc.has_pointcloud()) { pcl.CopyFrom(doc.pointcloud()); } else { pcl.set_name("pointcloud"); pcl.set_visible(false); } row.set_value(1, i); win_images[i] = img; win_pointclouds[i] = pcl; row.set_value(2, doc.document()); } win_combo->set_active(win_store->children().begin()); } } } } } responseMsgs.clear(); } void KIDTab::create_graphviz_dot() { std::string dot = graph.get_dot(); gda_graph->set_graph(dot); gda_graph->zoom_fit(); } void KIDTab::on_type_changed() { if(com_type->get_active_text() == "Node") { lbl_left->set_text("Level"); com_left->remove_all(); com_left->append("Knowledge"); com_left->append("Information"); com_left->append("Data"); lbl_right->set_text("Name"); ent_label->set_sensitive(false); com_right->remove_all(); std::list<std::string>::iterator iter; for(iter = db_collections.begin(); iter != db_collections.end(); iter++) com_right->append(*iter); } else if(com_type->get_active_text() == "Edge") { lbl_left->set_text("From"); lbl_right->set_text("To"); com_left->remove_all(); com_right->remove_all(); ent_label->set_sensitive(true); std::list<KIDGraph::KIDNode>::iterator iter; for(iter = graph.knowledge_nodes.begin(); iter != graph.knowledge_nodes.end(); iter++) { com_left->append(iter->node); com_right->append(iter->node); } for(iter = graph.information_nodes.begin(); iter != graph.information_nodes.end(); iter++) { com_left->append(iter->node); com_right->append(iter->node); } for(iter = graph.data_nodes.begin(); iter != graph.data_nodes.end(); iter++) { com_left->append(iter->node); com_right->append(iter->node); } com_left->get_entry()->set_editable(true); } } void KIDTab::on_add_clicked() { if(com_type->get_active_text() == "Node") { if(!graph.is_node(com_right->get_entry_text())) { if(com_left->get_active_text() == "Knowledge") { logger->log("kid", "knowledge node \""+com_right->get_entry_text()+"\" added"); KIDGraph::KIDNode node; node.node = com_right->get_entry_text(); graph.knowledge_nodes.push_back(node); Gtk::TreeModel::Row row; row = *(nds_store->append()); row.set_value(0, com_right->get_entry_text()); } else if(com_left->get_active_text() == "Information") { logger->log("kid", "information node \""+com_right->get_entry_text()+"\" added"); KIDGraph::KIDNode node; node.node = com_right->get_entry_text(); graph.information_nodes.push_back(node); Gtk::TreeModel::Row row; row = *(nds_store->append()); row.set_value(0, com_right->get_entry_text()); } else if(com_left->get_active_text() == "Data") { logger->log("kid", "data node \""+com_right->get_entry_text()+"\" added"); KIDGraph::KIDNode node; node.node = com_right->get_entry_text(); graph.data_nodes.push_back(node); Gtk::TreeModel::Row row; row = *(nds_store->append()); row.set_value(0, com_right->get_entry_text()); } else { logger->log("kid", "level \""+com_left->get_entry_text()+"\" not known"); } } else { logger->log("kid", "node \""+com_right->get_entry_text()+"\" already exists at level "+graph.level_of_node(com_right->get_entry_text())); } } else if(com_type->get_active_text() == "Edge") { KIDGraph::KIDEdge edge; edge.from = com_left->get_entry_text(); edge.to = com_right->get_entry_text(); edge.label = ent_label->get_text(); if(!graph.is_edge(edge) && graph.is_node(edge.from) && graph.is_node(edge.to)) { logger->log("kid", "edge "+edge.toString()+" added"); graph.edges.push_back(edge); KIDGraph::KIDNode *from = graph.get_node(edge.from); KIDGraph::KIDNode *to = graph.get_node(edge.to); from->children.push_back(to); to->parents.push_back(from); Gtk::TreeModel::Row row; row = *(edg_store->append()); row.set_value(0, edge.toString()); } else { std::string error = "edge not added"; if(graph.is_edge(edge)) error += ", edge already exists"; if(!graph.is_node(com_left->get_entry_text())) error += ", node \""+com_left->get_entry_text()+"\" is not known"; if(!graph.is_node(com_right->get_entry_text())) error += ", node \""+com_right->get_entry_text()+"\" is not known"; logger->log("kid", error); } } com_graphs->get_active()->set_value(1,graph.save_to_string()); create_graphviz_dot(); } void KIDTab::on_nodes_remove_clicked() { if(trv_nodes->get_selection()->count_selected_rows() == 1){ Glib::ustring node; trv_nodes->get_selection()->get_selected()->get_value(0, node); nds_store->erase(trv_nodes->get_selection()->get_selected()); logger->log("kid", "removed node: "+node); if(graph.level_of_node(node) == "knowledge") { std::list<KIDGraph::KIDNode>::iterator iter; iter = find(graph.knowledge_nodes.begin(), graph.knowledge_nodes.end(), (std::string)node); if(iter != graph.knowledge_nodes.end()) { std::list<KIDGraph::KIDNode*>::iterator subiter; KIDGraph::KIDNode *p; p = graph.get_node(node); for(subiter = iter->children.begin(); subiter != iter->children.end(); subiter++) { (*subiter)->parents.remove(p); } for(subiter = iter->parents.begin(); subiter != iter->parents.end(); subiter++) { (*subiter)->children.remove(p); } graph.knowledge_nodes.erase(iter); } } else if(graph.level_of_node(node) == "information") { std::list<KIDGraph::KIDNode>::iterator iter; iter = find(graph.information_nodes.begin(), graph.information_nodes.end(), (std::string)node); if(iter != graph.information_nodes.end()) { std::list<KIDGraph::KIDNode*>::iterator subiter; KIDGraph::KIDNode *p; p = graph.get_node(node); for(subiter = iter->children.begin(); subiter != iter->children.end(); subiter++) { (*subiter)->parents.remove(p); } for(subiter = iter->parents.begin(); subiter != iter->parents.end(); subiter++) { (*subiter)->children.remove(p); } graph.information_nodes.erase(iter); } } else if(graph.level_of_node(node) == "data") { std::list<KIDGraph::KIDNode>::iterator iter; iter = find(graph.data_nodes.begin(), graph.data_nodes.end(), (std::string)node); if(iter != graph.data_nodes.end()) { std::list<KIDGraph::KIDNode*>::iterator subiter; KIDGraph::KIDNode *p; p = graph.get_node(node); for(subiter = iter->children.begin(); subiter != iter->children.end(); subiter++) { (*subiter)->parents.remove(p); } for(subiter = iter->parents.begin(); subiter != iter->parents.end(); subiter++) { (*subiter)->children.remove(p); } graph.data_nodes.erase(iter); } } // remove edges that are no longer valid std::list<KIDGraph::KIDEdge>::iterator edgeiter; std::list<KIDGraph::KIDEdge> newedges; edg_store->clear(); Gtk::TreeModel::Row row; for(edgeiter = graph.edges.begin(); edgeiter != graph.edges.end(); edgeiter++) { if(!(edgeiter->from == node || edgeiter->to == node)) { row = *(edg_store->append()); row.set_value(0, edgeiter->toString()); newedges.push_back(*edgeiter); } } graph.edges = newedges; } com_graphs->get_active()->set_value(1,graph.save_to_string()); create_graphviz_dot(); } void KIDTab::on_unmark_clicked() { graph.clear_markup(); com_graphs->get_active()->set_value(1,graph.save_to_string()); create_graphviz_dot(); logger->log("kid", "unmarked graph"); } void KIDTab::on_edges_remove_clicked() { if(trv_edges->get_selection()->count_selected_rows() == 1) { Glib::ustring edge; trv_edges->get_selection()->get_selected()->get_value(0, edge); edg_store->erase(trv_edges->get_selection()->get_selected()); logger->log("kid", "removed edge: "+edge); std::list<KIDGraph::KIDEdge>::iterator iter; iter = find(graph.edges.begin(), graph.edges.end(), (std::string)edge); if(iter != graph.edges.end()) { KIDGraph::KIDNode *from; KIDGraph::KIDNode *to; from = graph.get_node(iter->from); from->parents.remove(to); to = graph.get_node(iter->to); to->children.remove(from); graph.edges.erase(iter); } } com_graphs->get_active()->set_value(1,graph.save_to_string()); create_graphviz_dot(); } bool KIDTab::on_graph_release(GdkEventButton *b) { std::string node = gda_graph->get_clicked_node(b->x, b->y); if(graph.is_node(node)) { if(b->button == 1) { if(find(db_collections.begin(), db_collections.end(), node) != db_collections.end()) { if(!win_show->get_visible()) { win_show->present(); logger->log("kid", "opening document window for node: "+node); } else logger->log("kid", "refreshing document window for node: "+node); // clear previous data win_store->clear(); win_images.clear(); // get new data from framework for selected collection node docreq = gazebo::msgs::CreateRequest("documents", node); framePub->Publish(*docreq); } else if (node != "") logger->log("kid", "node: "+node+" does not refer to a collection"); } else if(b->button == 3) { if(graph.is_marked(node)) { logger->log("kid", "unmark node: "+node); graph.unmark_node(node); com_graphs->get_active()->set_value(1,graph.save_to_string()); create_graphviz_dot(); } else { logger->log("kid", "mark node: "+node); graph.mark_node(node); com_graphs->get_active()->set_value(1,graph.save_to_string()); create_graphviz_dot(); } } } return false; } void KIDTab::on_document_changed() { // set textbuffer and image according to selection // send pointcloud to gazebo or remove currently shown one int id; if(win_combo->get_active_row_number() != -1) { win_combo->get_active()->get_value(1,id); win_image->set(win_images[id]); pclPub->Publish(win_pointclouds[id]); Glib::ustring doc; win_combo->get_active()->get_value(2,doc); win_textbuffer->set_text(Converter::parse_json(doc)); } else { win_image->set(Gtk::Stock::MISSING_IMAGE, Gtk::ICON_SIZE_BUTTON); gazebo::msgs::Drawing pcl; pcl.set_name("pointcloud"); pcl.set_visible(false); pclPub->Publish(pcl); win_textbuffer->set_text(""); } } void KIDTab::on_new_clicked() { // create new graph inside combobox Gtk::Window *w; _builder->get_widget("window", w); dia_new->set_transient_for(*w); int result = dia_new->run(); if (result == Gtk::RESPONSE_OK) { std::string __name = dia_new_entry->get_text(); std::string __graph = __name+"\n"; bool validname = true; Gtk::TreeModel::Children tmc = gra_store->children(); Gtk::TreeModel::iterator tmi = tmc.begin(); while(validname && tmi != tmc.end()) { std::string name; tmi->get_value(0, name); if(name == __name) validname = false; tmi++; } if(validname) { Gtk::TreeModel::Row row; row = *(gra_store->append()); row.set_value(0, __name); row.set_value(1, __graph); com_graphs->set_active(row); } else { Gtk::MessageDialog md(*w, "Graphname already exists", /* markup */ false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, /* modal */ true); md.set_title("Duplicate Graph Name"); md.run(); } } dia_new->hide(); } void KIDTab::on_load_clicked() { // load existing graph file into combobox (.kgf) Gtk::Window *w; _builder->get_widget("window", w); fcd_open->set_transient_for(*w); int result = fcd_open->run(); if (result == Gtk::RESPONSE_OK) { std::string filename = fcd_open->get_filename(); std::string __graph = ""; if (filename != "") { FILE *f = fopen(filename.c_str(), "r"); while (! feof(f)) { char tmp[4096]; size_t s; if ((s = fread(tmp, 1, 4096, f)) > 0) { __graph.append(tmp, s); } } fclose(f); size_t pos = __graph.find("\n"); std::string __name = __graph.substr(0, pos); Gtk::TreeModel::Row row; row = *(gra_store->append()); row.set_value(0, __name); row.set_value(1, __graph); com_graphs->set_active(row); } else { Gtk::MessageDialog md(*w, "Invalid filename", /* markup */ false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, /* modal */ true); md.set_title("Invalid File Name"); md.run(); } } fcd_open->hide(); } void KIDTab::on_save_clicked() { // save selected graph to file (.kgf) Gtk::Window *w; _builder->get_widget("window", w); fcd_save->set_transient_for(*w); int result = fcd_save->run(); if (result == Gtk::RESPONSE_OK) { std::string filename = fcd_save->get_filename(); if (filename != "") { size_t ext_pos = filename.rfind("."); std::string extension = ""; if(ext_pos != std::string::npos) { extension = filename.substr(ext_pos+1); std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); } if(extension != "kgf") filename += ".kgf"; graph.save(filename.c_str()); } else { Gtk::MessageDialog md(*w, "Invalid filename", /* markup */ false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, /* modal */ true); md.set_title("Invalid File Name"); md.run(); } } fcd_save->hide(); } void KIDTab::on_close_clicked() { // remove selected graph from combobox Gtk::TreeModel::iterator oldgraph = com_graphs->get_active(); Gtk::TreeModel::iterator newgraph = com_graphs->get_active(); newgraph++; if(newgraph == gra_store->children().end()) newgraph = gra_store->children().begin(); if(gra_store->children().size() == 1) { gra_store->clear(); } else { com_graphs->set_active(newgraph); gra_store->erase(oldgraph); } } void KIDTab::on_graphs_changed() { if(gra_store->children().size() == 0) { graph.load(""); nds_store->clear(); edg_store->clear(); } else { Glib::ustring g; com_graphs->get_active()->get_value(1,g); graph.load(g); nds_store->clear(); std::list<KIDGraph::KIDNode>::iterator iter; Gtk::TreeModel::Row row; for(iter = graph.knowledge_nodes.begin(); iter != graph.knowledge_nodes.end(); iter++) { row = *(nds_store->append()); row.set_value(0, iter->node); } for(iter = graph.information_nodes.begin(); iter != graph.information_nodes.end(); iter++) { row = *(nds_store->append()); row.set_value(0, iter->node); } for(iter = graph.data_nodes.begin(); iter != graph.data_nodes.end(); iter++) { row = *(nds_store->append()); row.set_value(0, iter->node); } edg_store->clear(); std::list<KIDGraph::KIDEdge>::iterator eiter; for(eiter = graph.edges.begin(); eiter != graph.edges.end(); eiter++) { row = *(edg_store->append()); row.set_value(0, eiter->toString()); } } create_graphviz_dot(); } void KIDTab::on_zoom_in_clicked() { gda_graph->zoom_in(); } void KIDTab::on_zoom_out_clicked() { gda_graph->zoom_out(); } void KIDTab::on_zoom_fit_clicked() { gda_graph->zoom_fit(); } void KIDTab::on_zoom_reset_clicked() { gda_graph->zoom_reset(); } void KIDTab::on_export_clicked() { gda_graph->save(); }
[ "bastian.klingen@rwth-aachen.de" ]
bastian.klingen@rwth-aachen.de
18652f923fc37c43a74a693d69929ae164b9f76c
98f0b92fc6d340f4846c5092bbca747af71bd748
/bistro/scheduler/RoundRobinSchedulerPolicy.h
e11f6a7d42609d678251802a208442f79205bd6d
[ "BSD-3-Clause" ]
permissive
runt18/bistro
3727a0f38487463414c6195673f551432c3e2c57
aa78b0eb66b4b2322a6d28a77388a35ef1bf6630
refs/heads/master
2020-07-25T18:56:31.742897
2015-07-11T05:54:44
2015-07-11T05:54:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
639
h
/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include "bistro/bistro/scheduler/SchedulerPolicy.h" namespace facebook { namespace bistro { class RoundRobinSchedulerPolicy : public SchedulerPolicy { public: int schedule(std::vector<JobWithNodes>& jobs, ResourcesByNodeType& resources_by_node, TaskRunnerCallback cb) override; }; }}
[ "lesha@fb.com" ]
lesha@fb.com
a9162b3758fc16de499f226462dd19585da66481
9bc1c6e0b743c2f421e89cbba443d7ca7ff55773
/src/rpcwallet.cpp
3287f02e5a8843c03c819010112d62fa0818b565
[ "MIT" ]
permissive
JOHN-XW/Star-Global-Coin
9cd57c3b8c3279a3647d147d932033c3c21624ba
d23c444547145f7e6c817a5872d6bd96616468c1
refs/heads/master
2021-06-21T14:26:49.971616
2017-09-05T07:38:45
2017-09-05T07:38:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
61,134
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "walletdb.h" #include "bitcoinrpc.h" #include "init.h" #include "base58.h" #include "version.h" using namespace json_spirit; using namespace std; int64 nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); std::string HelpRequiringPassphrase() { return pwalletMain->IsCrypted() ? "\nrequires wallet passphrase to be set with walletpassphrase first" : ""; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); if (fWalletUnlockMintOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Wallet unlocked for block minting only."); } void WalletTxToJSON(const CWalletTx& wtx, Object& entry) { int confirms = wtx.GetDepthInMainChain(); entry.push_back(Pair("confirmations", confirms)); if (wtx.IsCoinBase() || wtx.IsCoinStake()) entry.push_back(Pair("generated", true)); if (confirms) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime))); } entry.push_back(Pair("txid", wtx.GetHash().GetHex())); entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime())); entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived)); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const Value& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; } Value getinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info."); proxyType proxy; GetProxy(NET_IPV4, proxy); Object obj; obj.push_back(Pair("version", FormatFullVersion())); obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION)); obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint()))); obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake()))); obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply))); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string()))); obj.push_back(Pair("ip", addrSeenByPeer.ToStringIP())); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("testnet", fTestNet)); obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", pwalletMain->GetKeyPoolSize())); obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee))); if (pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000)); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } Value getnewpubkey(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewpubkey [account]\n" "Returns new public key for coinbase generation."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); vector<unsigned char> vchPubKey = newKey.Raw(); return HexStr(vchPubKey.begin(), vchPubKey.end()); } Value getnewaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress [account]\n" "Returns a new StarGlobalCoin address for receiving payments. " "If [account] is specified (recommended), it is added to the address book " "so payments received with the address will be credited to [account]."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey; scriptPubKey.SetDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } Value getaccountaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress <account>\n" "Returns the current StarGlobalCoin address for receiving payments to this account."); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); Value ret; ret = GetAccountAddress(strAccount).ToString(); return ret; } Value setaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount <StarGlobalCoinaddress> <account>\n" "Sets the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid StarGlobalCoin address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()]; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBookName(address.Get(), strAccount); return Value::null; } Value getaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccount <StarGlobalCoinaddress>\n" "Returns the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid StarGlobalCoin address"); string strAccount; map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty()) strAccount = (*mi).second; return strAccount; } Value getaddressesbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount <account>\n" "Returns the list of addresses for the given account."); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account Array ret; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } Value sendtoaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendtoaddress <StarGlobalCoinaddress> <amount> [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.000001" + HelpRequiringPassphrase()); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid StarGlobalCoin address"); // Amount int64 nAmount = AmountFromValue(params[1]); if (nAmount < MIN_TXOUT_AMOUNT) throw JSONRPCError(-101, "Send amount too small"); // Wallet comments CWalletTx wtx; if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value listaddressgroupings(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listaddressgroupings\n" "Lists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" "in past transactions"); Array jsonGroupings; map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances(); BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) { Array jsonGrouping; BOOST_FOREACH(CTxDestination address, grouping) { Array addressInfo; addressInfo.push_back(CBitcoinAddress(address).ToString()); addressInfo.push_back(ValueFromAmount(balances[address])); { LOCK(pwalletMain->cs_wallet); if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end()) addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second); } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; } Value signmessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "signmessage <StarGlobalCoinaddress> <message>\n" "Sign a message with the private key of an address"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } Value verifymessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage <StarGlobalCoinaddress> <signature> <message>\n" "Verify a signed message"); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CKey key; if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig)) return false; return (key.GetPubKey().GetID() == keyID); } Value getreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaddress <StarGlobalCoinaddress> [minconf=1]\n" "Returns the total amount received by <StarGlobalCoinaddress> in transactions with at least [minconf] confirmations."); // Bitcoin address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); CScript scriptPubKey; if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid StarGlobalCoin address"); scriptPubKey.SetDestination(address.Get()); if (!IsMine(*pwalletMain,scriptPubKey)) return (double)0.0; // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second; if (strName == strAccount) setAddress.insert(address); } } Value getreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaccount <account> [minconf=1]\n" "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations."); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress; GetAccountAddresses(strAccount, setAddress); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return (double)nAmount / (double)COIN; } int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth) { int64 nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal()) continue; int64 nGenerated, nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee); if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth) nBalance += nReceived; nBalance += nGenerated - nSent - nFee; } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } int64 GetAccountBalance(const string& strAccount, int nMinDepth) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth); } Value getbalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getbalance [account] [minconf=1]\n" "If [account] is not specified, returns the server's total available balance.\n" "If [account] is specified, returns the balance in the account."); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and getbalance '*' should always return the same number. int64 nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal()) continue; int64 allGeneratedImmature, allGeneratedMature, allFee; allGeneratedImmature = allGeneratedMature = allFee = 0; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount); if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived) nBalance += r.second; } BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent) nBalance -= r.second; nBalance -= allFee; nBalance += allGeneratedMature; } return ValueFromAmount(nBalance); } string strAccount = AccountFromValue(params[0]); int64 nBalance = GetAccountBalance(strAccount, nMinDepth); return ValueFromAmount(nBalance); } Value movecmd(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n" "Move from one account in your wallet to another."); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); int64 nAmount = AmountFromValue(params[2]); if (nAmount < MIN_TXOUT_AMOUNT) throw JSONRPCError(-101, "Send amount too small"); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); int64 nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; walletdb.WriteAccountingEntry(debit); // Credit CAccountingEntry credit; credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; walletdb.WriteAccountingEntry(credit); if (!walletdb.TxnCommit()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); return true; } Value sendfrom(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 6) throw runtime_error( "sendfrom <fromaccount> <toStarGlobalCoinaddress> <amount> [minconf=1] [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.000001" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid StarGlobalCoin address"); int64 nAmount = AmountFromValue(params[2]); if (nAmount < MIN_TXOUT_AMOUNT) throw JSONRPCError(-101, "Send amount too small"); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty()) wtx.mapValue["to"] = params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value sendmany(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n" "amounts are double-precision floating point numbers" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); Object sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); set<CBitcoinAddress> setAddress; vector<pair<CScript, int64> > vecSend; int64 totalAmount = 0; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid StarGlobalCoin address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64 nAmount = AmountFromValue(s.value_); if (nAmount < MIN_TXOUT_AMOUNT) throw JSONRPCError(-101, "Send amount too small"); totalAmount += nAmount; vecSend.push_back(make_pair(scriptPubKey, nAmount)); } EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); int64 nFeeRequired = 0; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired); if (!fCreated) { if (totalAmount + nFeeRequired > pwalletMain->GetBalance()) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); throw JSONRPCError(RPC_WALLET_ERROR, "Transaction creation failed"); } if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed"); return wtx.GetHash().GetHex(); } Value addmultisigaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n" "Add a nrequired-to-sign multisignature address to the wallet\"\n" "each key is a StarGlobalCoin address or hex-encoded public key\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); // Case 1: Bitcoin address and we have full public key: CBitcoinAddress address(ks); if (address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks.c_str())); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks.c_str())); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } // Case 2: hex public key else if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } else { throw runtime_error(" Invalid public key: "+ks); } } // Construct using pay-to-script-hash: CScript inner; inner.SetMultisig(nRequired, pubkeys); CScriptID innerID = inner.GetID(); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } struct tallyitem { int64 nAmount; int nConf; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); } }; Value ListReceived(const Array& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 1) fIncludeEmpty = params[1].get_bool(); // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal()) continue; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); } } // Reply Array ret; map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; int64 nAmount = 0; int nConf = std::numeric_limits<int>::max(); if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); } else { Object obj; obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { int64 nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; Object obj; obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } Value listreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaddress [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include addresses that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"address\" : receiving address\n" " \"account\" : the account of the receiving address\n" " \"amount\" : total amount received by the address\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, false); } Value listreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaccount [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include accounts that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"account\" : the account of the receiving addresses\n" " \"amount\" : total amount received by addresses with this account\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, true); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret) { int64 nGeneratedImmature, nGeneratedMature, nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount); bool fAllAccounts = (strAccount == string("*")); // Generated blocks assigned to account "" if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == "")) { Object entry; entry.push_back(Pair("account", string(""))); if (nGeneratedImmature) { entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan")); entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature))); } else { entry.push_back(Pair("category", "generate")); entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature))); } if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } // Sent if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) { Object entry; entry.push_back(Pair("account", strSentAccount)); entry.push_back(Pair("address", CBitcoinAddress(s.first).ToString())); entry.push_back(Pair("category", "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.second))); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.first)) account = pwalletMain->mapAddressBook[r.first]; if (fAllAccounts || (account == strAccount)) { Object entry; entry.push_back(Pair("account", account)); entry.push_back(Pair("address", CBitcoinAddress(r.first).ToString())); if (wtx.IsCoinBase()) { if (wtx.GetDepthInMainChain() < 1) entry.push_back(Pair("category", "orphan")); else if (wtx.GetBlocksToMaturity() > 0) entry.push_back(Pair("category", "immature")); else entry.push_back(Pair("category", "generate")); } else entry.push_back(Pair("category", "receive")); entry.push_back(Pair("amount", ValueFromAmount(r.second))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { Object entry; entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", (boost::int64_t)acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } Value listtransactions(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listtransactions [account] [count=10] [from=0]\n" "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]."); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); Array ret; std::list<CAccountingEntry> acentries; CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount); // iterate backwards until we have nCount items to return: for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; Array::iterator first = ret.begin(); std::advance(first, nFrom); Array::iterator last = ret.begin(); std::advance(last, nFrom+nCount); if (last != ret.end()) ret.erase(last, ret.end()); if (first != ret.begin()) ret.erase(ret.begin(), first); std::reverse(ret.begin(), ret.end()); // Return oldest to newest return ret; } Value listaccounts(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "listaccounts [minconf=1]\n" "Returns Object that has account names as keys, account balances as values."); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); map<string, int64> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first)) // This address belongs to me mapAccountBalances[entry.second] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; int64 nGeneratedImmature, nGeneratedMature, nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) mapAccountBalances[strSentAccount] -= s.second; if (wtx.GetDepthInMainChain() >= nMinDepth) { mapAccountBalances[""] += nGeneratedMature; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) if (pwalletMain->mapAddressBook.count(r.first)) mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second; else mapAccountBalances[""] += r.second; } } list<CAccountingEntry> acentries; CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries); BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; Object ret; BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } Value listsinceblock(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listsinceblock [blockhash] [target-confirmations]\n" "Get all transactions in blocks since block [blockhash], or all transactions if omitted"); CBlockIndex *pindex = NULL; int target_confirms = 1; if (params.size() > 0) { uint256 blockId = 0; blockId.SetHex(params[0].get_str()); pindex = CBlockLocator(blockId).GetBlockIndex(); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1; Array transactions; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain() < depth) ListTransactions(tx, "*", 0, true, transactions); } uint256 lastblock; if (target_confirms == 1) { lastblock = hashBestChain; } else { int target_height = pindexBest->nHeight + 1 - target_confirms; CBlockIndex *block; for (block = pindexBest; block && block->nHeight > target_height; block = block->pprev) { } lastblock = block ? block->GetBlockHash() : 0; } Object ret; ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } Value gettransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "gettransaction <txid>\n" "Get detailed information about <txid>"); uint256 hash; hash.SetHex(params[0].get_str()); Object entry; if (pwalletMain->mapWallet.count(hash)) { const CWalletTx& wtx = pwalletMain->mapWallet[hash]; TxToJSON(wtx, 0, entry); int64 nCredit = wtx.GetCredit(); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe()) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); Array details; ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details); entry.push_back(Pair("details", details)); } else { CTransaction tx; uint256 hashBlock = 0; if (GetTransaction(hash, tx, hashBlock)) { entry.push_back(Pair("txid", hash.GetHex())); TxToJSON(tx, 0, entry); if (hashBlock == 0) entry.push_back(Pair("confirmations", 0)); else { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) { entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); entry.push_back(Pair("txntime", (boost::int64_t)tx.nTime)); entry.push_back(Pair("time", (boost::int64_t)pindex->nTime)); } else entry.push_back(Pair("confirmations", 0)); } } } else throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); } return entry; } Value backupwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "backupwallet <destination>\n" "Safely copies wallet.dat to destination, which can be a directory or a path with filename."); string strDest = params[0].get_str(); if (!BackupWallet(*pwalletMain, strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); return Value::null; } Value keypoolrefill(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "keypoolrefill\n" "Fills the keypool." + HelpRequiringPassphrase()); EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(); if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100)) throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); return Value::null; } void ThreadTopUpKeyPool(void* parg) { // Make this thread recognisable as the key-topping-up thread RenameThread("bitcoin-key-top"); pwalletMain->TopUpKeyPool(); } void ThreadCleanWalletPassphrase(void* parg) { // Make this thread recognisable as the wallet relocking thread RenameThread("bitcoin-lock-wa"); int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000; ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); if (nWalletUnlockTime == 0) { nWalletUnlockTime = nMyWakeTime; do { if (nWalletUnlockTime==0) break; int64 nToSleep = nWalletUnlockTime - GetTimeMillis(); if (nToSleep <= 0) break; LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); Sleep(nToSleep); ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); } while(1); if (nWalletUnlockTime) { nWalletUnlockTime = 0; pwalletMain->Lock(); } } else { if (nWalletUnlockTime < nMyWakeTime) nWalletUnlockTime = nMyWakeTime; } LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); delete (int64*)parg; } Value walletpassphrase(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3)) throw runtime_error( "walletpassphrase <passphrase> <timeout> [mintonly]\n" "Stores the wallet decryption key in memory for <timeout> seconds.\n" "mintonly is optional true/false allowing only block minting."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); if (!pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked, use walletlock first if need to change unlock settings."); /* if (!pwalletMain->IsLocked()) { if (params.size() > 2) fWalletUnlockMintOnly = params[2].get_bool(); else fWalletUnlockMintOnly = false; return true; }*/ // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() > 0) { if (!pwalletMain->Unlock(strWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); } else throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); NewThread(ThreadTopUpKeyPool, NULL); int64* pnSleepTime = new int64(params[1].get_int64()); NewThread(ThreadCleanWalletPassphrase, pnSleepTime); // ppcoin: if user OS account compromised prevent trivial sendmoney commands if (params.size() > 2) fWalletUnlockMintOnly = params[2].get_bool(); else fWalletUnlockMintOnly = false; return Value::null; } Value walletpassphrasechange(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); return Value::null; } Value walletlock(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "Removes the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return Value::null; } Value encryptwallet(const Array& params, bool fHelp) { if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "wallet encrypted; StarGlobalCoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup."; } class DescribeAddressVisitor : public boost::static_visitor<Object> { public: Object operator()(const CNoDestination &dest) const { return Object(); } Object operator()(const CKeyID &keyID) const { Object obj; CPubKey vchPubKey; pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("isscript", false)); obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw()))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); return obj; } Object operator()(const CScriptID &scriptID) const { Object obj; obj.push_back(Pair("isscript", true)); CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); return obj; } }; Value validateaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress <StarGlobalCoinaddress>\n" "Return information about <StarGlobalCoinaddress>."); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = IsMine(*pwalletMain, dest); ret.push_back(Pair("ismine", fMine)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } Value validatepubkey(const Array& params, bool fHelp) { if (fHelp || !params.size() || params.size() > 2) throw runtime_error( "validatepubkey <StarGlobalCoinpubkey>\n" "Return information about <StarGlobalCoinpubkey>."); std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str()); CPubKey pubKey(vchPubKey); bool isValid = pubKey.IsValid(); bool isCompressed = pubKey.IsCompressed(); CKeyID keyID = pubKey.GetID(); CBitcoinAddress address; address.Set(keyID); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = IsMine(*pwalletMain, dest); ret.push_back(Pair("ismine", fMine)); ret.push_back(Pair("iscompressed", isCompressed)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } // ppcoin: reserve balance from being staked for network protection Value reservebalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "reservebalance [<reserve> [amount]]\n" "<reserve> is true or false to turn balance reserve on or off.\n" "<amount> is a real and rounded to cent.\n" "Set reserve amount not participating in network protection.\n" "If no parameters provided current setting is printed.\n"); if (params.size() > 0) { bool fReserve = params[0].get_bool(); if (fReserve) { if (params.size() == 1) throw runtime_error("must provide amount to reserve balance.\n"); int64 nAmount = AmountFromValue(params[1]); nAmount = (nAmount / CENT) * CENT; // round to cent if (nAmount < 0) throw runtime_error("amount cannot be negative.\n"); mapArgs["-reservebalance"] = FormatMoney(nAmount).c_str(); } else { if (params.size() > 1) throw runtime_error("cannot specify amount to turn off reserve.\n"); mapArgs["-reservebalance"] = "0"; } } Object result; int64 nReserveBalance = 0; if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) throw runtime_error("invalid reserve balance amount\n"); result.push_back(Pair("reserve", (nReserveBalance > 0))); result.push_back(Pair("amount", ValueFromAmount(nReserveBalance))); return result; } // ppcoin: check wallet integrity Value checkwallet(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "checkwallet\n" "Check wallet for integrity.\n"); int nMismatchSpent; int64 nBalanceInQuestion; pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion, true); Object result; if (nMismatchSpent == 0) result.push_back(Pair("wallet check passed", true)); else { result.push_back(Pair("mismatched spent coins", nMismatchSpent)); result.push_back(Pair("amount in question", ValueFromAmount(nBalanceInQuestion))); } return result; } // ppcoin: repair wallet Value repairwallet(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "repairwallet\n" "Repair wallet if checkwallet reports any problem.\n"); int nMismatchSpent; int64 nBalanceInQuestion; pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion); Object result; if (nMismatchSpent == 0) result.push_back(Pair("wallet check passed", true)); else { result.push_back(Pair("mismatched spent coins", nMismatchSpent)); result.push_back(Pair("amount affected by repair", ValueFromAmount(nBalanceInQuestion))); } return result; } // StarGlobalCoin: resend unconfirmed wallet transactions Value resendtx(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "resendtx\n" "Re-send unconfirmed transactions.\n" ); ResendWalletTransactions(); return Value::null; } // ppcoin: make a public-private key pair Value makekeypair(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "makekeypair [prefix]\n" "Make a public/private key pair.\n" "[prefix] is optional preferred prefix for the public key.\n"); string strPrefix = ""; if (params.size() > 0) strPrefix = params[0].get_str(); CKey key; key.MakeNewKey(false); CPrivKey vchPrivKey = key.GetPrivKey(); Object result; result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end()))); result.push_back(Pair("PublicKey", HexStr(key.GetPubKey().Raw()))); return result; }
[ "github123456" ]
github123456
920cc9bfd12a82fa2d3856b4b869dcf263956f94
81361fbb260f3a43f2dfd05474c1bb06c5160d9c
/Codeforces/Accepted/25A.cpp
f9633c4b2badf2b734e54dfb39db97670a0ebeea
[]
no_license
enamcse/ACM-Programming-Codes
9307a22aafb0be6d8f64920e46144f2f813c493a
70b57c35ec551eae6322959857b3ac37bcf615fa
refs/heads/master
2022-10-09T19:35:54.894241
2022-09-30T01:26:24
2022-09-30T01:26:24
33,211,745
3
2
null
null
null
null
UTF-8
C++
false
false
950
cpp
#include <bits/stdc++.h> #define _ ios_base::sync_with_stdio(0);cin.tie(0); #define sz 100 #define pb(a) push_back(a) #define pp pop_back() #define ll long long #define fread freopen("input.txt","r",stdin) #define fwrite freopen("output.txt","w",stdout) #define inf (1<<30-1) #define chng(a,b) a^=b^=a^=b; #define clr(abc,z) memset(abc,z,sizeof(abc)) #define PI acos(-1) using namespace std; int num[111]; int main() { _ int n, e=0,o=0; cin>>n; for (int i = 0; i<n; i++) cin>>num[i]; for (int i = 0; i<3; i++) if(num[i]%2) o++; else e++; if(o>e) { for (int i = 0; i<n; i++) if(num[i]%2==0) { cout<<i+1; break; } } else { for (int i = 0; i<n; i++) if(num[i]%2) { cout<<i+1; break; } } return 0; }
[ "enamsustcse@gmail.com" ]
enamsustcse@gmail.com
160e32e29ee3cb2e6708bb9d76a2bd487a3df84a
9fad4848e43f4487730185e4f50e05a044f865ab
/src/chrome/browser/download/download_history_unittest.cc
63961ccaf8626c91cdb9cad25ff11a2d8aee067d
[ "BSD-3-Clause" ]
permissive
dummas2008/chromium
d1b30da64f0630823cb97f58ec82825998dbb93e
82d2e84ce3ed8a00dc26c948219192c3229dfdaa
refs/heads/master
2020-12-31T07:18:45.026190
2016-04-14T03:17:45
2016-04-14T03:17:45
56,194,439
4
0
null
null
null
null
UTF-8
C++
false
false
34,544
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/download/download_history.h" #include <stddef.h> #include <stdint.h> #include <utility> #include <vector> #include "base/guid.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/rand_util.h" #include "base/stl_util.h" #include "components/history/content/browser/download_constants_utils.h" #include "components/history/core/browser/download_constants.h" #include "components/history/core/browser/download_row.h" #include "components/history/core/browser/history_service.h" #include "content/public/test/mock_download_item.h" #include "content/public/test/mock_download_manager.h" #include "content/public/test/test_browser_thread.h" #include "content/public/test/test_utils.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(ENABLE_EXTENSIONS) #include "chrome/browser/extensions/api/downloads/downloads_api.h" #endif using testing::DoAll; using testing::Invoke; using testing::Return; using testing::ReturnRefOfCopy; using testing::SetArgPointee; using testing::WithArg; using testing::_; namespace { typedef DownloadHistory::IdSet IdSet; typedef std::vector<history::DownloadRow> InfoVector; typedef testing::StrictMock<content::MockDownloadItem> StrictMockDownloadItem; class FakeHistoryAdapter : public DownloadHistory::HistoryAdapter { public: FakeHistoryAdapter() : DownloadHistory::HistoryAdapter(NULL), slow_create_download_(false), fail_create_download_(false) { } ~FakeHistoryAdapter() override {} void QueryDownloads( const history::HistoryService::DownloadQueryCallback& callback) override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, base::Bind(&FakeHistoryAdapter::QueryDownloadsDone, base::Unretained(this), callback)); } void QueryDownloadsDone( const history::HistoryService::DownloadQueryCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); CHECK(expect_query_downloads_.get()); callback.Run(std::move(expect_query_downloads_)); } void set_slow_create_download(bool slow) { slow_create_download_ = slow; } void CreateDownload(const history::DownloadRow& info, const history::HistoryService::DownloadCreateCallback& callback) override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); create_download_info_ = info; // Must not call CreateDownload() again before FinishCreateDownload()! DCHECK(create_download_callback_.is_null()); create_download_callback_ = base::Bind(callback, !fail_create_download_); fail_create_download_ = false; if (!slow_create_download_) FinishCreateDownload(); } void FinishCreateDownload() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); create_download_callback_.Run(); create_download_callback_.Reset(); } void UpdateDownload(const history::DownloadRow& info) override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); update_download_ = info; } void RemoveDownloads(const IdSet& ids) override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); for (IdSet::const_iterator it = ids.begin(); it != ids.end(); ++it) { remove_downloads_.insert(*it); } } void ExpectWillQueryDownloads(std::unique_ptr<InfoVector> infos) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); expect_query_downloads_ = std::move(infos); } void ExpectQueryDownloadsDone() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); EXPECT_TRUE(NULL == expect_query_downloads_.get()); } void FailCreateDownload() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); fail_create_download_ = true; } void ExpectDownloadCreated( const history::DownloadRow& info) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RunAllPendingInMessageLoop(content::BrowserThread::UI); EXPECT_EQ(info, create_download_info_); create_download_info_ = history::DownloadRow(); } void ExpectNoDownloadCreated() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RunAllPendingInMessageLoop(content::BrowserThread::UI); EXPECT_EQ(history::DownloadRow(), create_download_info_); } void ExpectDownloadUpdated(const history::DownloadRow& info) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RunAllPendingInMessageLoop(content::BrowserThread::UI); EXPECT_EQ(update_download_, info); update_download_ = history::DownloadRow(); } void ExpectNoDownloadUpdated() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RunAllPendingInMessageLoop(content::BrowserThread::UI); EXPECT_EQ(history::DownloadRow(), update_download_); } void ExpectNoDownloadsRemoved() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RunAllPendingInMessageLoop(content::BrowserThread::UI); EXPECT_EQ(0, static_cast<int>(remove_downloads_.size())); } void ExpectDownloadsRemoved(const IdSet& ids) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RunAllPendingInMessageLoop(content::BrowserThread::UI); IdSet differences = base::STLSetDifference<IdSet>(ids, remove_downloads_); for (IdSet::const_iterator different = differences.begin(); different != differences.end(); ++different) { EXPECT_TRUE(false) << *different; } remove_downloads_.clear(); } private: bool slow_create_download_; bool fail_create_download_; base::Closure create_download_callback_; history::DownloadRow update_download_; std::unique_ptr<InfoVector> expect_query_downloads_; IdSet remove_downloads_; history::DownloadRow create_download_info_; DISALLOW_COPY_AND_ASSIGN(FakeHistoryAdapter); }; class TestDownloadHistoryObserver : public DownloadHistory::Observer { public: void OnHistoryQueryComplete() override { on_history_query_complete_called_ = true; } bool on_history_query_complete_called_ = false; }; class DownloadHistoryTest : public testing::Test { public: // Generic callback that receives a pointer to a StrictMockDownloadItem. typedef base::Callback<void(content::MockDownloadItem*)> DownloadItemCallback; DownloadHistoryTest() : ui_thread_(content::BrowserThread::UI, &loop_), manager_(new content::MockDownloadManager()), history_(NULL), manager_observer_(NULL), download_created_index_(0) {} ~DownloadHistoryTest() override { STLDeleteElements(&items_); } protected: void TearDown() override { download_history_.reset(); } content::MockDownloadManager& manager() { return *manager_.get(); } content::MockDownloadItem& item(size_t index) { return *items_[index]; } DownloadHistory* download_history() { return download_history_.get(); } void SetManagerObserver( content::DownloadManager::Observer* manager_observer) { manager_observer_ = manager_observer; } content::DownloadManager::Observer* manager_observer() { return manager_observer_; } void CreateDownloadHistory(std::unique_ptr<InfoVector> infos) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); CHECK(infos.get()); EXPECT_CALL(manager(), AddObserver(_)).WillOnce(WithArg<0>(Invoke( this, &DownloadHistoryTest::SetManagerObserver))); EXPECT_CALL(manager(), RemoveObserver(_)); download_created_index_ = 0; for (size_t index = 0; index < infos->size(); ++index) { const history::DownloadRow& row = infos->at(index); content::MockDownloadManager::CreateDownloadItemAdapter adapter( row.guid, history::ToContentDownloadId(row.id), row.current_path, row.target_path, row.url_chain, row.referrer_url, row.mime_type, row.original_mime_type, row.start_time, row.end_time, row.etag, row.last_modified, row.received_bytes, row.total_bytes, std::string(), history::ToContentDownloadState(row.state), history::ToContentDownloadDangerType(row.danger_type), history::ToContentDownloadInterruptReason(row.interrupt_reason), row.opened); EXPECT_CALL(manager(), MockCreateDownloadItem(adapter)) .WillOnce(DoAll( InvokeWithoutArgs( this, &DownloadHistoryTest::CallOnDownloadCreatedInOrder), Return(&item(index)))); } EXPECT_CALL(manager(), CheckForHistoryFilesRemoval()); history_ = new FakeHistoryAdapter(); history_->ExpectWillQueryDownloads(std::move(infos)); EXPECT_CALL(*manager_.get(), GetAllDownloads(_)).WillRepeatedly(Return()); download_history_.reset(new DownloadHistory( &manager(), std::unique_ptr<DownloadHistory::HistoryAdapter>(history_))); content::RunAllPendingInMessageLoop(content::BrowserThread::UI); history_->ExpectQueryDownloadsDone(); } void CallOnDownloadCreated(size_t index) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!pre_on_create_handler_.is_null()) pre_on_create_handler_.Run(&item(index)); manager_observer()->OnDownloadCreated(&manager(), &item(index)); if (!post_on_create_handler_.is_null()) post_on_create_handler_.Run(&item(index)); } void CallOnDownloadCreatedInOrder() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // Gmock doesn't appear to support something like InvokeWithTheseArgs. Maybe // gmock needs to learn about base::Callback. CallOnDownloadCreated(download_created_index_++); } void set_slow_create_download(bool slow) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); history_->set_slow_create_download(slow); } void FinishCreateDownload() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); history_->FinishCreateDownload(); } void FailCreateDownload() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); history_->FailCreateDownload(); } void ExpectDownloadCreated( const history::DownloadRow& info) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); history_->ExpectDownloadCreated(info); } void ExpectNoDownloadCreated() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); history_->ExpectNoDownloadCreated(); } void ExpectDownloadUpdated(const history::DownloadRow& info) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); history_->ExpectDownloadUpdated(info); } void ExpectNoDownloadUpdated() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); history_->ExpectNoDownloadUpdated(); } void ExpectNoDownloadsRemoved() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); history_->ExpectNoDownloadsRemoved(); } void ExpectDownloadsRemoved(const IdSet& ids) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); history_->ExpectDownloadsRemoved(ids); } void ExpectDownloadsRestoredFromHistory(bool expected_value) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); pre_on_create_handler_ = base::Bind(&DownloadHistoryTest::CheckDownloadWasRestoredFromHistory, base::Unretained(this), expected_value); post_on_create_handler_ = base::Bind(&DownloadHistoryTest::CheckDownloadWasRestoredFromHistory, base::Unretained(this), expected_value); } void InitBasicItem(const base::FilePath::CharType* path, const char* url_string, const char* referrer_string, history::DownloadRow* info) { GURL url(url_string); GURL referrer(referrer_string); std::vector<GURL> url_chain; url_chain.push_back(url); InitItem(base::GenerateGUID(), static_cast<uint32_t>(items_.size() + 1), base::FilePath(path), base::FilePath(path), url_chain, referrer, "application/octet-stream", "application/octet-stream", (base::Time::Now() - base::TimeDelta::FromMinutes(10)), (base::Time::Now() - base::TimeDelta::FromMinutes(1)), "Etag", "abc", 100, 100, content::DownloadItem::COMPLETE, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, content::DOWNLOAD_INTERRUPT_REASON_NONE, false, std::string(), std::string(), info); } void InitItem(const std::string& guid, uint32_t id, const base::FilePath& current_path, const base::FilePath& target_path, const std::vector<GURL>& url_chain, const GURL& referrer, const std::string& mime_type, const std::string& original_mime_type, const base::Time& start_time, const base::Time& end_time, const std::string& etag, const std::string& last_modified, int64_t received_bytes, int64_t total_bytes, content::DownloadItem::DownloadState state, content::DownloadDangerType danger_type, content::DownloadInterruptReason interrupt_reason, bool opened, const std::string& by_extension_id, const std::string& by_extension_name, history::DownloadRow* info) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); size_t index = items_.size(); StrictMockDownloadItem* mock_item = new StrictMockDownloadItem(); items_.push_back(mock_item); info->current_path = current_path; info->target_path = target_path; info->url_chain = url_chain; info->referrer_url = referrer; info->mime_type = mime_type; info->original_mime_type = original_mime_type; info->start_time = start_time; info->end_time = end_time; info->etag = etag; info->last_modified = last_modified; info->received_bytes = received_bytes; info->total_bytes = total_bytes; info->state = history::ToHistoryDownloadState(state); info->danger_type = history::ToHistoryDownloadDangerType(danger_type); info->interrupt_reason = history::ToHistoryDownloadInterruptReason(interrupt_reason); info->id = history::ToHistoryDownloadId(id); info->guid = guid; info->opened = opened; info->by_ext_id = by_extension_id; info->by_ext_name = by_extension_name; EXPECT_CALL(item(index), GetId()).WillRepeatedly(Return(id)); EXPECT_CALL(item(index), GetGuid()).WillRepeatedly(ReturnRefOfCopy(guid)); EXPECT_CALL(item(index), GetFullPath()) .WillRepeatedly(ReturnRefOfCopy(current_path)); EXPECT_CALL(item(index), GetTargetFilePath()) .WillRepeatedly(ReturnRefOfCopy(target_path)); DCHECK_LE(1u, url_chain.size()); EXPECT_CALL(item(index), GetURL()) .WillRepeatedly(ReturnRefOfCopy(url_chain[0])); EXPECT_CALL(item(index), GetUrlChain()) .WillRepeatedly(ReturnRefOfCopy(url_chain)); EXPECT_CALL(item(index), GetMimeType()).WillRepeatedly(Return(mime_type)); EXPECT_CALL(item(index), GetOriginalMimeType()).WillRepeatedly(Return( original_mime_type)); EXPECT_CALL(item(index), GetReferrerUrl()) .WillRepeatedly(ReturnRefOfCopy(referrer)); EXPECT_CALL(item(index), GetStartTime()).WillRepeatedly(Return(start_time)); EXPECT_CALL(item(index), GetEndTime()).WillRepeatedly(Return(end_time)); EXPECT_CALL(item(index), GetETag()).WillRepeatedly(ReturnRefOfCopy(etag)); EXPECT_CALL(item(index), GetLastModifiedTime()) .WillRepeatedly(ReturnRefOfCopy(last_modified)); EXPECT_CALL(item(index), GetReceivedBytes()) .WillRepeatedly(Return(received_bytes)); EXPECT_CALL(item(index), GetTotalBytes()) .WillRepeatedly(Return(total_bytes)); EXPECT_CALL(item(index), GetState()).WillRepeatedly(Return(state)); EXPECT_CALL(item(index), GetDangerType()) .WillRepeatedly(Return(danger_type)); EXPECT_CALL(item(index), GetLastReason()) .WillRepeatedly(Return(interrupt_reason)); EXPECT_CALL(item(index), GetOpened()).WillRepeatedly(Return(opened)); EXPECT_CALL(item(index), GetTargetDisposition()) .WillRepeatedly( Return(content::DownloadItem::TARGET_DISPOSITION_OVERWRITE)); EXPECT_CALL(manager(), GetDownload(id)) .WillRepeatedly(Return(&item(index))); EXPECT_CALL(item(index), IsTemporary()).WillRepeatedly(Return(false)); #if defined(ENABLE_EXTENSIONS) new extensions::DownloadedByExtension( &item(index), by_extension_id, by_extension_name); #endif std::vector<content::DownloadItem*> items; for (size_t i = 0; i < items_.size(); ++i) { items.push_back(&item(i)); } EXPECT_CALL(*manager_.get(), GetAllDownloads(_)) .WillRepeatedly(SetArgPointee<0>(items)); } private: void CheckDownloadWasRestoredFromHistory(bool expected_value, content::MockDownloadItem* item) { ASSERT_TRUE(download_history_.get()); EXPECT_EQ(expected_value, download_history_->WasRestoredFromHistory(item)); } base::MessageLoopForUI loop_; content::TestBrowserThread ui_thread_; std::vector<StrictMockDownloadItem*> items_; std::unique_ptr<content::MockDownloadManager> manager_; FakeHistoryAdapter* history_; std::unique_ptr<DownloadHistory> download_history_; content::DownloadManager::Observer* manager_observer_; size_t download_created_index_; DownloadItemCallback pre_on_create_handler_; DownloadItemCallback post_on_create_handler_; DISALLOW_COPY_AND_ASSIGN(DownloadHistoryTest); }; // Test loading an item from the database, changing it, saving it back, removing // it. TEST_F(DownloadHistoryTest, DownloadHistoryTest_Load) { // Load a download from history, create the item, OnDownloadCreated, // OnDownloadUpdated, OnDownloadRemoved. history::DownloadRow info; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", &info); { std::unique_ptr<InfoVector> infos(new InfoVector()); infos->push_back(info); CreateDownloadHistory(std::move(infos)); ExpectNoDownloadCreated(); } EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); // Pretend that something changed on the item. EXPECT_CALL(item(0), GetOpened()).WillRepeatedly(Return(true)); item(0).NotifyObserversDownloadUpdated(); info.opened = true; ExpectDownloadUpdated(info); // Pretend that the user removed the item. IdSet ids; ids.insert(info.id); item(0).NotifyObserversDownloadRemoved(); ExpectDownloadsRemoved(ids); } // Test that the OnHistoryQueryComplete() observer method is invoked for an // observer that was added before the initial history query completing. TEST_F(DownloadHistoryTest, DownloadHistoryTest_OnHistoryQueryComplete_Pre) { class TestHistoryAdapter : public DownloadHistory::HistoryAdapter { public: TestHistoryAdapter( history::HistoryService::DownloadQueryCallback* callback_storage) : HistoryAdapter(nullptr), query_callback_(callback_storage) {} void QueryDownloads(const history::HistoryService::DownloadQueryCallback& callback) override { *query_callback_ = callback; } history::HistoryService::DownloadQueryCallback* query_callback_; }; TestDownloadHistoryObserver observer; history::HistoryService::DownloadQueryCallback query_callback; std::unique_ptr<TestHistoryAdapter> test_history_adapter( new TestHistoryAdapter(&query_callback)); // Create a new DownloadHistory object. This should cause // TestHistoryAdapter::QueryDownloads() to be called. The TestHistoryAdapter // stored the completion callback. std::unique_ptr<DownloadHistory> history( new DownloadHistory(&manager(), std::move(test_history_adapter))); history->AddObserver(&observer); EXPECT_FALSE(observer.on_history_query_complete_called_); ASSERT_FALSE(query_callback.is_null()); // Now invoke the query completion callback. std::unique_ptr<std::vector<history::DownloadRow>> query_results( new std::vector<history::DownloadRow>()); query_callback.Run(std::move(query_results)); EXPECT_TRUE(observer.on_history_query_complete_called_); history->RemoveObserver(&observer); } // Test that the OnHistoryQueryComplete() observer method is invoked for an // observer that was added after the initial history query completing. TEST_F(DownloadHistoryTest, DownloadHistoryTest_OnHistoryQueryComplete_Post) { TestDownloadHistoryObserver observer; CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); download_history()->AddObserver(&observer); EXPECT_TRUE(observer.on_history_query_complete_called_); download_history()->RemoveObserver(&observer); } // Test that WasRestoredFromHistory accurately identifies downloads that were // created from history, even during an OnDownloadCreated() handler. TEST_F(DownloadHistoryTest, DownloadHistoryTest_WasRestoredFromHistory_True) { // This sets DownloadHistoryTest to call DH::WasRestoredFromHistory() both // before and after DH::OnDownloadCreated() is called. At each call, the // expected return value is |true| since the download was restored from // history. ExpectDownloadsRestoredFromHistory(true); // Construct a DownloadHistory with a single history download. This results in // DownloadManager::CreateDownload() being called for the restored download. // The above test expectation should verify that the value of // WasRestoredFromHistory is correct for this download. history::DownloadRow info; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", &info); std::unique_ptr<InfoVector> infos(new InfoVector()); infos->push_back(info); CreateDownloadHistory(std::move(infos)); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); } // Test that WasRestoredFromHistory accurately identifies downloads that were // not created from history. TEST_F(DownloadHistoryTest, DownloadHistoryTest_WasRestoredFromHistory_False) { // This sets DownloadHistoryTest to call DH::WasRestoredFromHistory() both // before and after DH::OnDownloadCreated() is called. At each call, the // expected return value is |true| since the download was restored from // history. ExpectDownloadsRestoredFromHistory(false); // Create a DownloadHistory with no history downloads. No // DownloadManager::CreateDownload() calls are expected. CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); // Notify DownloadHistory that a new download was created. The above test // expecation should verify that WasRestoredFromHistory is correct for this // download. history::DownloadRow info; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", &info); CallOnDownloadCreated(0); ExpectDownloadCreated(info); } // Test creating an item, saving it to the database, changing it, saving it // back, removing it. TEST_F(DownloadHistoryTest, DownloadHistoryTest_Create) { // Create a fresh item not from history, OnDownloadCreated, OnDownloadUpdated, // OnDownloadRemoved. CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); history::DownloadRow info; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", &info); // Pretend the manager just created |item|. CallOnDownloadCreated(0); ExpectDownloadCreated(info); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); // Pretend that something changed on the item. EXPECT_CALL(item(0), GetOpened()).WillRepeatedly(Return(true)); item(0).NotifyObserversDownloadUpdated(); info.opened = true; ExpectDownloadUpdated(info); // Pretend that the user removed the item. IdSet ids; ids.insert(info.id); item(0).NotifyObserversDownloadRemoved(); ExpectDownloadsRemoved(ids); } // Test that changes to persisted fields in a DownloadItem triggers database // updates. TEST_F(DownloadHistoryTest, DownloadHistoryTest_Update) { CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); history::DownloadRow info; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", &info); CallOnDownloadCreated(0); ExpectDownloadCreated(info); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); base::FilePath new_path(FILE_PATH_LITERAL("/foo/baz.txt")); base::Time new_time(base::Time::Now()); std::string new_etag("new etag"); std::string new_last_modifed("new last modified"); // current_path EXPECT_CALL(item(0), GetFullPath()).WillRepeatedly(ReturnRefOfCopy(new_path)); info.current_path = new_path; item(0).NotifyObserversDownloadUpdated(); ExpectDownloadUpdated(info); // target_path EXPECT_CALL(item(0), GetTargetFilePath()) .WillRepeatedly(ReturnRefOfCopy(new_path)); info.target_path = new_path; item(0).NotifyObserversDownloadUpdated(); ExpectDownloadUpdated(info); // end_time EXPECT_CALL(item(0), GetEndTime()).WillRepeatedly(Return(new_time)); info.end_time = new_time; item(0).NotifyObserversDownloadUpdated(); ExpectDownloadUpdated(info); // received_bytes EXPECT_CALL(item(0), GetReceivedBytes()).WillRepeatedly(Return(101)); info.received_bytes = 101; item(0).NotifyObserversDownloadUpdated(); ExpectDownloadUpdated(info); // total_bytes EXPECT_CALL(item(0), GetTotalBytes()).WillRepeatedly(Return(102)); info.total_bytes = 102; item(0).NotifyObserversDownloadUpdated(); ExpectDownloadUpdated(info); // etag EXPECT_CALL(item(0), GetETag()).WillRepeatedly(ReturnRefOfCopy(new_etag)); info.etag = new_etag; item(0).NotifyObserversDownloadUpdated(); ExpectDownloadUpdated(info); // last_modified EXPECT_CALL(item(0), GetLastModifiedTime()) .WillRepeatedly(ReturnRefOfCopy(new_last_modifed)); info.last_modified = new_last_modifed; item(0).NotifyObserversDownloadUpdated(); ExpectDownloadUpdated(info); // state EXPECT_CALL(item(0), GetState()) .WillRepeatedly(Return(content::DownloadItem::INTERRUPTED)); info.state = history::DownloadState::INTERRUPTED; item(0).NotifyObserversDownloadUpdated(); ExpectDownloadUpdated(info); // danger_type EXPECT_CALL(item(0), GetDangerType()) .WillRepeatedly(Return(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT)); info.danger_type = history::DownloadDangerType::DANGEROUS_CONTENT; item(0).NotifyObserversDownloadUpdated(); ExpectDownloadUpdated(info); // interrupt_reason EXPECT_CALL(item(0), GetLastReason()) .WillRepeatedly(Return(content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED)); info.interrupt_reason = history::ToHistoryDownloadInterruptReason( content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED); item(0).NotifyObserversDownloadUpdated(); ExpectDownloadUpdated(info); // opened EXPECT_CALL(item(0), GetOpened()).WillRepeatedly(Return(true)); info.opened = true; item(0).NotifyObserversDownloadUpdated(); ExpectDownloadUpdated(info); } // Test creating a new item, saving it, removing it by setting it Temporary, // changing it without saving it back because it's Temporary, clearing // IsTemporary, saving it back, changing it, saving it back because it isn't // Temporary anymore. TEST_F(DownloadHistoryTest, DownloadHistoryTest_Temporary) { // Create a fresh item not from history, OnDownloadCreated, OnDownloadUpdated, // OnDownloadRemoved. CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); history::DownloadRow info; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", &info); // Pretend the manager just created |item|. CallOnDownloadCreated(0); ExpectDownloadCreated(info); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); // Pretend the item was marked temporary. DownloadHistory should remove it // from history and start ignoring it. EXPECT_CALL(item(0), IsTemporary()).WillRepeatedly(Return(true)); item(0).NotifyObserversDownloadUpdated(); IdSet ids; ids.insert(info.id); ExpectDownloadsRemoved(ids); // Change something that would make DownloadHistory call UpdateDownload if the // item weren't temporary. EXPECT_CALL(item(0), GetReceivedBytes()).WillRepeatedly(Return(4200)); item(0).NotifyObserversDownloadUpdated(); ExpectNoDownloadUpdated(); // Changing a temporary item back to a non-temporary item should make // DownloadHistory call CreateDownload. EXPECT_CALL(item(0), IsTemporary()).WillRepeatedly(Return(false)); item(0).NotifyObserversDownloadUpdated(); info.received_bytes = 4200; ExpectDownloadCreated(info); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); EXPECT_CALL(item(0), GetReceivedBytes()).WillRepeatedly(Return(100)); item(0).NotifyObserversDownloadUpdated(); info.received_bytes = 100; ExpectDownloadUpdated(info); } // Test removing downloads while they're still being added. TEST_F(DownloadHistoryTest, DownloadHistoryTest_RemoveWhileAdding) { CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); history::DownloadRow info; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", &info); // Instruct CreateDownload() to not callback to DownloadHistory immediately, // but to wait for FinishCreateDownload(). set_slow_create_download(true); // Pretend the manager just created |item|. CallOnDownloadCreated(0); ExpectDownloadCreated(info); EXPECT_FALSE(DownloadHistory::IsPersisted(&item(0))); // Call OnDownloadRemoved before calling back to DownloadHistory::ItemAdded(). // Instead of calling RemoveDownloads() immediately, DownloadHistory should // add the item's id to removed_while_adding_. Then, ItemAdded should // immediately remove the item's record from history. item(0).NotifyObserversDownloadRemoved(); EXPECT_CALL(manager(), GetDownload(item(0).GetId())) .WillRepeatedly(Return(static_cast<content::DownloadItem*>(NULL))); ExpectNoDownloadsRemoved(); EXPECT_FALSE(DownloadHistory::IsPersisted(&item(0))); // Now callback to DownloadHistory::ItemAdded(), and expect a call to // RemoveDownloads() for the item that was removed while it was being added. FinishCreateDownload(); IdSet ids; ids.insert(info.id); ExpectDownloadsRemoved(ids); EXPECT_FALSE(DownloadHistory::IsPersisted(&item(0))); } // Test loading multiple items from the database and removing them all. TEST_F(DownloadHistoryTest, DownloadHistoryTest_Multiple) { // Load a download from history, create the item, OnDownloadCreated, // OnDownloadUpdated, OnDownloadRemoved. history::DownloadRow info0, info1; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", &info0); InitBasicItem(FILE_PATH_LITERAL("/foo/qux.pdf"), "http://example.com/qux.pdf", "http://example.com/referrer1.html", &info1); { std::unique_ptr<InfoVector> infos(new InfoVector()); infos->push_back(info0); infos->push_back(info1); CreateDownloadHistory(std::move(infos)); ExpectNoDownloadCreated(); } EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(1))); // Pretend that the user removed both items. IdSet ids; ids.insert(info0.id); ids.insert(info1.id); item(0).NotifyObserversDownloadRemoved(); item(1).NotifyObserversDownloadRemoved(); ExpectDownloadsRemoved(ids); } // Test what happens when HistoryService/CreateDownload::CreateDownload() fails. TEST_F(DownloadHistoryTest, DownloadHistoryTest_CreateFailed) { // Create a fresh item not from history, OnDownloadCreated, OnDownloadUpdated, // OnDownloadRemoved. CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); history::DownloadRow info; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", &info); FailCreateDownload(); // Pretend the manager just created |item|. CallOnDownloadCreated(0); ExpectDownloadCreated(info); EXPECT_FALSE(DownloadHistory::IsPersisted(&item(0))); EXPECT_CALL(item(0), GetReceivedBytes()).WillRepeatedly(Return(100)); item(0).NotifyObserversDownloadUpdated(); info.received_bytes = 100; ExpectDownloadCreated(info); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); } TEST_F(DownloadHistoryTest, DownloadHistoryTest_UpdateWhileAdding) { // Create a fresh item not from history, OnDownloadCreated, OnDownloadUpdated, // OnDownloadRemoved. CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); history::DownloadRow info; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", &info); // Instruct CreateDownload() to not callback to DownloadHistory immediately, // but to wait for FinishCreateDownload(). set_slow_create_download(true); // Pretend the manager just created |item|. CallOnDownloadCreated(0); ExpectDownloadCreated(info); EXPECT_FALSE(DownloadHistory::IsPersisted(&item(0))); // Pretend that something changed on the item. EXPECT_CALL(item(0), GetOpened()).WillRepeatedly(Return(true)); item(0).NotifyObserversDownloadUpdated(); FinishCreateDownload(); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); // ItemAdded should call OnDownloadUpdated, which should detect that the item // changed while it was being added and call UpdateDownload immediately. info.opened = true; ExpectDownloadUpdated(info); } } // anonymous namespace
[ "dummas@163.com" ]
dummas@163.com
fed7e41c3f76c2e8c47f50701487d0d9bbceb3d9
5b997d414b0fd924ebd5919bb1fbfe3b713e866a
/Tierra.cpp
6c83fe10be878062e3953295bc5799b7fb2f7929
[ "MIT" ]
permissive
Franklin-garcia/Lab5_p3_franklin__garcia
70e7aae9cc5f9f8100c984f089b07b2d5c5ec67d
07c0c82dd92cdb02ae6c2f1182ae7aa722e27234
refs/heads/master
2021-08-15T17:43:03.359771
2017-11-18T01:28:44
2017-11-18T01:28:44
111,140,205
0
0
null
null
null
null
UTF-8
C++
false
false
521
cpp
#include "Tierra.h" #include <string> Tierra::Tierra(){ this->coles; this->graduacion; } Tierra::Tierra(Poder *pPoder,string pColes,int pGraduacion,string pNacion,string pNombre,string pEdad,string pSexo):Persona(pNacion,pNombre, pEdad,pSexo){ coles=pColes; graduacion=pGraduacion; poder=pPoder; } int Tierra::getGraduacion(){ return graduacion; } string Tierra::getColes(){ return coles; } Poder* Tierra::getPoder(){ return poder; } Tierra::~Tierra(){ delete poder; }
[ "franklin__garcia@unitec.edu" ]
franklin__garcia@unitec.edu
717ce0ddf866f2e65d96b1e917da3f1a2db59729
36063ac9a8f9e2b8a8ff64a64fa1d2ce87d9bc3a
/dijkstra.cpp
c8f7552bd33b016ee48958a28dd5b0d6ac7e96e9
[]
no_license
siddian93/Algorithms
1f67c1c1c70a7f70ee4c26ca44973ca9cc2b1bbd
d792cb9490cbf28199cb60afe00f82a87e4036bd
refs/heads/master
2021-01-24T03:04:01.644338
2018-02-25T21:27:22
2018-02-25T21:27:22
122,876,656
0
0
null
2018-02-25T21:27:23
2018-02-25T21:03:15
C++
UTF-8
C++
false
false
1,736
cpp
#include<bits/stdc++.h> using namespace std; class Graph{ private: int N, E; vector<vector<pair<int, int> > > graph; vector<int> dist; vector<bool> visted; void create_graph(); void add_edges(int, int, int); public: Graph(){ N = 5; E = 7; graph.resize(N+1); dist.resize(N+1, 2e9); visted.resize(N+1); create_graph(); } void disjkstra(int); }; void Graph::add_edges(int a, int b, int cost){ graph[a].push_back(make_pair(cost, b)); graph[b].push_back(make_pair(cost, a)); } void Graph::create_graph(){ add_edges(1, 2, 1); add_edges(2, 3, 5); add_edges(1, 3, 7); add_edges(2, 4, 4); add_edges(2, 5, 3); add_edges(4, 5, 2); add_edges(3, 5, 6); } void Graph::disjkstra(int start){ priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > q; q.push(make_pair(0, start)); dist[start] = 0; while(!q.empty()){ cout<<q.top().second<<" "; int n = q.top().second; int c = q.top().first; q.pop(); if (visted[n]) continue; visted[n] = 1; for (int i = 0; i< graph[n].size(); ++i){ if (dist[graph[n][i].second] > dist[n] + graph[n][i].first){ dist[graph[n][i].second] = dist[n] + graph[n][i].first; q.push(make_pair(dist[graph[n][i].second], graph[n][i].second)); } } cout<<endl; for (int i =1 ; i< dist.size(); i++){ cout<<dist[i]<<" "; } } cout<<endl; for (int i =1 ; i< dist.size(); i++){ cout<<dist[i]<<" "; } } int main(){ Graph sp; sp.disjkstra(1); cout<<endl; return 0; }
[ "siddian.narayana@gmail.com" ]
siddian.narayana@gmail.com
1f1e08f614b1d695dd92863db4e8212ed1554499
f173dffa018b85db0410b051701968b45e0cc9b4
/Box Shooter/Temp/StagingArea/Data/il2cppOutput/AssemblyU2DCSharpU2Dfirstpass_UnityStandardAssets_I579860294.h
b36e7f694051b8e342ae171930149e9981f5d015
[]
no_license
Prakhar32/Box-Shooter
a348724ca0f5b3cbf5ec7dca6a4c0a90f3c8b262
da78280f31e014979b4550e822d93df31a6e5b3b
refs/heads/master
2021-05-02T10:57:56.099303
2018-02-08T14:23:28
2018-02-08T14:23:28
120,766,441
0
0
null
null
null
null
UTF-8
C++
false
false
4,995
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "AssemblyU2DCSharpU2Dfirstpass_UnityStandardAssets_2152133263.h" #include "AssemblyU2DCSharpU2Dfirstpass_UnityStandardAssets_2174076389.h" #include "AssemblyU2DCSharpU2Dfirstpass_UnityStandardAssets_2318278682.h" // UnityEngine.Shader struct Shader_t2430389951; // UnityEngine.Material struct Material_t193706927; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityStandardAssets.ImageEffects.BloomOptimized struct BloomOptimized_t579860294 : public PostEffectsBase_t2152133263 { public: // System.Single UnityStandardAssets.ImageEffects.BloomOptimized::threshold float ___threshold_5; // System.Single UnityStandardAssets.ImageEffects.BloomOptimized::intensity float ___intensity_6; // System.Single UnityStandardAssets.ImageEffects.BloomOptimized::blurSize float ___blurSize_7; // UnityStandardAssets.ImageEffects.BloomOptimized/Resolution UnityStandardAssets.ImageEffects.BloomOptimized::resolution int32_t ___resolution_8; // System.Int32 UnityStandardAssets.ImageEffects.BloomOptimized::blurIterations int32_t ___blurIterations_9; // UnityStandardAssets.ImageEffects.BloomOptimized/BlurType UnityStandardAssets.ImageEffects.BloomOptimized::blurType int32_t ___blurType_10; // UnityEngine.Shader UnityStandardAssets.ImageEffects.BloomOptimized::fastBloomShader Shader_t2430389951 * ___fastBloomShader_11; // UnityEngine.Material UnityStandardAssets.ImageEffects.BloomOptimized::fastBloomMaterial Material_t193706927 * ___fastBloomMaterial_12; public: inline static int32_t get_offset_of_threshold_5() { return static_cast<int32_t>(offsetof(BloomOptimized_t579860294, ___threshold_5)); } inline float get_threshold_5() const { return ___threshold_5; } inline float* get_address_of_threshold_5() { return &___threshold_5; } inline void set_threshold_5(float value) { ___threshold_5 = value; } inline static int32_t get_offset_of_intensity_6() { return static_cast<int32_t>(offsetof(BloomOptimized_t579860294, ___intensity_6)); } inline float get_intensity_6() const { return ___intensity_6; } inline float* get_address_of_intensity_6() { return &___intensity_6; } inline void set_intensity_6(float value) { ___intensity_6 = value; } inline static int32_t get_offset_of_blurSize_7() { return static_cast<int32_t>(offsetof(BloomOptimized_t579860294, ___blurSize_7)); } inline float get_blurSize_7() const { return ___blurSize_7; } inline float* get_address_of_blurSize_7() { return &___blurSize_7; } inline void set_blurSize_7(float value) { ___blurSize_7 = value; } inline static int32_t get_offset_of_resolution_8() { return static_cast<int32_t>(offsetof(BloomOptimized_t579860294, ___resolution_8)); } inline int32_t get_resolution_8() const { return ___resolution_8; } inline int32_t* get_address_of_resolution_8() { return &___resolution_8; } inline void set_resolution_8(int32_t value) { ___resolution_8 = value; } inline static int32_t get_offset_of_blurIterations_9() { return static_cast<int32_t>(offsetof(BloomOptimized_t579860294, ___blurIterations_9)); } inline int32_t get_blurIterations_9() const { return ___blurIterations_9; } inline int32_t* get_address_of_blurIterations_9() { return &___blurIterations_9; } inline void set_blurIterations_9(int32_t value) { ___blurIterations_9 = value; } inline static int32_t get_offset_of_blurType_10() { return static_cast<int32_t>(offsetof(BloomOptimized_t579860294, ___blurType_10)); } inline int32_t get_blurType_10() const { return ___blurType_10; } inline int32_t* get_address_of_blurType_10() { return &___blurType_10; } inline void set_blurType_10(int32_t value) { ___blurType_10 = value; } inline static int32_t get_offset_of_fastBloomShader_11() { return static_cast<int32_t>(offsetof(BloomOptimized_t579860294, ___fastBloomShader_11)); } inline Shader_t2430389951 * get_fastBloomShader_11() const { return ___fastBloomShader_11; } inline Shader_t2430389951 ** get_address_of_fastBloomShader_11() { return &___fastBloomShader_11; } inline void set_fastBloomShader_11(Shader_t2430389951 * value) { ___fastBloomShader_11 = value; Il2CppCodeGenWriteBarrier(&___fastBloomShader_11, value); } inline static int32_t get_offset_of_fastBloomMaterial_12() { return static_cast<int32_t>(offsetof(BloomOptimized_t579860294, ___fastBloomMaterial_12)); } inline Material_t193706927 * get_fastBloomMaterial_12() const { return ___fastBloomMaterial_12; } inline Material_t193706927 ** get_address_of_fastBloomMaterial_12() { return &___fastBloomMaterial_12; } inline void set_fastBloomMaterial_12(Material_t193706927 * value) { ___fastBloomMaterial_12 = value; Il2CppCodeGenWriteBarrier(&___fastBloomMaterial_12, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "prkhrsingh3@gmail.com" ]
prkhrsingh3@gmail.com
0946e5dad17d3866bce44c8d878bd93ad56686bb
3ff17558a5faf1e07c405156e945fc689b17ff83
/p2p_Client/commend_list.cpp
cb851a8b1ce079bbbea49573427faf0b3f2d2183
[]
no_license
ww406531195/16S003011_WangRui
bb408843a2ca28afd9f15217a502fc90669c7b44
8e0e0b08d1bfa4ba6ccaa9ccfe0643fdd5ce19dd
refs/heads/master
2021-01-21T14:34:00.622454
2017-06-24T15:23:11
2017-06-24T15:23:11
95,305,695
0
0
null
null
null
null
UTF-8
C++
false
false
1,980
cpp
// // Created by PC on 2017/6/16. // #include <cstring> #include <sstream> #include "file_hash.h" #include "commend_list.h" #include "sharedFileLibrary.h" bool commend_list::Form_add_c_msg(char*path,char * filename,int len_name,char * result) { if(!filename) return false; fstream f; sharedFileLibrary::Search_file(path,filename,f); if(!f.good()) return false; int file_len=f.rdbuf()->in_avail(); char hash_val[41]; file_hash::Get_file_hash(f,hash_val); memset(result,'\0',LEN_COMMEND_C); memcpy(result,"ADD ",4); memcpy(result+4,filename,len_name); memcpy(result+strlen(result)," ",1); memcpy(result+strlen(result),hash_val,strlen(hash_val)); memcpy(result+strlen(result)," ",1); stringstream s; s<<file_len; string file_len_s; s>>file_len_s; memcpy(result+strlen(result),file_len_s.c_str(), sizeof(int)); return true; } bool commend_list::Form_del_c_msg(char*path,char * filename,int len_name,char * result) { if(!filename) return false; fstream f; sharedFileLibrary::Search_file(path,filename,f); if(!f.good()) return false; char hash_val[41]; file_hash::Get_file_hash(f,hash_val); memset(result,'\0',LEN_COMMEND_C); memcpy(result,"DELETE ",7); memcpy(result+7,filename,len_name); memcpy(result+strlen(result)," ",1); memcpy(result+strlen(result),hash_val,strlen(hash_val)); return true; } bool commend_list::Form_req_c_msg(char * filename,int len_name,char * result) { if(!filename) return false; memset(result,'\0',LEN_COMMEND_C); memcpy(result,"REQUEST ",8); memcpy(result+8,filename,len_name); return true; } bool commend_list::Form_list_c_msg(char * result) { memset(result,'\0',LEN_COMMEND_C); memcpy(result,"LIST",4); return true; } bool commend_list::Form_quit_c_msg(char * result) { memset(result,'\0',LEN_COMMEND_C); memcpy(result,"QUIT",4); return true; }
[ "406531195@qq.com" ]
406531195@qq.com
4953c93d40e21b48f0b4945dbfe85899543a2800
873002d555745752657e3e25839f6653e73966a2
/model/CartShippingAddressRequest.h
d478fd262ea4c5e428ec28a468f5fcbfc48d9fc2
[]
no_license
knetikmedia/knetikcloud-cpprest-client
e7e739e382c02479b0a9aed8160d857414bd2fbf
14afb57d62de064fb8b7a68823043cc0150465d6
refs/heads/master
2021-01-23T06:35:44.076177
2018-03-14T16:02:35
2018-03-14T16:02:35
86,382,044
0
0
null
null
null
null
UTF-8
C++
false
false
5,083
h
/** * Knetik Platform API Documentation latest * This is the spec for the Knetik API. Use this in conjunction with the documentation found at https://knetikcloud.com. * * OpenAPI spec version: latest * Contact: support@knetik.com * * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ /* * CartShippingAddressRequest.h * * */ #ifndef CartShippingAddressRequest_H_ #define CartShippingAddressRequest_H_ #include "ModelBase.h" #include <cpprest/details/basic_types.h> namespace com { namespace knetikcloud { namespace client { namespace model { /// <summary> /// /// </summary> class CartShippingAddressRequest : public ModelBase { public: CartShippingAddressRequest(); virtual ~CartShippingAddressRequest(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; void fromJson(web::json::value& json) override; void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override; void fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override; ///////////////////////////////////////////// /// CartShippingAddressRequest members /// <summary> /// The city of the user /// </summary> utility::string_t getCity() const; bool cityIsSet() const; void unsetCity(); void setCity(utility::string_t value); /// <summary> /// The country code of the user /// </summary> utility::string_t getCountryCodeIso3() const; bool countryCodeIso3IsSet() const; void unsetCountry_code_iso3(); void setCountryCodeIso3(utility::string_t value); /// <summary> /// The email of the user /// </summary> utility::string_t getEmail() const; bool emailIsSet() const; void unsetEmail(); void setEmail(utility::string_t value); /// <summary> /// The first name of the user /// </summary> utility::string_t getFirstName() const; bool firstNameIsSet() const; void unsetFirst_name(); void setFirstName(utility::string_t value); /// <summary> /// The last name of the user /// </summary> utility::string_t getLastName() const; bool lastNameIsSet() const; void unsetLast_name(); void setLastName(utility::string_t value); /// <summary> /// /// </summary> utility::string_t getNamePrefix() const; bool namePrefixIsSet() const; void unsetName_prefix(); void setNamePrefix(utility::string_t value); /// <summary> /// The order notes the user /// </summary> utility::string_t getOrderNotes() const; bool orderNotesIsSet() const; void unsetOrder_notes(); void setOrderNotes(utility::string_t value); /// <summary> /// The phone number of the user /// </summary> utility::string_t getPhoneNumber() const; bool phoneNumberIsSet() const; void unsetPhone_number(); void setPhoneNumber(utility::string_t value); /// <summary> /// The postal state code of the user /// </summary> utility::string_t getPostalStateCode() const; bool postalStateCodeIsSet() const; void unsetPostal_state_code(); void setPostalStateCode(utility::string_t value); /// <summary> /// The shipping address of the user, first line /// </summary> utility::string_t getShippingAddressLine1() const; bool shippingAddressLine1IsSet() const; void unsetShipping_address_line1(); void setShippingAddressLine1(utility::string_t value); /// <summary> /// The shipping address of the user, second line /// </summary> utility::string_t getShippingAddressLine2() const; bool shippingAddressLine2IsSet() const; void unsetShipping_address_line2(); void setShippingAddressLine2(utility::string_t value); /// <summary> /// The zipcode of the user /// </summary> utility::string_t getZip() const; bool zipIsSet() const; void unsetZip(); void setZip(utility::string_t value); protected: utility::string_t m_City; bool m_CityIsSet; utility::string_t m_Country_code_iso3; bool m_Country_code_iso3IsSet; utility::string_t m_Email; bool m_EmailIsSet; utility::string_t m_First_name; bool m_First_nameIsSet; utility::string_t m_Last_name; bool m_Last_nameIsSet; utility::string_t m_Name_prefix; bool m_Name_prefixIsSet; utility::string_t m_Order_notes; bool m_Order_notesIsSet; utility::string_t m_Phone_number; bool m_Phone_numberIsSet; utility::string_t m_Postal_state_code; bool m_Postal_state_codeIsSet; utility::string_t m_Shipping_address_line1; bool m_Shipping_address_line1IsSet; utility::string_t m_Shipping_address_line2; bool m_Shipping_address_line2IsSet; utility::string_t m_Zip; bool m_ZipIsSet; }; } } } } #endif /* CartShippingAddressRequest_H_ */
[ "shawn.stout@knetik.com" ]
shawn.stout@knetik.com
c0d1524f62441fd3c8eed4f4efc4cfe0b2e524f4
cdd8641c8fd12bde3840e8946bc428e87c9248ef
/src/NYC_Subway_Router/MainProgram.h
23489474d7a376e10d1ec83984d372c73d1d66ec
[]
no_license
alecarreche/City_Folk
004a9e7cc1ec2b119f55ced816a33a9b59faba82
948c102b9ae8d41a52a1e68a1214d4610ce1a684
refs/heads/master
2023-01-30T16:41:00.423070
2020-12-06T23:49:54
2020-12-06T23:49:54
315,744,669
0
0
null
2020-12-04T22:32:48
2020-11-24T20:27:32
Jupyter Notebook
UTF-8
C++
false
false
781
h
#pragma once #include <QApplication> #include <QPushButton> #include <QLineEdit> #include <QMainWindow> #include <QInputDialog> #include <QCloseEvent> #include <QStyle> #include <QDesktopWidget> #include <QBoxLayout> #include <QLabel> #include <sys/time.h> #include <sys/resource.h> #include <chrono> #include "graph.h" using namespace std; class MainProgram : public QMainWindow { Q_OBJECT public: explicit MainProgram(QWidget *parent = nullptr); QPushButton *randlonglat, *inlonglat, *mapNY; Graph subway; string dspStations = ""; string aspStations = ""; bool testInput = false; bool testProgram = false; double totalTimeSecsDijkstras = 0; double totalTimeSecsAstar = 0; public slots: void inputLongLat(); void getLongLat(); };
[ "aehampton99@gmail.com" ]
aehampton99@gmail.com
d788afb5277634da5c3c13de5a040f3cb7ee3ef4
ad55ae060104e243dd4e36efda2f167a620d334d
/GameData/Player.h
d593617760160f7bcfdd6910649d56b35097b12c
[]
no_license
elmordo/VOB
382a3db451979f812409afecc59e9da29477eeec
1f1c262c7a5249cedafccf8673d1e52d20b17321
refs/heads/master
2021-01-01T05:40:22.149799
2014-10-28T14:13:54
2014-10-28T14:13:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,080
h
#pragma once #include <string> #include <Utils\Exception.h> #include "Room.h" using namespace std; using namespace VOB::Utils; namespace VOB { namespace GameData { VOB_CREATE_EXCEPTION_EXPORTABLE(PlayerException, Exception); VOB_CREATE_EXCEPTION_EXPORTABLE(TransitException, PlayerException); class DllExport Player { /* game name of player */ string name; /* where is player in game? */ Room *position; public: /* create empty instance */ Player(); /* create instance with name and start position */ Player(const string &name, Room *position = 0x0); virtual ~Player(); /* return current name of player */ const string &GetName() const; /* set new name to player */ void SetName(const string &name); /* return current position of player */ Room *GetPosition() const; /* set new position of player */ void SetPosition(Room *room); /* move player through door "from" is not current position, throw exception */ void Transit(Door *door); }; } }
[ "el.mordo@gmail.com" ]
el.mordo@gmail.com
8f5ac7dbe5f18a805097a50a2580f2f57c4f9f37
ee9c5d0ca8f5b0884827f808fd74289f5f8fc5f2
/problems/POI/AMPPZ/jas.cpp
5d858ad707bc711adee1980301a0279c0f538f1d
[]
no_license
caoash/competitive-programming
a1f69a03da5ea6eae463c6ae521a55bf32011752
f98d8d547d25811a26cf28316fbeb76477b6c63f
refs/heads/master
2022-05-26T12:51:37.952057
2021-10-10T22:01:03
2021-10-10T22:01:03
162,861,707
21
1
null
null
null
null
UTF-8
C++
false
false
1,682
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define F0R(i, x, y) for (int i = x; i < y; i++) #define FOR(i, n) F0R(i, 0, n) #define F0RD(i, x, y) for (int i = y - 1; i >= x; i--) #define FORD(i, n) F0RD(i, 0, n) #define F first #define S second const int MX = 3000005; int n; vector<int> adj[MX]; int sub[MX]; int count_sub[MX]; bool works[MX]; int groups = 0; vector<int> res; vector<int> ord; void bfs(int st) { queue<int> bfs; bfs.push(st); while (!bfs.empty()) { int v = bfs.front(); bfs.pop(); ord.push_back(v); for (int to : adj[v]) { bfs.push(to); } } reverse(ord.begin(), ord.end()); for (auto v : ord) { sub[v] = 1; for (int to : adj[v]) { sub[v] += sub[to]; } count_sub[sub[v]]++; } } void go(int len) { for (int l = 0; len * l <= n; ++l) { groups += count_sub[l * len]; } } bool Tri(int len) { groups = 0; go(len); if (groups == (n / len)) { return true; } return false; } int main() { #ifdef mikey freopen("a.in", "r", stdin); #endif ios::sync_with_stdio(false); cin.tie(0); cin >> n; FOR(i, n - 1) { int p; cin >> p; adj[p - 1].push_back(i + 1); } bfs(0); for (int i = 1; i * i <= n; i++) { if (n % i == 0) { if (Tri(i)) works[n / i] = true; if (i != (n / i)) { if (n % (n / i) == 0) { if (Tri(n / i)) works[i] = true; } } } } F0R(i, 1, n + 1) if (works[i]) cout << i << " "; cout << '\n'; }
[ "caoash@gmail.com" ]
caoash@gmail.com
12e5333a2dd30243f54566a7f49158452a75f708
58773e59b47166d70254cace4963d0b3a042191a
/module4/task4/tests.cpp
d2e2c43ceafacc1c0d6366d0610a3f964a7a9140
[]
no_license
JungleTryne/algo2
61cf2ee5bf25540096c9a9fef2ab91a1833d4927
2d46001da3a004d58b62f8bd0b0627eb568117e6
refs/heads/master
2023-01-20T18:38:45.378247
2020-11-20T13:03:38
2020-11-20T13:03:38
314,501,046
0
0
null
null
null
null
UTF-8
C++
false
false
540
cpp
#define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include "task4.h" TEST_CASE("Test 1") { std::vector<size_t> parents = {0, 0, 1}; LCA lca(parents); REQUIRE(lca.getLCA(1, 2) == 1); REQUIRE(lca.getLCA(0, 1) == 0); } TEST_CASE("Test 2") { std::vector<size_t> parents = {0, 0, 0}; LCA lca(parents); REQUIRE(lca.getLCA(1, 2) == 0); } TEST_CASE("Test 3") { std::vector<size_t> parents = {0, 0, 0, 1, 1, 2, 2}; LCA lca(parents); REQUIRE(lca.getLCA(3, 4) == 1); REQUIRE(lca.getLCA(5, 6) == 2); }
[ "danila.mishin.2001@gmail.com" ]
danila.mishin.2001@gmail.com
c870441fcebe7d9b8874026c93ff5ebd12e5a462
e9e2355abbc5942a87411941028d90937c3ad081
/linuxserverplatform/src/SDK/include/ServerCommon/sha1.h
d1d8c4651bd994b5b3860cfc1fa5a06c2d13e683
[]
no_license
kerwinzxc/libevent-game-server
9159d3f8227aaa9c51d985a15c6cb22d043082b7
4971ccef3397c9ab39e0423fa0e8ff376a2a1c0b
refs/heads/master
2022-09-04T04:11:34.046369
2020-06-01T07:43:45
2020-06-01T07:43:45
268,738,227
1
0
null
2020-06-02T08:00:58
2020-06-02T08:00:58
null
UTF-8
C++
false
false
2,494
h
/* * sha1.h * * Copyright (C) 1998, 2009 * Paul E. Jones <paulej@packetizer.com> * All Rights Reserved. * ***************************************************************************** * $Id: sha1.h 12 2009-06-22 19:34:25Z paulej $ ***************************************************************************** * * Description: * This class implements the Secure Hashing Standard as defined * in FIPS PUB 180-1 published April 17, 1995. * * Many of the variable names in this class, especially the single * character names, were used because those were the names used * in the publication. * * Please read the file sha1.cpp for more information. * */ #ifndef _SHA1_H_ #define _SHA1_H_ class SHA1 { public: SHA1(); virtual ~SHA1(); /* * Re-initialize the class */ void Reset(); /* * Returns the message digest */ bool Result(unsigned *message_digest_array); /* * Provide input to SHA1 */ void Input( const unsigned char *message_array, unsigned length); void Input( const char *message_array, unsigned length); void Input(unsigned char message_element); void Input(char message_element); SHA1& operator<<(const char *message_array); SHA1& operator<<(const unsigned char *message_array); SHA1& operator<<(const char message_element); SHA1& operator<<(const unsigned char message_element); private: /* * Process the next 512 bits of the message */ void ProcessMessageBlock(); /* * Pads the current message block to 512 bits */ void PadMessage(); /* * Performs a circular left shift operation */ unsigned CircularShift(int bits, unsigned word); unsigned H[5]; // Message digest buffers unsigned Length_Low; // Message length in bits unsigned Length_High; // Message length in bits unsigned char Message_Block[64]; // 512-bit message blocks int Message_Block_Index; // Index into message block array bool Computed; // Is the digest computed? bool Corrupted; // Is the message digest corruped? }; #endif // _SHA1_H_
[ "935451190@qq.com" ]
935451190@qq.com
c2b90d2ef3c5177f610cbe6eccdba404acfe4c9d
01aabb4a7a36d397b2f4a58255840749227043f1
/Beginner127/c.cpp
cd79a5bff8484f8a846ca197ff9723a81e5aafe2
[]
no_license
higher68/atcoder
1c8e562a21d043827912d27b032b55b71399e6b6
a089b4a096fde6ca0be28b220af55c48210e7966
refs/heads/master
2021-06-17T04:02:22.189387
2019-09-22T07:36:27
2019-09-22T07:36:27
137,625,434
0
0
null
null
null
null
UTF-8
C++
false
false
518
cpp
#include <bits/stdc++.h> using namespace std; int main() { int N, M; cin >> N >> M; int l_max, r_min; cin >> l_max >> r_min; for (int i = 1; i < M; i++) { int l, r; cin >> l >> r; if (l > l_max) { l_max = l; } if (r < r_min) { r_min = r; } } int ans; if (r_min >= l_max) { ans = r_min - l_max + 1; } else { ans = 0; } cout << ans << endl; return 0; }
[ "hatiro7code@gmail.com" ]
hatiro7code@gmail.com
28369c5494b9804027055b74317f3c15f8fba142
6a69d57c782e0b1b993e876ad4ca2927a5f2e863
/vendor/samsung/common/packages/apps/SBrowser/src/ash/metrics/user_metrics_recorder.cc
4d49e9273a5c32edf2df9e016a1713864796c861
[ "BSD-3-Clause" ]
permissive
duki994/G900H-Platform-XXU1BOA7
c8411ef51f5f01defa96b3381f15ea741aa5bce2
4f9307e6ef21893c9a791c96a500dfad36e3b202
refs/heads/master
2020-05-16T20:57:07.585212
2015-05-11T11:03:16
2015-05-11T11:03:16
35,418,464
2
1
null
null
null
null
UTF-8
C++
false
false
17,317
cc
// Copyright 2013 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 "ash/metrics/user_metrics_recorder.h" #include "ash/shelf/shelf_layout_manager.h" #include "ash/shelf/shelf_view.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" #include "ash/wm/window_state.h" #include "base/metrics/histogram.h" #include "base/metrics/user_metrics.h" namespace ash { // Time in seconds between calls to "RecordPeriodicMetrics". const int kAshPeriodicMetricsTimeInSeconds = 30 * 60; UserMetricsRecorder::UserMetricsRecorder() { timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kAshPeriodicMetricsTimeInSeconds), this, &UserMetricsRecorder::RecordPeriodicMetrics); } UserMetricsRecorder::~UserMetricsRecorder() { timer_.Stop(); } void UserMetricsRecorder::RecordUserMetricsAction(UserMetricsAction action) { switch (action) { case ash::UMA_ACCEL_KEYBOARD_BRIGHTNESS_DOWN_F6: base::RecordAction( base::UserMetricsAction("Accel_KeyboardBrightnessDown_F6")); break; case ash::UMA_ACCEL_KEYBOARD_BRIGHTNESS_UP_F7: base::RecordAction( base::UserMetricsAction("Accel_KeyboardBrightnessUp_F7")); break; case ash::UMA_ACCEL_LOCK_SCREEN_LOCK_BUTTON: base::RecordAction( base::UserMetricsAction("Accel_LockScreen_LockButton")); break; case ash::UMA_ACCEL_LOCK_SCREEN_POWER_BUTTON: base::RecordAction( base::UserMetricsAction("Accel_LockScreen_PowerButton")); break; case ash::UMA_ACCEL_MAXIMIZE_RESTORE_F4: base::RecordAction( base::UserMetricsAction("Accel_Maximize_Restore_F4")); break; case ash::UMA_ACCEL_PREVWINDOW_F5: base::RecordAction(base::UserMetricsAction("Accel_PrevWindow_F5")); break; case ash::UMA_ACCEL_EXIT_FIRST_Q: base::RecordAction(base::UserMetricsAction("Accel_Exit_First_Q")); break; case ash::UMA_ACCEL_EXIT_SECOND_Q: base::RecordAction(base::UserMetricsAction("Accel_Exit_Second_Q")); break; case ash::UMA_ACCEL_SHUT_DOWN_POWER_BUTTON: base::RecordAction( base::UserMetricsAction("Accel_ShutDown_PowerButton")); break; case ash::UMA_CLOSE_THROUGH_CONTEXT_MENU: base::RecordAction(base::UserMetricsAction("CloseFromContextMenu")); break; case ash::UMA_DRAG_MAXIMIZE_LEFT: base::RecordAction(base::UserMetricsAction("WindowDrag_MaximizeLeft")); break; case ash::UMA_DRAG_MAXIMIZE_RIGHT: base::RecordAction(base::UserMetricsAction("WindowDrag_MaximizeRight")); break; case ash::UMA_GESTURE_OVERVIEW: base::RecordAction(base::UserMetricsAction("Gesture_Overview")); break; case ash::UMA_LAUNCHER_CLICK_ON_APP: base::RecordAction(base::UserMetricsAction("Launcher_ClickOnApp")); break; case ash::UMA_LAUNCHER_CLICK_ON_APPLIST_BUTTON: base::RecordAction( base::UserMetricsAction("Launcher_ClickOnApplistButton")); break; case ash::UMA_MOUSE_DOWN: base::RecordAction(base::UserMetricsAction("Mouse_Down")); break; case ash::UMA_PANEL_MINIMIZE_CAPTION_CLICK: base::RecordAction( base::UserMetricsAction("Panel_Minimize_Caption_Click")); break; case ash::UMA_PANEL_MINIMIZE_CAPTION_GESTURE: base::RecordAction( base::UserMetricsAction("Panel_Minimize_Caption_Gesture")); break; case ash::UMA_SHELF_ALIGNMENT_SET_BOTTOM: base::RecordAction( base::UserMetricsAction("Shelf_AlignmentSetBottom")); break; case ash::UMA_SHELF_ALIGNMENT_SET_LEFT: base::RecordAction( base::UserMetricsAction("Shelf_AlignmentSetLeft")); break; case ash::UMA_SHELF_ALIGNMENT_SET_RIGHT: base::RecordAction( base::UserMetricsAction("Shelf_AlignmentSetRight")); case ash::UMA_STATUS_AREA_AUDIO_CURRENT_INPUT_DEVICE: base::RecordAction( base::UserMetricsAction("StatusArea_Audio_CurrentInputDevice")); break; case ash::UMA_STATUS_AREA_AUDIO_CURRENT_OUTPUT_DEVICE: base::RecordAction( base::UserMetricsAction("StatusArea_Audio_CurrentOutputDevice")); break; case ash::UMA_STATUS_AREA_AUDIO_SWITCH_INPUT_DEVICE: base::RecordAction( base::UserMetricsAction("StatusArea_Audio_SwitchInputDevice")); break; case ash::UMA_STATUS_AREA_AUDIO_SWITCH_OUTPUT_DEVICE: base::RecordAction( base::UserMetricsAction("StatusArea_Audio_SwitchOutputDevice")); break; case ash::UMA_STATUS_AREA_BRIGHTNESS_CHANGED: base::RecordAction( base::UserMetricsAction("StatusArea_BrightnessChanged")); break; case ash::UMA_STATUS_AREA_BLUETOOTH_CONNECT_KNOWN_DEVICE: base::RecordAction( base::UserMetricsAction("StatusArea_Bluetooth_Connect_Known")); break; case ash::UMA_STATUS_AREA_BLUETOOTH_CONNECT_UNKNOWN_DEVICE: base::RecordAction( base::UserMetricsAction("StatusArea_Bluetooth_Connect_Unknown")); break; case ash::UMA_STATUS_AREA_BLUETOOTH_DISABLED: base::RecordAction( base::UserMetricsAction("StatusArea_Bluetooth_Disabled")); break; case ash::UMA_STATUS_AREA_BLUETOOTH_ENABLED: base::RecordAction( base::UserMetricsAction("StatusArea_Bluetooth_Enabled")); break; case ash::UMA_STATUS_AREA_CAPS_LOCK_DETAILED: base::RecordAction( base::UserMetricsAction("StatusArea_CapsLock_Detailed")); break; case ash::UMA_STATUS_AREA_CAPS_LOCK_DISABLED_BY_CLICK: base::RecordAction( base::UserMetricsAction("StatusArea_CapsLock_DisabledByClick")); break; case ash::UMA_STATUS_AREA_CAPS_LOCK_ENABLED_BY_CLICK: base::RecordAction( base::UserMetricsAction("StatusArea_CapsLock_EnabledByClick")); break; case ash::UMA_STATUS_AREA_CAPS_LOCK_POPUP: base::RecordAction( base::UserMetricsAction("StatusArea_CapsLock_Popup")); break; case ash::UMA_STATUS_AREA_CONNECT_TO_CONFIGURED_NETWORK: base::RecordAction( base::UserMetricsAction("StatusArea_Network_ConnectConfigured")); break; case ash::UMA_STATUS_AREA_CONNECT_TO_UNCONFIGURED_NETWORK: base::RecordAction( base::UserMetricsAction("StatusArea_Network_ConnectUnconfigured")); break; case ash::UMA_STATUS_AREA_CONNECT_TO_VPN: base::RecordAction( base::UserMetricsAction("StatusArea_VPN_ConnectToNetwork")); break; case ash::UMA_STATUS_AREA_CHANGED_VOLUME_MENU: base::RecordAction( base::UserMetricsAction("StatusArea_Volume_ChangedMenu")); break; case ash::UMA_STATUS_AREA_CHANGED_VOLUME_POPUP: base::RecordAction( base::UserMetricsAction("StatusArea_Volume_ChangedPopup")); break; case ash::UMA_STATUS_AREA_DETAILED_ACCESSABILITY: base::RecordAction( base::UserMetricsAction("StatusArea_Accessability_DetailedView")); break; case ash::UMA_STATUS_AREA_DETAILED_AUDIO_VIEW: base::RecordAction( base::UserMetricsAction("StatusArea_Audio_Detailed")); break; case ash::UMA_STATUS_AREA_DETAILED_BLUETOOTH_VIEW: base::RecordAction( base::UserMetricsAction("StatusArea_Bluetooth_Detailed")); break; case ash::UMA_STATUS_AREA_DETAILED_BRIGHTNESS_VIEW: base::RecordAction( base::UserMetricsAction("StatusArea_Brightness_Detailed")); break; case ash::UMA_STATUS_AREA_DETAILED_DRIVE_VIEW: base::RecordAction( base::UserMetricsAction("StatusArea_Drive_Detailed")); break; case ash::UMA_STATUS_AREA_DETAILED_NETWORK_VIEW: base::RecordAction( base::UserMetricsAction("StatusArea_Network_Detailed")); break; case ash::UMA_STATUS_AREA_DETAILED_VPN_VIEW: base::RecordAction( base::UserMetricsAction("StatusArea_VPN_Detailed")); break; case ash::UMA_STATUS_AREA_DISABLE_AUTO_CLICK: base::RecordAction( base::UserMetricsAction("StatusArea_AutoClickDisabled")); break; case ash::UMA_STATUS_AREA_DISABLE_HIGH_CONTRAST: base::RecordAction( base::UserMetricsAction("StatusArea_HighContrastDisabled")); break; case ash::UMA_STATUS_AREA_DISABLE_LARGE_CURSOR: base::RecordAction( base::UserMetricsAction("StatusArea_LargeCursorDisabled")); break; case ash::UMA_STATUS_AREA_DISABLE_MAGNIFIER: base::RecordAction( base::UserMetricsAction("StatusArea_MagnifierDisabled")); break; case ash::UMA_STATUS_AREA_DISABLE_SPOKEN_FEEDBACK: base::RecordAction( base::UserMetricsAction("StatusArea_SpokenFeedbackDisabled")); break; case ash::UMA_STATUS_AREA_DISABLE_VIRTUAL_KEYBOARD: base::RecordAction( base::UserMetricsAction("StatusArea_VirtualKeyboardDisabled")); break; case ash::UMA_STATUS_AREA_DISABLE_WIFI: base::RecordAction( base::UserMetricsAction("StatusArea_Network_WifiDisabled")); break; case ash::UMA_STATUS_AREA_DRIVE_CANCEL_OPERATION: base::RecordAction( base::UserMetricsAction("StatusArea_Drive_CancelOperation")); break; case ash::UMA_STATUS_AREA_DRIVE_SETTINGS: base::RecordAction( base::UserMetricsAction("StatusArea_Drive_Settings")); break; case ash::UMA_STATUS_AREA_ENABLE_AUTO_CLICK: base::RecordAction( base::UserMetricsAction("StatusArea_AutoClickEnabled")); break; case ash::UMA_STATUS_AREA_ENABLE_HIGH_CONTRAST: base::RecordAction( base::UserMetricsAction("StatusArea_HighContrastEnabled")); break; case ash::UMA_STATUS_AREA_ENABLE_LARGE_CURSOR: base::RecordAction( base::UserMetricsAction("StatusArea_LargeCursorEnabled")); break; case ash::UMA_STATUS_AREA_ENABLE_MAGNIFIER: base::RecordAction( base::UserMetricsAction("StatusArea_MagnifierEnabled")); break; case ash::UMA_STATUS_AREA_ENABLE_SPOKEN_FEEDBACK: base::RecordAction( base::UserMetricsAction("StatusArea_SpokenFeedbackEnabled")); break; case ash::UMA_STATUS_AREA_ENABLE_VIRTUAL_KEYBOARD: base::RecordAction( base::UserMetricsAction("StatusArea_VirtualKeyboardEnabled")); break; case ash::UMA_STATUS_AREA_ENABLE_WIFI: base::RecordAction( base::UserMetricsAction("StatusArea_Network_WifiEnabled")); break; case ash::UMA_STATUS_AREA_IME_SHOW_DETAILED: base::RecordAction( base::UserMetricsAction("StatusArea_IME_Detailed")); break; case ash::UMA_STATUS_AREA_IME_SWITCH_MODE: base::RecordAction( base::UserMetricsAction("StatusArea_IME_SwitchMode")); break; case ash::UMA_STATUS_AREA_MENU_OPENED: base::RecordAction( base::UserMetricsAction("StatusArea_MenuOpened")); break; case ash::UMA_STATUS_AREA_NETWORK_JOIN_OTHER_CLICKED: base::RecordAction( base::UserMetricsAction("StatusArea_Network_JoinOther")); break; case ash::UMA_STATUS_AREA_NETWORK_SETTINGS_CLICKED: base::RecordAction( base::UserMetricsAction("StatusArea_Network_Settings")); break; case ash::UMA_STATUS_AREA_SHOW_NETWORK_CONNECTION_DETAILS: base::RecordAction( base::UserMetricsAction("StatusArea_Network_ConnectionDetails")); break; case ash::UMA_STATUS_AREA_SHOW_VPN_CONNECTION_DETAILS: base::RecordAction( base::UserMetricsAction("StatusArea_VPN_ConnectionDetails")); break; case ash::UMA_STATUS_AREA_SIGN_OUT: base::RecordAction( base::UserMetricsAction("StatusArea_SignOut")); break; case ash::UMA_STATUS_AREA_VPN_JOIN_OTHER_CLICKED: base::RecordAction( base::UserMetricsAction("StatusArea_VPN_JoinOther")); break; case ash::UMA_STATUS_AREA_VPN_SETTINGS_CLICKED: base::RecordAction( base::UserMetricsAction("StatusArea_VPN_Settings")); break; case ash::UMA_TOGGLE_MAXIMIZE_CAPTION_CLICK: base::RecordAction( base::UserMetricsAction("Caption_ClickTogglesMaximize")); break; case ash::UMA_TOGGLE_MAXIMIZE_CAPTION_GESTURE: base::RecordAction( base::UserMetricsAction("Caption_GestureTogglesMaximize")); break; case ash::UMA_TOGGLE_SINGLE_AXIS_MAXIMIZE_BORDER_CLICK: base::RecordAction( base::UserMetricsAction( "WindowBorder_ClickTogglesSingleAxisMaximize")); break; case ash::UMA_TOUCHPAD_GESTURE_OVERVIEW: base::RecordAction( base::UserMetricsAction("Touchpad_Gesture_Overview")); break; case ash::UMA_TOUCHSCREEN_TAP_DOWN: base::RecordAction(base::UserMetricsAction("Touchscreen_Down")); break; case ash::UMA_TRAY_HELP: base::RecordAction(base::UserMetricsAction("Tray_Help")); break; case ash::UMA_TRAY_LOCK_SCREEN: base::RecordAction(base::UserMetricsAction("Tray_LockScreen")); break; case ash::UMA_TRAY_SHUT_DOWN: base::RecordAction(base::UserMetricsAction("Tray_ShutDown")); break; case ash::UMA_WINDOW_APP_CLOSE_BUTTON_CLICK: base::RecordAction(base::UserMetricsAction("AppCloseButton_Clk")); break; case ash::UMA_WINDOW_CLOSE_BUTTON_CLICK: base::RecordAction(base::UserMetricsAction("CloseButton_Clk")); break; case ash::UMA_WINDOW_MAXIMIZE_BUTTON_CLICK_EXIT_FULLSCREEN: base::RecordAction(base::UserMetricsAction("MaxButton_Clk_ExitFS")); break; case ash::UMA_WINDOW_MAXIMIZE_BUTTON_CLICK_RESTORE: base::RecordAction( base::UserMetricsAction("MaxButton_Clk_Restore")); break; case ash::UMA_WINDOW_MAXIMIZE_BUTTON_CLICK_MAXIMIZE: base::RecordAction( base::UserMetricsAction("MaxButton_Clk_Maximize")); break; case ash::UMA_WINDOW_MAXIMIZE_BUTTON_CLICK_MINIMIZE: base::RecordAction(base::UserMetricsAction("MinButton_Clk")); break; case ash::UMA_WINDOW_MAXIMIZE_BUTTON_MAXIMIZE: base::RecordAction(base::UserMetricsAction("MaxButton_Maximize")); break; case ash::UMA_WINDOW_MAXIMIZE_BUTTON_MAXIMIZE_LEFT: base::RecordAction(base::UserMetricsAction("MaxButton_MaxLeft")); break; case ash::UMA_WINDOW_MAXIMIZE_BUTTON_MAXIMIZE_RIGHT: base::RecordAction(base::UserMetricsAction("MaxButton_MaxRight")); break; case ash::UMA_WINDOW_MAXIMIZE_BUTTON_MINIMIZE: base::RecordAction(base::UserMetricsAction("MaxButton_Minimize")); break; case ash::UMA_WINDOW_MAXIMIZE_BUTTON_RESTORE: base::RecordAction(base::UserMetricsAction("MaxButton_Restore")); break; case ash::UMA_WINDOW_MAXIMIZE_BUTTON_SHOW_BUBBLE: base::RecordAction(base::UserMetricsAction("MaxButton_ShowBubble")); break; case ash::UMA_WINDOW_OVERVIEW: base::RecordAction( base::UserMetricsAction("WindowSelector_Overview")); break; case ash::UMA_WINDOW_SELECTION: base::RecordAction( base::UserMetricsAction("WindowSelector_Selection")); break; } } void UserMetricsRecorder::RecordPeriodicMetrics() { internal::ShelfLayoutManager* manager = internal::ShelfLayoutManager::ForShelf(Shell::GetPrimaryRootWindow()); if (manager) { UMA_HISTOGRAM_ENUMERATION("Ash.ShelfAlignmentOverTime", manager->SelectValueForShelfAlignment( internal::SHELF_ALIGNMENT_UMA_ENUM_VALUE_BOTTOM, internal::SHELF_ALIGNMENT_UMA_ENUM_VALUE_LEFT, internal::SHELF_ALIGNMENT_UMA_ENUM_VALUE_RIGHT, -1), internal::SHELF_ALIGNMENT_UMA_ENUM_VALUE_COUNT); } enum ActiveWindowShowType { ACTIVE_WINDOW_SHOW_TYPE_NO_ACTIVE_WINDOW, ACTIVE_WINDOW_SHOW_TYPE_OTHER, ACTIVE_WINDOW_SHOW_TYPE_MAXIMIZED, ACTIVE_WINDOW_SHOW_TYPE_FULLSCREEN, ACTIVE_WINDOW_SHOW_TYPE_SNAPPED, ACTIVE_WINDOW_SHOW_TYPE_COUNT }; ActiveWindowShowType active_window_show_type = ACTIVE_WINDOW_SHOW_TYPE_NO_ACTIVE_WINDOW; wm::WindowState* active_window_state = ash::wm::GetActiveWindowState(); if (active_window_state) { switch(active_window_state->window_show_type()) { case wm::SHOW_TYPE_MAXIMIZED: active_window_show_type = ACTIVE_WINDOW_SHOW_TYPE_MAXIMIZED; break; case wm::SHOW_TYPE_FULLSCREEN: active_window_show_type = ACTIVE_WINDOW_SHOW_TYPE_FULLSCREEN; break; case wm::SHOW_TYPE_LEFT_SNAPPED: case wm::SHOW_TYPE_RIGHT_SNAPPED: active_window_show_type = ACTIVE_WINDOW_SHOW_TYPE_SNAPPED; break; case wm::SHOW_TYPE_DEFAULT: case wm::SHOW_TYPE_NORMAL: case wm::SHOW_TYPE_MINIMIZED: case wm::SHOW_TYPE_INACTIVE: case wm::SHOW_TYPE_DETACHED: case wm::SHOW_TYPE_END: case wm::SHOW_TYPE_AUTO_POSITIONED: active_window_show_type = ACTIVE_WINDOW_SHOW_TYPE_OTHER; break; } } UMA_HISTOGRAM_ENUMERATION("Ash.ActiveWindowShowTypeOverTime", active_window_show_type, ACTIVE_WINDOW_SHOW_TYPE_COUNT); } } // namespace ash
[ "duki994@gmail.com" ]
duki994@gmail.com
61b50361d0f4a8aefeb4a0050da424157e931df7
118022796f4cf787baf3e862436154b48ae34daf
/npr.cpp
e11a9792db98151035138d93040d4fb97d6d4965
[]
no_license
RABARISONHeriniaina/Qt
1a7c3d5b04d7d249076ec3ced3bde6909f2c679a
99ddf38b55d46b58dae2487c218d9fbb42d6aca1
refs/heads/master
2022-12-10T22:32:39.601351
2020-09-11T10:18:28
2020-09-11T10:18:28
294,661,879
0
0
null
null
null
null
UTF-8
C++
false
false
4,267
cpp
#include "npr.h" #include "ui_npr.h" #include <QMediaPlayer> #include <QVideoWidget> #include <QDebug> #include <QUrl> #include <QFileDialog> #include <QMessageBox> npr::npr(QWidget *parent) : QMainWindow(parent) , ui(new Ui::npr) { ui->setupUi(this); player = new QMediaPlayer; QVideoWidget *vw = new QVideoWidget(this); player->setVideoOutput(vw); //for the video this->setCentralWidget(vw); vw->setStyleSheet("background-color:black"); qDebug()<< (player->state()); connect(ui->horizontalSlider,&QSlider::sliderMoved,player,&QMediaPlayer::setPosition); connect(player,&QMediaPlayer::positionChanged,ui->horizontalSlider,&QSlider::setValue); connect(player,&QMediaPlayer::durationChanged,ui->horizontalSlider,&QSlider::setMaximum); ui->statusbar->addPermanentWidget(ui->label); ui->statusbar->addPermanentWidget(ui->horizontalSlider,1); ui->statusbar->addPermanentWidget(ui->label_2); ui->label_3->setText(QString::number(100) + "% Volume"); maxTemps = 0; ui->toolBar->addWidget(ui->label_3); //pour le volume volume = 100; this->setWindowFlag(Qt::WindowStaysOnTopHint); ui->verticalSlider->setValue(player->volume()); connect(ui->verticalSlider,&QSlider::valueChanged,player,&QMediaPlayer::setVolume); } npr::~npr() { delete ui; } QString npr::calculeSeconde(int sec) { QString text,minutee,secondee; int minute = sec / 60; int seconde = sec % 60; if(minute >= 0 && minute < 10) { minutee = "0" + QString::number(minute); } else { minutee = QString::number(minute); } if(seconde >= 0 && seconde < 10) { secondee = "0" + QString::number(seconde); } else { secondee = QString::number(seconde); } text = minutee +":"+ secondee; return text; } void npr::on_actionOuvrir_triggered() { QString fileName = QFileDialog::getOpenFileName(this,"Choisissez votre chanson","C:/","Tout les fichiers (*.*) ;;Tout les mp4 (*.mp4) ;;Tout les mkv (*.mkv)"); player->setMedia(QUrl(fileName)); player->play(); volume = player->volume(); QStringList lt = fileName.split("/"); this->setWindowTitle(lt[lt.length()-1]); ui->label->setText(QString::number(player->position())); qDebug()<< (player->state()); maxTemps = ui->horizontalSlider->maximum(); ui->label_2->setText(QString::number(maxTemps)); } void npr::on_actionStop_triggered() { player->stop(); } void npr::on_actionPlay_triggered() { player->play(); } void npr::on_actionPrev_triggered() { player->setPosition(ui->horizontalSlider->value() - 10000); } void npr::on_actionPause_triggered() { player->pause(); } void npr::on_actionNext_triggered() { player->setPosition(ui->horizontalSlider->value() + 10000); } void npr::on_actionMute_triggered() { volume = 0; player->setVolume(volume); ui->label_3->setText(QString::number(volume) + "% Volume"); } void npr::on_actionAugmenter_triggered() { volume+=10; player->setVolume(volume); ui->label_3->setText(QString::number(volume) + "% Volume"); } void npr::on_actionDiminuer_triggered() { volume-=10; player->setVolume(volume); ui->label_3->setText(QString::number(volume) + "% Volume"); } void npr::on_actionNormal_triggered() { volume = 50; player->setVolume(volume); ui->label_3->setText(QString::number(volume) + "% Volume"); } void npr::on_horizontalSlider_valueChanged(int value) { ui->label->setText(calculeSeconde(value/1000)); } void npr::on_horizontalSlider_rangeChanged(int min, int max) { min++; ui->label_2->setText(calculeSeconde(max/1000)); } void npr::on_actionNPR_triggered() { player->pause(); QMessageBox::about(this,"NPR","NPR<br/>Niah PlayeR(2020)"); player->play(); } void npr::on_actionRABARISON_Heriniaina_triggered() { player->pause(); QMessageBox::about(this,"RABARISON Heriniaina","Nom : RABARISON<br/>Prenom : Heriniaina<br/>Age : -- ans<br/>Developpeur<br/>Sns......"); player->play(); }
[ "noreply@github.com" ]
noreply@github.com
03e2c2579f52cdc695a0df38725654cd07a6c074
e9f8c0d925fec4db3764321b19d2e2b5f5625be5
/Project_1/App/InputHandler.cpp
7f12e7fb265286f6cd654ce90951552dfa8285f6
[]
no_license
iliask796/SysPro
208808ad6fb20d79c699beeca50bd0b31e50edd4
4aa4670266c3a56446b8f6d12bf92185b9e9315e
refs/heads/main
2023-09-01T00:21:15.291032
2021-06-26T05:54:16
2021-06-26T05:54:16
349,146,511
0
0
null
null
null
null
UTF-8
C++
false
false
2,748
cpp
#include "InputHandler.h" CommandInput::CommandInput(int size1) { size = size1; wordArray = new string[size]; } void CommandInput::insertCommand(const string& command) { int counter = 0; int start = 0; int end = command.find(' '); while (end != -1){ wordArray[counter++] = command.substr(start,end-start); start = end + 1; end = command.find(' ',start); if (counter == size-1){ break; } } wordArray[counter] = command.substr(start,end-start); } string CommandInput::getWord(int pos) { if (pos>=0 and pos<=size-1){ return wordArray[pos]; } return ""; } bool CommandInput::isDigit(int pos) { for(char i : wordArray[pos]){ if (isdigit(i) == false){ return false; } } return true; } bool CommandInput::isDate(int pos) { int i; string date = wordArray[pos]; if (date.length() < 8 or date.length() > 10){ return false; } if (isdigit(date[0]) == false){ return false; } for (i=1;i<4;i++){ if (isdigit(date[date.length()-i]) == false){ return false; } } if (date[date.length()-(++i)] != '-' or (date[2] != '-' and date[3]!= '-')){ return false; } return true; } void CommandInput::clear() { for (int i=0;i<size;i++){ wordArray[i] = ""; } } int CommandInput::getCount() { int i=0; while (i<size){ if (wordArray[i].empty()){ break; } i++; } return i; } CommandInput::~CommandInput() { delete[] wordArray; } int compareDates(const string& date1,const string& date2) { string dateInfo1[3]; string dateInfo2[3]; int i,start = 0,end = date1.find('-'); for (i=0;i<2;i++){ dateInfo1[i]= date1.substr(start,end-start); start = end + 1; end = date1.find('-',start); } dateInfo1[i]= date1.substr(start,end-start); start = 0; end = date2.find('-'); for (i=0;i<2;i++){ dateInfo2[i]= date2.substr(start,end-start); start = end + 1; end = date2.find('-',start); } dateInfo2[i]= date2.substr(start,end-start); if (dateInfo1[2]>dateInfo2[2]){ return -1; } else if (dateInfo1[2]<dateInfo2[2]){ return 1; } else{ if (dateInfo1[1]>dateInfo2[1]){ return -1; } else if (dateInfo1[1]<dateInfo2[1]){ return 1; } else{ if (dateInfo1[0]>dateInfo2[0]){ return -1; } else if (dateInfo1[0]<dateInfo2[0]){ return 1; } else{ return 0; } } } }
[ "iliaskal7@gmail.com" ]
iliaskal7@gmail.com
9a843e5d02a467f04564aee06652bb79631de3fb
42d22c73e23d6d5950cad4dc4e47f05500e81b70
/Square/ABC.cpp
c2bc565db871cee06cb5d82847e0a10ff2d4b7a0
[]
no_license
anny-nov/study_projects-c-plus-plus-
f01548528cc03ee586459be6249e2faf15aebb83
8096e2318d205725918aa34568321ac386c8c320
refs/heads/main
2023-07-16T04:42:37.099115
2021-08-30T16:25:11
2021-08-30T16:25:11
389,385,817
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
787
cpp
#include<iostream> #include<cmath> using namespace std; double square(double a) { double p = a * 3 / 2; double s = sqrt(p * (p - a) * (p - a) * (p - a)); return s; } double square(double a, double b, double c) { double p = (a+b+c)/ 2; double s = sqrt(p * (p - a) * (p - b) * (p - c)); return s; } int main() //Вычисление площади треугольника { double p, a, s, s2, b, c; cout << "Put the perimetr of the triangle: " << endl; cin >> a >> b >> c; if (a == b == c) { s2 = square(a); cout << "\nSide:\t Square: \t\n" << endl; cout << a << "\t" << s << "\t" << endl; } else { s = square (a,b,c) ; cout << "\nSide:\t Square: \t\n" << endl; cout << a << "\t" << s << "\t" << endl; } system("pause"); }
[ "noreply@github.com" ]
noreply@github.com
284ecc59488026d2f7932005fe751f9b5b8aa968
504855c4dd6cd7d771e567944ed95e87e655d727
/entity.h
a33f427457c40d70fd99ea3a7914273d9a8018d0
[]
no_license
HeyaShokubutsu/Maksimychev_Artyom
9117be0811643e300bdfa0320a2ca3dba44bb7da
3cf8a9d6a8472341e7597a023279e95ea2b13a36
refs/heads/master
2020-12-11T10:20:15.947199
2020-01-14T10:54:05
2020-01-14T10:54:05
233,820,700
0
0
null
null
null
null
UTF-8
C++
false
false
339
h
#ifndef ENTITY_H #define ENTITY_H #include "graphicsobject.h" class Entity : public GraphicsObject { int rotation; int nextRotation; double speed; int animationStep; public: Entity( double _x, double _y, int t, HANDLE h ); void moveForvard(); void rotate( int side ); void paint(); }; #endif // ENTITY_H
[ "37301928+HeyaShokubutsu@users.noreply.github.com" ]
37301928+HeyaShokubutsu@users.noreply.github.com
6f7115d09ac430d12c7c04d02eba8ecb5ba3f299
2ef3248ca1bf3e40cd1bafadfcb3ab2a837f90ec
/core/CachedThreadResources.h
0b2c97ff93be07328d0887a37f3d58d45deb047c
[ "MIT" ]
permissive
Harsha-Nori/interpret
9baaf487fcb5e58f03ba907835221735ab57b3c0
11994c1d4c62e25fad029f4859dfdf1a3ac85874
refs/heads/master
2020-07-07T20:48:04.993680
2019-08-17T10:25:52
2019-08-17T10:25:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,952
h
// Copyright (c) 2018 Microsoft Corporation // Licensed under the MIT license. // Author: Paul Koch <code@koch.ninja> #ifndef CACHED_THREAD_RESOURCES_H #define CACHED_THREAD_RESOURCES_H #include <queue> #include <stdlib.h> // malloc, realloc, free #include <stddef.h> // size_t, ptrdiff_t #include "EbmInternal.h" // EBM_INLINE #include "Logging.h" // EBM_ASSERT & LOG template<bool bRegression> class TreeNode; template<bool bRegression> class CompareTreeNodeSplittingGain final { public: // TODO : check how efficient this is. Is there a faster way to to this via a function EBM_INLINE bool operator() (const TreeNode<bRegression> * const & lhs, const TreeNode<bRegression> * const & rhs) const { return rhs->m_UNION.afterExaminationForPossibleSplitting.splitGain < lhs->m_UNION.afterExaminationForPossibleSplitting.splitGain; } }; template<bool bRegression> struct HistogramBucketVectorEntry; template<bool bRegression> class CachedTrainingThreadResources { bool m_bError; const CompareTreeNodeSplittingGain<bRegression> m_compareTreeNodeSplitGain; // this allows us to share the memory between underlying data types void * m_aThreadByteBuffer1; size_t m_cThreadByteBufferCapacity1; void * m_aThreadByteBuffer2; size_t m_cThreadByteBufferCapacity2; public: HistogramBucketVectorEntry<bRegression> * const m_aSumHistogramBucketVectorEntry; HistogramBucketVectorEntry<bRegression> * const m_aSumHistogramBucketVectorEntry1; HistogramBucketVectorEntry<bRegression> * const m_aSumHistogramBucketVectorEntryBest; FractionalDataType * const m_aSumResidualErrors2; // THIS SHOULD ALWAYS BE THE LAST ITEM IN THIS STRUCTURE. C++ guarantees that constructions initialize data members in the order that they are declared // since this class can potentially throw an exception in the constructor, we leave it last so that we are guaranteed that the rest of our object has been initialized std::priority_queue<TreeNode<bRegression> *, std::vector<TreeNode<bRegression> *>, CompareTreeNodeSplittingGain<bRegression>> m_bestTreeNodeToSplit; // in case you were wondering, this odd syntax of putting a try outside the function is called "Function try blocks" and it's the best way of handling exception in initialization CachedTrainingThreadResources(const size_t cVectorLength) try : m_bError(true) , m_compareTreeNodeSplitGain() , m_aThreadByteBuffer1(nullptr) , m_cThreadByteBufferCapacity1(0) , m_aThreadByteBuffer2(nullptr) , m_cThreadByteBufferCapacity2(0) , m_aSumHistogramBucketVectorEntry(new (std::nothrow) HistogramBucketVectorEntry<bRegression>[cVectorLength]) , m_aSumHistogramBucketVectorEntry1(new (std::nothrow) HistogramBucketVectorEntry<bRegression>[cVectorLength]) , m_aSumHistogramBucketVectorEntryBest(new (std::nothrow) HistogramBucketVectorEntry<bRegression>[cVectorLength]) , m_aSumResidualErrors2(new (std::nothrow) FractionalDataType[cVectorLength]) // m_bestTreeNodeToSplit should be constructed last because we want everything above to be initialized before the constructor for m_bestTreeNodeToSplit is called since it could throw an exception and we don't want partial state in the rest of the member data. // Construction initialization actually depends on order within the class, so this placement doesn't matter here. , m_bestTreeNodeToSplit(std::priority_queue<TreeNode<bRegression> *, std::vector<TreeNode<bRegression> *>, CompareTreeNodeSplittingGain<bRegression>>(m_compareTreeNodeSplitGain)) { // an unfortunate thing about function exception handling is that accessing non-static data from the catch block gives undefined behavior // so, we can't set m_bError to true if an error occurs, so instead we set it to true in the static initialization // C++ guarantees that initialization will occur in the order the variables are declared (not in the order of initialization) // but since we put m_bError above m_bestTreeNodeToSplit and since m_bestTreeNodeToSplit is the only thing that can throw an exception // if an exception occurs then our m_bError will be left as true m_bError = false; } catch(...) { // the only reason we should potentially find outselves here is if there was an exception thrown during construction of m_bestTreeNodeToSplit // C++ exceptions are suposed to be thrown by value and caught by reference, so it shouldn't be a pointer, and we shouldn't leak memory // according to the spec, it's undefined to access a non-static variable from a Function-try-block, so we can't access m_bError here https://en.cppreference.com/w/cpp/language/function-try-block // so instead of setting it to true here, we set it to true by default and flip it to false if our caller gets to the constructor part } ~CachedTrainingThreadResources() { LOG(TraceLevelInfo, "Entered ~CachedTrainingThreadResources"); free(m_aThreadByteBuffer1); free(m_aThreadByteBuffer2); delete[] m_aSumHistogramBucketVectorEntry; delete[] m_aSumHistogramBucketVectorEntry1; delete[] m_aSumHistogramBucketVectorEntryBest; delete[] m_aSumResidualErrors2; LOG(TraceLevelInfo, "Exited ~CachedTrainingThreadResources"); } EBM_INLINE void * GetThreadByteBuffer1(const size_t cBytesRequired) { if(UNLIKELY(m_cThreadByteBufferCapacity1 < cBytesRequired)) { m_cThreadByteBufferCapacity1 = cBytesRequired << 1; LOG(TraceLevelInfo, "Growing CachedTrainingThreadResources::ThreadByteBuffer1 to %zu", m_cThreadByteBufferCapacity1); // TODO : use malloc here instead of realloc. We don't need to copy the data, and if we free first then we can either slot the new memory in the old slot or it can be moved void * const aNewThreadByteBuffer = realloc(m_aThreadByteBuffer1, m_cThreadByteBufferCapacity1); if(UNLIKELY(nullptr == aNewThreadByteBuffer)) { // according to the realloc spec, if realloc fails to allocate the new memory, it returns nullptr BUT the old memory is valid. // we leave m_aThreadByteBuffer1 alone in this instance and will free that memory later in the destructor return nullptr; } m_aThreadByteBuffer1 = aNewThreadByteBuffer; } return m_aThreadByteBuffer1; } // TODO : we can probably avoid redoing any tree growing IF realloc doesn't move the memory since all the internal pointers would still be valid in that case EBM_INLINE bool GrowThreadByteBuffer2(const size_t cByteBoundaries) { // by adding cByteBoundaries and shifting our existing size, we do 2 things: // 1) we ensure that if we have zero size, we'll get some size that we'll get a non-zero size after the shift // 2) we'll always get back an odd number of items, which is good because we always have an odd number of TreeNodeChilden EBM_ASSERT(0 == m_cThreadByteBufferCapacity2 % cByteBoundaries); m_cThreadByteBufferCapacity2 = cByteBoundaries + (m_cThreadByteBufferCapacity2 << 1); LOG(TraceLevelInfo, "Growing CachedTrainingThreadResources::ThreadByteBuffer2 to %zu", m_cThreadByteBufferCapacity2); // TODO : can we use malloc here? We only need realloc if we need to keep the existing data void * const aNewThreadByteBuffer = realloc(m_aThreadByteBuffer2, m_cThreadByteBufferCapacity2); if(UNLIKELY(nullptr == aNewThreadByteBuffer)) { // according to the realloc spec, if realloc fails to allocate the new memory, it returns nullptr BUT the old memory is valid. // we leave m_aThreadByteBuffer1 alone in this instance and will free that memory later in the destructor return true; } m_aThreadByteBuffer2 = aNewThreadByteBuffer; return false; } EBM_INLINE void * GetThreadByteBuffer2() { return m_aThreadByteBuffer2; } EBM_INLINE size_t GetThreadByteBuffer2Size() const { return m_cThreadByteBufferCapacity2; } EBM_INLINE bool IsError() const { return m_bError || nullptr == m_aSumHistogramBucketVectorEntry || nullptr == m_aSumHistogramBucketVectorEntry1 || nullptr == m_aSumHistogramBucketVectorEntryBest || nullptr == m_aSumResidualErrors2; } }; class CachedInteractionThreadResources { // this allows us to share the memory between underlying data types void * m_aThreadByteBuffer1; size_t m_cThreadByteBufferCapacity1; public: CachedInteractionThreadResources() : m_aThreadByteBuffer1(nullptr) , m_cThreadByteBufferCapacity1(0) { } ~CachedInteractionThreadResources() { LOG(TraceLevelInfo, "Entered ~CachedInteractionThreadResources"); free(m_aThreadByteBuffer1); LOG(TraceLevelInfo, "Exited ~CachedInteractionThreadResources"); } EBM_INLINE void * GetThreadByteBuffer1(const size_t cBytesRequired) { if(UNLIKELY(m_cThreadByteBufferCapacity1 < cBytesRequired)) { m_cThreadByteBufferCapacity1 = cBytesRequired << 1; LOG(TraceLevelInfo, "Growing CachedInteractionThreadResources::ThreadByteBuffer1 to %zu", m_cThreadByteBufferCapacity1); // TODO : use malloc here instead of realloc. We don't need to copy the data, and if we free first then we can either slot the new memory in the old slot or it can be moved void * const aNewThreadByteBuffer = realloc(m_aThreadByteBuffer1, m_cThreadByteBufferCapacity1); if(UNLIKELY(nullptr == aNewThreadByteBuffer)) { // according to the realloc spec, if realloc fails to allocate the new memory, it returns nullptr BUT the old memory is valid. // we leave m_aThreadByteBuffer1 alone in this instance and will free that memory later in the destructor return nullptr; } m_aThreadByteBuffer1 = aNewThreadByteBuffer; } return m_aThreadByteBuffer1; } }; #endif // CACHED_THREAD_RESOURCES_H
[ "interpretml@outlook.com" ]
interpretml@outlook.com
9238ec0186116438c1f7e9c69aed1c1fdbecb341
9f7ae044ec7e6fab9bd27e81b636ea242d3dfa1d
/java/src/gmsecJNI_Config.cpp
cadc6019776084fdb51ee3d57d2478395e368eb2
[]
no_license
barbaroony/GMSEC_API
9ced39b6d6847a14db386264be907403acc911da
85f806c2519104f5e527dab52331c974d590145a
refs/heads/master
2022-12-18T20:52:36.877566
2020-09-25T12:27:13
2020-09-25T12:27:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,311
cpp
/* * Copyright 2007-2020 United States Government as represented by the * Administrator of The National Aeronautics and Space Administration. * No copyright is claimed in the United States under Title 17, U.S. Code. * All Rights Reserved. */ // Config class functions // #include "gov_nasa_gsfc_gmsecapi_jni_gmsecJNI.h" #include "gmsecJNI_Cache.h" #include "gmsecJNI_Jenv.h" #include <gmsec/Config.h> #include <gmsec/Status.h> #include <gmsec/internal/strutil.h> #include <vector> using gmsec::Config; using gmsec::Status; #ifdef __cplusplus extern "C" { #endif /** @brief Creates a new Config object and returns a pointer to it. */ JNIEXPORT jlong JNICALL Java_gov_nasa_gsfc_gmsecapi_jni_gmsecJNI_new_1Config(JNIEnv *jenv, jclass jcls) { Config *created = 0; try { created = new Config(); } JNI_CATCH return JNI_POINTER_TO_JLONG(created); } /** @brief Creates a new Config object with the specified arguments and returns a pointer to it. * @param jargs The arguments to create the Config with. */ JNIEXPORT jlong JNICALL Java_gov_nasa_gsfc_gmsecapi_jni_gmsecJNI_new_1Config_1String(JNIEnv *jenv, jclass jcls, jobjectArray jargs) { Config *created = 0; try { jint size = jenv->GetArrayLength(jargs); if (size < 1) return Java_gov_nasa_gsfc_gmsecapi_jni_gmsecJNI_new_1Config(jenv, jcls); std::vector<char*> args; int i; for (i = 0; jvmOk(jenv, "new Config(String[])") && i < size; ++i) { jstring s = (jstring) jenv->GetObjectArrayElement(jargs, i); JStringManager manager(jenv, s); if (manager.c_str()) args.push_back(gmsec::util::stringNew(manager.c_str())); } if (jvmOk(jenv, "new Config(String[])")) created = new Config((int) args.size(), &args[0]); for (size_t j = 0; j < args.size(); ++j) gmsec::util::stringDestroy(args[j]); } JNI_CATCH return JNI_POINTER_TO_JLONG(created); } /** @brief Creates a Config object as a copy of the specified Config. */ JNIEXPORT jlong JNICALL Java_gov_nasa_gsfc_gmsecapi_jni_gmsecJNI_new_1Config_1Copy(JNIEnv *jenv, jclass jcls, jlong jCfgPtr, jobject jConfig) { Config *created = 0; try { Config *config = JNI_JLONG_TO_CONFIG(jCfgPtr); if (!config) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Config reference is null"); } else { created = new Config(*config); } } JNI_CATCH return JNI_POINTER_TO_JLONG(created); } /** @brief Deletes a Config. */ JNIEXPORT void JNICALL Java_gov_nasa_gsfc_gmsecapi_jni_gmsecJNI_delete_1Config(JNIEnv *jenv, jclass jcls, jlong jCfgPtr, jobject jConfig) { try { Config *config = JNI_JLONG_TO_CONFIG(jCfgPtr); if (!config) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Config reference is null"); } else { delete config; } } JNI_CATCH } /** @brief Adds the specified name-value pair to a Config object. */ JNIEXPORT jlong JNICALL Java_gov_nasa_gsfc_gmsecapi_jni_gmsecJNI_Config_1AddValue(JNIEnv *jenv, jclass jcls, jlong jCfgPtr, jobject jConfig, jstring jName, jstring jValue) { Status *created = 0; try { Status status; Config *config = JNI_JLONG_TO_CONFIG(jCfgPtr); if (!config) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Config reference is null"); } else { JStringManager name(jenv, jName); JStringManager value(jenv, jValue, true); if (jvmOk(jenv, "Config.AddValue") && name.c_str() && value.c_str()) status = config->AddValue(name.c_str(), value.c_str()); created = new Status(status); } } JNI_CATCH return JNI_POINTER_TO_JLONG(created); } /** @brief Clears the name-value pair at the specified name in the specified Config. */ JNIEXPORT jlong JNICALL Java_gov_nasa_gsfc_gmsecapi_jni_gmsecJNI_Config_1ClearValue(JNIEnv *jenv, jclass jcls, jlong jCfgPtr, jobject jConfig, jstring jName) { Status *created = 0; try { Status status; Config *config = JNI_JLONG_TO_CONFIG(jCfgPtr); if (!config) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Config reference is null"); } else { JStringManager name(jenv, jName); if (jvmOk(jenv, "Config.ClearValue")) status = config->ClearValue(name.c_str()); created = new Status(status); } } JNI_CATCH return JNI_POINTER_TO_JLONG(created); } /** @brief Gets the value associated with the specified name in the specified Config. * @param [out] jGvalue The value at the specified name. */ JNIEXPORT jlong JNICALL Java_gov_nasa_gsfc_gmsecapi_jni_gmsecJNI_Config_1GetValue(JNIEnv *jenv, jclass jcls, jlong jCfgPtr, jobject jConfig, jstring jName, jobject jGvalue) { Status * created = 0; try { Status status; Config *config = JNI_JLONG_TO_CONFIG(jCfgPtr); if (!config) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Config reference is null"); } else { const char *value = NULL; JStringManager name(jenv, jName); if (jvmOk(jenv, "Config.GetValue")) { status = config->GetValue(name.c_str(), value); if (!status.isError()) { jstring s = makeJavaString(jenv, value); if (jvmOk(jenv, "Config.GetValue")) { jenv->SetObjectField(jGvalue, Cache::getCache().fieldString_value, s); } } } created = new Status(status); } } JNI_CATCH return JNI_POINTER_TO_JLONG(created); } /** @brief Clears all name-value pairs in the specified Config. */ JNIEXPORT jlong JNICALL Java_gov_nasa_gsfc_gmsecapi_jni_gmsecJNI_Config_1Clear(JNIEnv *jenv, jclass jcls, jlong jCfgPtr, jobject jConfig) { Status *created = 0; try { Status status; Config *config = JNI_JLONG_TO_CONFIG(jCfgPtr); if (!config) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Config reference is null"); } else { status = config->Clear(); created = new Status(status); } } JNI_CATCH return JNI_POINTER_TO_JLONG(created); } /** @brief Gets the first name-value pair out of the specified config object. * @param [out] jGname The name of the first pair. * @param [out] jGvalue The value of the first pair. */ JNIEXPORT jlong JNICALL Java_gov_nasa_gsfc_gmsecapi_jni_gmsecJNI_Config_1GetFirst(JNIEnv *jenv, jclass jcls, jlong jCfgPtr, jobject jConfig, jobject jGname, jobject jGvalue) { Status *created = 0; try { Status status; Config *config = JNI_JLONG_TO_CONFIG(jCfgPtr); if (!config) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Config reference is null"); } else { const char *name = NULL; const char *value = NULL; status = config->GetFirst(name, value); if (!status.isError()) { jstring jName = makeJavaString(jenv, name); if (jvmOk(jenv, "Config.GetFirst")) jenv->SetObjectField(jGname, Cache::getCache().fieldString_value, jName); jstring jValue = 0; if (jvmOk(jenv, "Config.GetFirst")) jValue = makeJavaString(jenv, value); if (jvmOk(jenv, "Config.GetFirst")) jenv->SetObjectField(jGvalue, Cache::getCache().fieldString_value, jValue); } created = new Status(status); } } JNI_CATCH return JNI_POINTER_TO_JLONG(created); } /** @brief Gets a name-value pair from the specified Config object. Subsequent * calls to this method on the same Config will get subsequent names and * values. * @param [out] name The name of the next name-value pair. * @param [out] value The value of the next name-value pair. */ JNIEXPORT jlong JNICALL Java_gov_nasa_gsfc_gmsecapi_jni_gmsecJNI_Config_1GetNext(JNIEnv *jenv, jclass jcls, jlong jCfgPtr, jobject jConfig, jobject jGname, jobject jGvalue) { Status *created = 0; try { Status status; Config *config = JNI_JLONG_TO_CONFIG(jCfgPtr); if (!config) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Config reference is null"); } else { const char *name = NULL; const char *value = NULL; status = config->GetNext(name, value); if (!status.isError()) { jstring jName = makeJavaString(jenv, name); if (jvmOk(jenv, "Config.GetNext")) jenv->SetObjectField(jGname, Cache::getCache().fieldString_value, jName); jstring jValue = 0; if (jvmOk(jenv, "Config.GetNext")) jValue = makeJavaString(jenv, value); if (jvmOk(jenv, "Config.GetNext")) jenv->SetObjectField(jGvalue, Cache::getCache().fieldString_value, jValue); } created = new Status(status); } } JNI_CATCH return JNI_POINTER_TO_JLONG(created); } /** @brief Converts the specified Config object to XML. * @param [out] outxml The XML representation of this Config. */ JNIEXPORT jlong JNICALL Java_gov_nasa_gsfc_gmsecapi_jni_gmsecJNI_Config_1ToXML(JNIEnv *jenv, jclass jcls, jlong ptr, jobject jConfig, jobject outxml) { Status *created = 0; try { Status status; Config *config = JNI_JLONG_TO_CONFIG(ptr); if (!config) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Config reference is null"); } else { const char *tmp = NULL; status = config->ToXML(tmp); if (!status.isError()) { jstring s = makeJavaString(jenv, tmp); if (jvmOk(jenv, "Config.ToXML")) { jenv->SetObjectField(outxml, Cache::getCache().fieldString_value, s); jvmOk(jenv, "Config.ToXML"); } } created = new Status(status); } } JNI_CATCH return JNI_POINTER_TO_JLONG(created); } /** @brief Creates a Config from an XML representation. * @param [out] jConfig The new Config object. */ JNIEXPORT jlong JNICALL Java_gov_nasa_gsfc_gmsecapi_jni_gmsecJNI_Config_1FromXML(JNIEnv *jenv, jclass jcls, jlong ptr, jobject jConfig, jstring inxml) { Status *created = 0; try { Status status; Config *config = JNI_JLONG_TO_CONFIG(ptr); if (!config) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Config reference is null"); } else { JStringManager xml(jenv, inxml); if (jvmOk(jenv, "Config.FromXML")) status = config->FromXML(xml.c_str()); created = new Status(status); } } JNI_CATCH return JNI_POINTER_TO_JLONG(created); } #ifdef __cplusplus } #endif
[ "david.m.whitney@nasa.gov" ]
david.m.whitney@nasa.gov
a199e142517618a043f1d959c1b07bb5aad04a3f
8bfa3c91abe7f22bffc3115c1fa48ed1a4aabd82
/ABC/108/D/all_your_paths_are_different_lengths.cpp
3f2d4e0678dac9909cd80e3ab068d380a2fdd4ac
[]
no_license
yugo1103/atcoder
96a0dcd41704fadc0a1ef3253cdffa4a961fdc0a
9b2d0b1a0f178cd442d51d2ad07added982d2a92
refs/heads/master
2020-07-26T04:04:41.019118
2020-03-30T10:42:39
2020-03-30T10:42:39
208,528,448
0
0
null
null
null
null
UTF-8
C++
false
false
1,523
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define rep(i,a,b) for(ll i=a;i<b;i++) #define rrep(i,a,b) for(ll i=a;i>=b;i--) #define fore(i,a) for(auto &i:a) #define all(x) (x).begin(),(x).end() int main(void){ ll l; cin >> l; vector<pair<ll, ll>> path[60]; ll current_num = 2; ll last_v = 1; ll path_num = 2; path[0].push_back(pair<ll, ll>(1,0)); path[0].push_back(pair<ll, ll>(1,1)); ll tmp = l; vector<ll> seq; seq.push_back(tmp); if(tmp % 2 == 1){ tmp--; seq.push_back(tmp); } while(tmp != 2){ tmp /= 2; seq.push_back(tmp); if(tmp % 2 == 1){ tmp--; seq.push_back(tmp); } } rrep(x, seq.size()-2, 0){ if(current_num == seq[x] / 2.0){ current_num *= 2; rep(i, 0, 60){ fore(a, path[i]){ a.second *= 2; } } path[last_v].push_back(pair<ll, ll>(last_v + 1,0)); path[last_v].push_back(pair<ll, ll>(last_v + 1,1)); last_v++; path_num += 2; }else{ current_num++; path[0].push_back(pair<ll, ll>(last_v, current_num - 1)); path_num++; } } cout << last_v + 1 << " " << path_num << endl; rep(i, 0, 60){ fore(a, path[i]){ cout << i + 1 << " " << a.first + 1 << " " << a.second << endl; } } return 0; }
[ "y1103orz@akane.waseda.jp" ]
y1103orz@akane.waseda.jp
e4ffe651166c28728bc164656c0d8bc0f017f98b
69a94a9316bf97d8ae783d880c5688f52f11c0aa
/mame/src/mess/machine/coco_vhd.h
7d514b0d503ee3c7102c7c1149a9e48c3cc1c108
[]
no_license
bradparks/UME-Core
530fd1dee865453f8a7c00ca2d7c9b2b5b59d34e
ed48bd0e86f701e0f1a22150445ae42ac57aa4aa
refs/heads/master
2021-01-22T23:57:48.291810
2015-11-10T08:43:50
2015-11-10T08:44:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,307
h
/*************************************************************************** coco_vhd.h Color Computer Virtual Hard Drives ***************************************************************************/ #ifndef COCOVHD_H #define COCOVHD_H #include "image.h" /*************************************************************************** TYPE DEFINITIONS ***************************************************************************/ // ======================> coco_vhd_image_device class coco_vhd_image_device : public device_t, public device_image_interface { public: // construction/destruction coco_vhd_image_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock); virtual ~coco_vhd_image_device(); // image-level overrides virtual bool call_load(); virtual iodevice_t image_type() const { return IO_HARDDISK; } virtual bool is_readable() const { return 1; } virtual bool is_writeable() const { return 1; } virtual bool is_creatable() const { return 1; } virtual bool must_be_loaded() const { return 0; } virtual bool is_reset_on_load() const { return 0; } virtual const char *image_interface() const { return NULL; } virtual const char *file_extensions() const { return "vhd"; } virtual const option_guide *create_option_guide() const { return NULL; } // specific implementation DECLARE_READ8_MEMBER(read) { return read(offset); } DECLARE_WRITE8_MEMBER(write) { write(offset, data); } UINT8 read(offs_t offset); void write(offs_t offset, UINT8 data); protected: // device-level overrides virtual void device_config_complete(); virtual void device_start(); void coco_vhd_readwrite(UINT8 data); private: cpu_device * m_cpu; address_space * m_cpu_space; UINT32 m_logical_record_number; UINT32 m_buffer_address; UINT8 m_status; }; // device type definition extern const device_type COCO_VHD; /*************************************************************************** DEVICE CONFIGURATION MACROS ***************************************************************************/ #define MCFG_COCO_VHD_ADD(_tag) \ MCFG_DEVICE_ADD(_tag, COCO_VHD, 0) #endif /* COCOVHD_H */
[ "conrad@kramerapps.com" ]
conrad@kramerapps.com
8966b639443ee6a677669be55c4e17926383b2f5
f2d9d0ca26c21ce7a1a6be5185229bf21dff722c
/include/CurveSegment.hpp
c4535cb2bfed7761cc325b502c1dca203c885f2b
[ "MIT" ]
permissive
agehama/BezierCurveEditor
3cff103f4ec3c9ce067c292874fa4b7da9c81286
56b047efed9c037db98ccb5f4380e27072536409
refs/heads/master
2021-01-19T20:55:01.511550
2017-08-25T01:36:53
2017-08-25T01:36:53
101,239,122
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
4,742
hpp
#pragma once #include <Siv3D.hpp> #include "include/SegmentTree.hpp" /* 三次ベジェ曲線で構成されたパスの1セグメントを表すクラス 他のセグメントとの交差判定はSegmentTreeを使って二分探索で行う 自分との交差判定は記号解を用いて行う */ class CurveSegment { public: CurveSegment() = default; CurveSegment(const Vec2& p0, const Vec2& p1, const Vec2& p2, const Vec2& p3) : m_curve(p0, p1, p2, p3) { init(); } void draw()const { m_segmentTree->draw(); } std::vector<SegmentTree::CurvePoint> intersectionPoints(CurveSegment& other) { std::vector<SegmentTree::CurvePoint> result; return m_segmentTree->intersectionPoints(m_curve, other.m_segmentTree, other.m_curve); } Optional<SegmentTree::CurvePoint> selfIntersection()const { /* Reduce[(1 - t)^3 x1 + 3(1 - t)^2 t x2 + 3(1 - t) t^2 x3 + t^3 x4 == (1 - s)^3 x1 + 3(1 - s)^2 s x2 + 3(1 - s) s^2 x3 + s^3 x4 && (1 - t)^3 y1 + 3(1 - t)^2 t y2 + 3(1 - t) t^2 y3 + t^3 y4 == (1 - s)^3 y1 + 3(1 - s)^2 s y2 + 3(1 - s) s^2 y3 + s^3 y4 && s != t, {s, t}] をFactor,Simplifyを使って整形したもの */ double x1 = m_curve.p0.x, x2 = m_curve.p1.x, x3 = m_curve.p2.x, x4 = m_curve.p3.x; double y1 = m_curve.p0.y, y2 = m_curve.p1.y, y3 = m_curve.p2.y, y4 = m_curve.p3.y; const double a = 2 * x2*y1 - 3 * x3*y1 + x4*y1 - 2 * x1*y2 + 3 * x3*y2 - x4*y2 + 3 * x1*y3 - 3 * x2*y3 - x1*y4 + x2*y4; const double b = x2*y1 - 2 * x3*y1 + x4*y1 - x1*y2 + 3 * x3*y2 - 2 * x4*y2 + 2 * x1*y3 - 3 * x2*y3 + x4*y3 - x1*y4 + 2 * x2*y4 - x3*y4; const double c = a*b; const double d = x4*(y1 - 2 * y2 + y3) - x3*(2 * y1 - 3 * y2 + y4) - x1*(y2 - 2 * y3 + y4) + x2*(y1 - 3 * y3 + 2 * y4); const double s = ( c - Sqrt( c*c - 4 * (x4*x4*y1*y1 - x1*x4*y1*y2 - 2 * x4*x4*y1*y2 + x1*x1*y2*y2 - 2 * x1*x4*y2*y2 + x4*x4*y2*y2 + 3 * x1*x4*y1*y3 - 3 * x1*x1*y2*y3 + 3 * x1*x4*y2*y3 + 3 * x1*x1*y3*y3 - 3 * x1*x4*y3*y3 + 3 * x3*x3*(y1 - y2)*(y1 - y4) + x2*x2*(y1 - y4)*(y1 - y4) - 2 * x1*x4*y1*y4 + x1*x1*y2*y4 + 2 * x1*x4*y2*y4 - 3 * x1*x1*y3*y4 + x1*x1*y4*y4 + x2* (-3 * x3*(y1 - y3)*(y1 - y4) + x4*(y1*y1 + 3 * y3*y3 - 2 * y2*y4 + 2 * y1*(y2 - 3 * y3 + y4)) - x1*(3 * y3*y3 - 3 * y3*y4 + 2 * y4*(-y2 + y4) + y1*(2 * y2 - 3 * y3 + y4))) + 3 * x3*(-(x4*(y1 - y2)*(y1 - y3)) + x1*(y2*y3 - 2 * y2*y4 + y3*y4 + y1*(y2 - 2 * y3 + y4)))) * b*b ) ) / (2.*d*d); const double t = (3 * (-((x3 - x4)*(y1 - y2)) + (x1 - x2)*(y3 - y4)) + 3 * s*(-(x4*(y1 - 2 * y2 + y3)) + x3*(2 * y1 - 3 * y2 + y4) + x1*(y2 - 2 * y3 + y4) - x2*(y1 - 3 * y3 + 2 * y4)) + 2 * s*s*(x4*(y1 - 2 * y2 + y3) - x3*(2 * y1 - 3 * y2 + y4) - x1*(y2 - 2 * y3 + y4) + x2*(y1 - 3 * y3 + 2 * y4))) / (x4*(y1 - 4 * y2 + 3 * y3) - x2*(y1 + 3 * y3 - 4 * y4) + (x1 + 3 * x3)*(y2 - y4)); if (0.0 < s&&s < 1.0&&0.0 < t&&t < 1.0) { return SegmentTree::CurvePoint(s, m_curve(s)); } return none; } void print()const { Println(m_segmentTree->boundingRect().toString()); } const BezierCurve& curve()const { return m_curve; } private: void init() { std::deque<SegmentTree::CurvePoint> curvePoints; const auto& p0 = m_curve.p0; const auto& p1 = m_curve.p1; const auto& p2 = m_curve.p2; const auto& p3 = m_curve.p3; /* https://stackoverflow.com/questions/24809978/calculating-the-bounding-box-of-cubic-bezier-curve */ const Vec2 a = (-3 * p0 + 9 * p1 - 9 * p2 + 3 * p3); const Vec2 b = (6 * p0 - 12 * p1 + 6 * p2); const Vec2 c = 3 * (p1 - p0); const Vec2 d = b*b - 4 * a*c; curvePoints.emplace_back(0.0, p0); if (0 < d.x) { const double dSqrt = sqrt(d.x); const double t1 = (-b.x + dSqrt) / (2 * a.x); const double t2 = (-b.x - dSqrt) / (2 * a.x); if (0 < t1&&t1 < 1) { curvePoints.emplace_back(t1, m_curve(t1)); } if (0 < t2&&t2 < 1) { curvePoints.emplace_back(t2, m_curve(t2)); } } if (0 < d.y) { const double dSqrt = sqrt(d.y); const double t1 = (-b.y + dSqrt) / (2 * a.y); const double t2 = (-b.y - dSqrt) / (2 * a.y); if (0 < t1&&t1 < 1) { curvePoints.emplace_back(t1, m_curve(t1)); } if (0 < t2&&t2 < 1) { curvePoints.emplace_back(t2, m_curve(t2)); } } curvePoints.emplace_back(1.0, p3); std::sort(curvePoints.begin(), curvePoints.end(), [](const SegmentTree::CurvePoint& a, const SegmentTree::CurvePoint& b) {return a.first < b.first; }); m_segmentTree = std::make_shared<SegmentTree>(0.0, 1.0, curvePoints); } BezierCurve m_curve; std::shared_ptr<SegmentTree> m_segmentTree; };
[ "agehama1@gmail.com" ]
agehama1@gmail.com
10e862994b494816c28416b49884cc3e0acddbc1
2a7a74f42670ba916e87a4b62bc46b32db8ef522
/src/imperative/cached_op.cc
afaa32c2a345d085b14c509560b9f2949cb559e2
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause", "MIT", "BSD-2-Clause-Views", "LicenseRef-scancode-unknown-license-reference" ]
permissive
sergeykolychev/mxnet
30eeb933156d509c99e2c0cde6c06fb7f2ed86c0
d6290ad647249d0329125730f6544ce5a4192062
refs/heads/master
2020-12-31T07:00:06.159000
2017-09-25T00:28:04
2017-09-25T00:28:04
80,577,235
7
0
null
2017-09-08T01:32:22
2017-02-01T00:44:23
Python
UTF-8
C++
false
false
17,184
cc
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <unordered_set> #include <iostream> #include "./imperative_utils.h" namespace mxnet { Imperative::CachedOp::CachedOp(const nnvm::Symbol& sym) { using namespace nnvm; using namespace imperative; static const std::vector<const Op*> zero_ops{Op::Get("zeros_like"), Op::Get("_zeros")}; static const auto _copy = Op::Get("_copy"); // construct forward graph { NodeEntryMap<int> dedup_out; for (const auto& i : sym.outputs) { if (dedup_out.count(i)) { NodePtr copy_node = Node::Create(); copy_node->attrs.op = _copy; copy_node->attrs.name = i.node->attrs.name + "_copy" + std::to_string(dedup_out[i]++); copy_node->inputs.emplace_back(i); if (_copy->attr_parser != nullptr) { _copy->attr_parser(&(copy_node->attrs)); } fwd_graph_.outputs.push_back(NodeEntry{copy_node, 0, 0}); } else { dedup_out.insert({i, 0}); fwd_graph_.outputs.push_back(i); } } const auto& idx = fwd_graph_.indexed_graph(); CHECK_GE(idx.input_nodes().size(), 1) << "CachedOp requires at least 1 input"; std::vector<uint32_t> ref_count(idx.num_node_entries(), 0); for (const auto& i : idx.input_nodes()) ++ref_count[idx.entry_id(i, 0)]; for (const auto& i : idx.outputs()) ++ref_count[idx.entry_id(i)]; for (size_t i = 0; i < idx.num_nodes(); ++i) { for (const auto& j : idx[i].inputs) ++ref_count[idx.entry_id(j)]; } fwd_graph_.attrs["forward_ref_count"] = std::make_shared<dmlc::any>(std::move(ref_count)); } // construct backward graph std::vector<NodeEntry> ograd_entries; { ograd_entries.reserve(fwd_graph_.outputs.size()); for (size_t i = 0; i < fwd_graph_.outputs.size(); ++i) { ograd_entries.emplace_back(NodeEntry{Node::Create(), 0, 0}); } std::vector<NodeEntry> xs; std::vector<NodePtr> args = sym.ListInputs(Symbol::kReadOnlyArgs); xs.reserve(args.size()); for (const auto& i : args) xs.emplace_back(NodeEntry{i, 0, 0}); CHECK_GT(xs.size(), 0) << "There are no inputs in computation graph that require gradients."; grad_graph_ = pass::Gradient( fwd_graph_, fwd_graph_.outputs, xs, ograd_entries, exec::AggregateGradient, nullptr, nullptr, zero_ops, "_copy"); } // construct full graph { size_t num_forward_nodes = fwd_graph_.indexed_graph().num_nodes(); size_t num_forward_entries = fwd_graph_.indexed_graph().num_node_entries(); full_graph_.outputs = fwd_graph_.outputs; curr_grad_req_ = std::vector<bool>(grad_graph_.outputs.size(), true); for (const auto& i : grad_graph_.outputs) full_graph_.outputs.emplace_back(i); const auto& idx = full_graph_.indexed_graph(); std::vector<uint32_t> ref_count(idx.num_node_entries(), 0); for (size_t i = num_forward_nodes; i < idx.num_nodes(); ++i) { for (const auto& j : idx[i].inputs) { ++ref_count[idx.entry_id(j)]; } } auto full_ref_count = fwd_graph_.GetAttr<std::vector<uint32_t> >("forward_ref_count"); for (size_t i = 0; i < num_forward_entries; ++i) full_ref_count[i] += ref_count[i]; fwd_graph_.attrs["full_ref_count"] = std::make_shared<dmlc::any>(std::move(full_ref_count)); size_t num_forward_inputs = num_inputs(); for (uint32_t i = 0; i < ograd_entries.size(); ++i) { if (!idx.exist(ograd_entries[i].node.get())) continue; auto eid = idx.entry_id(ograd_entries[i]); if (ref_count[eid] > 0) { bwd_ograd_dep_.push_back(i); bwd_input_eid_.push_back(eid); } } save_inputs_.resize(num_forward_inputs, false); for (uint32_t i = 0; i < num_forward_inputs; ++i) { auto eid = idx.entry_id(idx.input_nodes()[i], 0); if (ref_count[eid] > 0) { save_inputs_[i] = true; bwd_in_dep_.push_back(i); bwd_input_eid_.push_back(eid); } } save_outputs_.resize(idx.outputs().size(), false); for (uint32_t i = 0; i < idx.outputs().size(); ++i) { auto eid = idx.entry_id(idx.outputs()[i]); if (ref_count[eid] > 0) { save_outputs_[i] = true; bwd_out_dep_.push_back(i); bwd_input_eid_.push_back(eid); } } } } std::vector<nnvm::NodeEntry> Imperative::CachedOp::Gradient( const nnvm::NodePtr& node, const std::vector<nnvm::NodeEntry>& ograds) { using namespace nnvm; static const auto _backward_CachedOp = Op::Get("_backward_CachedOp"); static const auto _CachedOp_NoGrad = Op::Get("_CachedOp_NoGrad"); auto p = Node::Create(); p->attrs.op = _backward_CachedOp; p->attrs.name = node->attrs.name + "_backward"; p->attrs.parsed = node->attrs.parsed; p->control_deps.push_back(node); p->inputs.reserve(bwd_ograd_dep_.size() + bwd_in_dep_.size() + bwd_out_dep_.size()); for (auto i : bwd_ograd_dep_) p->inputs.push_back(ograds[i]); for (auto i : bwd_in_dep_) p->inputs.push_back(node->inputs[i]); for (auto i : bwd_out_dep_) p->inputs.emplace_back(NodeEntry{node, i, 0}); std::vector<NodeEntry> ret; ret.reserve(num_inputs()); const auto& auxs = mutable_input_nodes(); if (auxs.size()) { auto nop = Node::Create(); nop->attrs.op = _CachedOp_NoGrad; nop->attrs.parsed = static_cast<uint32_t>(auxs.size()); nop->control_deps.push_back(node); uint32_t j = 0, k = 0; for (const auto& i : fwd_graph_.indexed_graph().input_nodes()) { if (auxs.count(i)) { ret.emplace_back(NodeEntry{nop, j++, 0}); } else { ret.emplace_back(NodeEntry{p, k++, 0}); } } } else { for (uint32_t i = 0; i < num_inputs(); ++i) ret.emplace_back(NodeEntry{p, i, 0}); } return ret; } nnvm::Graph Imperative::CachedOp::GetForwardGraph( const bool recording, const std::vector<NDArray*>& inputs) { using namespace nnvm; using namespace imperative; std::lock_guard<std::mutex> lock(mutex_); CHECK_EQ(inputs.size(), num_inputs()); nnvm::Graph& g = fwd_graph_; ShapeVector shape_inputs; DTypeVector dtype_inputs; StorageTypeVector storage_type_inputs; shape_inputs.reserve(inputs.size()); dtype_inputs.reserve(inputs.size()); storage_type_inputs.reserve(inputs.size()); for (uint32_t i = 0; i < inputs.size(); ++i) { shape_inputs.emplace_back(inputs[i]->shape()); dtype_inputs.emplace_back(inputs[i]->dtype()); storage_type_inputs.emplace_back(inputs[i]->storage_type()); } bool match = true; match &= CheckAndInferShape(&g, std::move(shape_inputs), true); match &= CheckAndInferType(&g, std::move(dtype_inputs), true); match &= CheckAndInferStorageType(&g, inputs[0]->ctx(), std::move(storage_type_inputs), true); if (!match) { g.attrs.erase("forward_mem_plan"); g.attrs.erase("full_mem_plan"); } else if (g.attrs.count(recording ? "full_mem_plan" : "forward_mem_plan")) { return g; } const auto& idx = g.indexed_graph(); StorageVector storage(idx.num_node_entries(), exec::kBadStorageID); for (const auto i : idx.input_nodes()) storage[idx.entry_id(i, 0)] = exec::kExternalStorageID; auto mem_plan = PlanMemory( &g, std::move(storage), g.GetAttr<std::vector<uint32_t> >( recording ? "full_ref_count" : "forward_ref_count")); g.attrs[recording ? "full_mem_plan" : "forward_mem_plan"] = std::make_shared<dmlc::any>(std::move(mem_plan)); return g; } nnvm::Graph Imperative::CachedOp::GetBackwardGraph( const OpStatePtr& op_state, const std::vector<OpReqType>& reqs, const std::vector<NDArray*>& inputs) { using namespace nnvm; using namespace imperative; std::lock_guard<std::mutex> lock(mutex_); nnvm::Graph& g = full_graph_; auto& state = op_state.get_state<CachedOpState>(); bool req_match = true; for (size_t i = 0; i < reqs.size(); ++i) { if (curr_grad_req_[i] != (reqs[i] != kNullOp)) { curr_grad_req_[i] = reqs[i] != kNullOp; req_match = false; } } if (!req_match) { g = nnvm::Graph(); g.outputs = fwd_graph_.outputs; for (size_t i = 0; i < grad_graph_.outputs.size(); ++i) { if (curr_grad_req_[i]) g.outputs.emplace_back(grad_graph_.outputs[i]); } } const auto& idx = g.indexed_graph(); size_t num_forward_nodes = fwd_graph_.indexed_graph().num_nodes(); size_t num_forward_entries = fwd_graph_.indexed_graph().num_node_entries(); if (!g.attrs.count("backward_ref_count")) { std::vector<uint32_t> ref_count(idx.num_node_entries(), 0); for (size_t i = num_forward_nodes; i < idx.num_nodes(); ++i) { for (const auto& j : idx[i].inputs) ++ref_count[idx.entry_id(j)]; } for (size_t i = 0; i < inputs.size(); ++i) ++ref_count[bwd_input_eid_[i]]; for (const auto& i : idx.outputs()) ++ref_count[idx.entry_id(i)]; g.attrs["backward_ref_count"] = std::make_shared<dmlc::any>(std::move(ref_count)); } ShapeVector shapes(idx.num_node_entries(), TShape()); DTypeVector dtypes(idx.num_node_entries(), -1); StorageTypeVector stypes(idx.num_node_entries(), -1); for (size_t i = 0; i < num_forward_entries; ++i) { shapes[i] = state.buff[i].shape(); dtypes[i] = state.buff[i].dtype(); stypes[i] = state.buff[i].storage_type(); } std::pair<uint32_t, uint32_t> node_range, entry_range; node_range = {num_forward_nodes, idx.num_nodes()}; entry_range = {num_forward_entries, idx.num_node_entries()}; bool match = true; match &= CheckAndInferShape(&g, std::move(shapes), false, node_range, entry_range); match &= CheckAndInferType(&g, std::move(dtypes), false, node_range, entry_range); match &= CheckAndInferStorageType(&g, inputs[0]->ctx(), std::move(stypes), false, node_range, entry_range); if (!match) { g.attrs.erase("backward_mem_plan"); } else if (g.attrs.count("backward_mem_plan")) { return g; } StorageVector storage(idx.num_node_entries(), exec::kBadStorageID); for (size_t i = 0; i < num_forward_entries; ++i) storage[i] = exec::kExternalStorageID; for (const auto i : idx.input_nodes()) storage[idx.entry_id(i, 0)] = exec::kExternalStorageID; for (const auto i : idx.outputs()) storage[idx.entry_id(i)] = exec::kExternalStorageID; auto mem_plan = PlanMemory( &g, std::move(storage), g.GetAttr<std::vector<uint32_t> >("backward_ref_count"), {num_forward_nodes, idx.num_nodes()}, {num_forward_entries, idx.num_node_entries()}); g.attrs["backward_mem_plan"] = std::make_shared<dmlc::any>(std::move(mem_plan)); return g; } OpStatePtr Imperative::CachedOp::Forward(const std::vector<NDArray*>& inputs, const std::vector<NDArray*>& outputs) { using namespace nnvm; using namespace imperative; bool recording = Imperative::Get()->set_is_recording(false); // Initialize nnvm::Graph g = GetForwardGraph(recording, inputs); const auto& idx = g.indexed_graph(); size_t num_inputs = idx.input_nodes().size(); auto op_state_ptr = OpStatePtr::Create<CachedOpState>(); auto& cached_op_state = op_state_ptr.get_state<CachedOpState>(); auto& buff = cached_op_state.buff; auto& states = cached_op_state.states; // Allocate entries states.resize(idx.num_nodes()); buff.resize(idx.num_node_entries()); states.reserve(idx.num_nodes()); std::vector<NDArray*> arrays; arrays.reserve(buff.size()); for (size_t i = 0; i < buff.size(); ++i) arrays.push_back(&buff[i]); for (size_t i = 0; i < num_inputs; ++i) { arrays[idx.entry_id(idx.input_nodes()[i], 0)] = inputs[i]; } for (size_t i = 0; i < idx.outputs().size(); ++i) { auto eid = idx.entry_id(idx.outputs()[i]); if (!arrays[eid]->is_none()) *outputs[i] = arrays[eid]->Detach(); arrays[eid] = outputs[i]; } // Allocate NDArrays std::vector<uint32_t> ref_count = g.GetAttr<std::vector<uint32_t> >( recording ? "full_ref_count" : "forward_ref_count"); std::vector<OpReqType> array_reqs(arrays.size(), kWriteTo); for (size_t i = 0; i < idx.num_node_entries(); ++i) { if (ref_count[i] == 0) array_reqs[i] = kNullOp; } Context default_ctx = inputs[0]->ctx(); const auto& mem_plan = g.GetAttr<MemoryPlanVector >( recording ? "full_mem_plan" : "forward_mem_plan"); AllocateMemory(g, idx, default_ctx, 0, idx.num_node_entries(), mem_plan, arrays, &array_reqs); Imperative::Get()->RunGraph( false, default_ctx, idx, arrays, 0, idx.num_nodes(), std::move(array_reqs), std::move(ref_count), &states); for (size_t i = 0; i < idx.num_node_entries(); ++i) { if (arrays[i] == &buff[i]) continue; buff[i].shape_ = arrays[i]->shape_; buff[i].dtype_ = arrays[i]->dtype_; buff[i].storage_type_ = arrays[i]->storage_type_; } Imperative::Get()->set_is_recording(recording); return op_state_ptr; } void Imperative::CachedOp::Backward( const bool retain_graph, const OpStatePtr& state, const std::vector<NDArray*>& inputs, const std::vector<OpReqType>& reqs, const std::vector<NDArray*>& outputs) { using namespace nnvm; using namespace imperative; CHECK(!Imperative::Get()->is_recording()) << "CachedOp does not support higher order gradients. " << "If you want to do backward with create_graph=True please " << "do not use hybridize."; // Initialize nnvm::Graph g = GetBackwardGraph(state, reqs, inputs); const auto& idx = g.indexed_graph(); auto& cached_op_state = state.get_state<CachedOpState>(); auto& buff = cached_op_state.buff; auto& states = cached_op_state.states; size_t num_forward_outputs = fwd_graph_.outputs.size(); size_t num_forward_nodes = fwd_graph_.indexed_graph().num_nodes(); size_t num_forward_entries = fwd_graph_.indexed_graph().num_node_entries(); buff.resize(idx.num_node_entries()); std::vector<NDArray*> arrays; arrays.reserve(buff.size()); for (size_t i = 0; i < buff.size(); ++i) arrays.push_back(&buff[i]); for (size_t i = 0; i < inputs.size(); ++i) { arrays[bwd_input_eid_[i]] = inputs[i]; } for (size_t i = 0, j = num_forward_outputs; i < reqs.size(); ++i) { if (reqs[i] == kNullOp) continue; arrays[idx.entry_id(idx.outputs()[j++])] = outputs[i]; } // Allocate NDArrays auto ref_count = g.GetAttr<std::vector<uint32_t> >("backward_ref_count"); if (retain_graph) { for (size_t i = 0; i < num_forward_entries; ++i) ++ref_count[i]; } std::vector<OpReqType> array_reqs(arrays.size(), kWriteTo); for (size_t i = num_forward_entries; i < idx.num_node_entries(); ++i) { if (ref_count[i] == 0) array_reqs[i] = kNullOp; } Context default_ctx = outputs[0]->ctx(); const auto& mem_plan = g.GetAttr<MemoryPlanVector >("backward_mem_plan"); AllocateMemory(g, idx, default_ctx, num_forward_entries, idx.num_node_entries(), mem_plan, arrays, &array_reqs); Imperative::Get()->RunGraph( retain_graph, default_ctx, idx, arrays, num_forward_nodes, idx.num_nodes(), std::move(array_reqs), std::move(ref_count), &states); if (retain_graph) { buff.resize(num_forward_entries); } else { buff.clear(); states.clear(); } } NNVM_REGISTER_OP(_CachedOp) .set_num_inputs([](const NodeAttrs& attrs) { const CachedOpPtr& op = nnvm::get<CachedOpPtr>(attrs.parsed); return op->num_inputs(); }) .set_num_outputs([](const NodeAttrs& attrs) { const CachedOpPtr& op = nnvm::get<CachedOpPtr>(attrs.parsed); return op->num_outputs(); }) .set_attr<nnvm::FGradient>("FGradient", [](const nnvm::NodePtr& n, const std::vector<nnvm::NodeEntry>& ograds) { const CachedOpPtr& op = nnvm::get<CachedOpPtr>(n->attrs.parsed); return op->Gradient(n, ograds); }); NNVM_REGISTER_OP(_backward_CachedOp) .set_num_inputs([](const NodeAttrs& attrs){ const CachedOpPtr& op = nnvm::get<CachedOpPtr>(attrs.parsed); return op->num_backward_inputs(); }) .set_num_outputs([](const NodeAttrs& attrs){ const CachedOpPtr& op = nnvm::get<CachedOpPtr>(attrs.parsed); return op->num_inputs() - op->mutable_input_nodes().size(); }) .set_attr<bool>("TIsLayerOpBackward", true) .set_attr<bool>("TIsBackward", true); NNVM_REGISTER_OP(_CachedOp_NoGrad) .set_num_inputs(0) .set_num_outputs([](const NodeAttrs& attrs) { const uint32_t& nout = nnvm::get<uint32_t>(attrs.parsed); return nout; }); } // namespace mxnet
[ "noreply@github.com" ]
noreply@github.com
4ef6ba180c6757d932ece10426f15e56d9eb528c
c20c4812ac0164c8ec2434e1126c1fdb1a2cc09e
/Source/Source/KG3DEngine/KG3DEngine/KG3DFontRenderer.h
27f505e21bca0d939f5c9b559f52235b43fc83eb
[ "MIT" ]
permissive
uvbs/FullSource
f8673b02e10c8c749b9b88bf18018a69158e8cb9
07601c5f18d243fb478735b7bdcb8955598b9a90
refs/heads/master
2020-03-24T03:11:13.148940
2018-07-25T18:30:25
2018-07-25T18:30:25
142,408,505
2
2
null
2018-07-26T07:58:12
2018-07-26T07:58:12
null
UTF-8
C++
false
false
2,575
h
//////////////////////////////////////////////////////////////////////////////// // // FileName : KG3DFontRenderer.h // Version : 1.0 // Creator : dengchao // Create Date : 2006-02-13 16:43:32 // Comment : font renderer // //////////////////////////////////////////////////////////////////////////////// #ifndef _INCLUDE_KG3DFONTRENDERER_H_ #define _INCLUDE_KG3DFONTRENDERER_H_ #include "./KG3DFontDescr.h" class KG3DFontRenderer { private: enum { MAX_FONT = 128 }; enum { MAX_RENDER_BATCH = 16 }; enum { MAX_FONT_VERTEX = MAX_FONT * 4 }; enum { MAX_FONT_VERTEX_INDEX = MAX_FONT * 6 }; struct KRenderBatch { LPDIRECT3DTEXTURE9 pTexture; LPDIRECT3DVERTEXBUFFER9 pVB; UINT uTLVertex; }; typedef std::vector<LPDIRECT3DTEXTURE9> KTextureArray; public: enum { INVALID_TEXTURE_INDEX = 0xFFFFFFFF }; public: KG3DFontRenderer(); ~KG3DFontRenderer(); HRESULT Initialize(LPDIRECT3DDEVICE9 pD3DDevice); HRESULT CleanUp(); HRESULT OnLostDevice(); HRESULT OnResetDevice(); HRESULT Prepare(); HRESULT Flush(); BOOL BuildTexture(UINT& uIndex, UINT& uWidth, UINT& uHeight, UINT uGlyphWidth, UINT uGlyphHeight, UINT uMipmapLevel); void DeleteTexture(UINT uIndex); BOOL UploadTexture(UINT uIndex, UINT uLevel, UINT uX, UINT uY, UINT uWidth, UINT uHeight, BYTE const* pUpload, UCHAR *puchAdjust); BOOL UploadMonoTexture(UINT uIndex, UINT uLevel, UINT uX, UINT uY, UINT uWidth, UINT uHeight, UINT uUploadPitch, BYTE const* pUpload); BOOL UploadBoderTexture(UINT uIndex, UINT uLevel, UINT uX, UINT uY, UINT uWidth, UINT uHeight, BYTE const* pUpload, UCHAR *puchAdjust); BOOL UploadMonoBoderTexture(UINT uIndex, UINT uLevel, UINT uX, UINT uY, UINT uWidth, UINT uHeight, UINT uUploadPitch, BYTE const* pUpload); HRESULT PrepareVertex(UINT uIndex, KG3DFontTLVertex* pVertex, UINT uVertex); protected: HRESULT CheckD3DTextureCaps(LPDIRECT3DDEVICE9 pD3DDevice); HRESULT CheckD3DTextureFormat(LPDIRECT3DDEVICE9 pD3DDevice); HRESULT FlushTexture(UINT uIndex); HRESULT FlushTLVertex(); private: size_t GetTexturePixelByte() const; HRESULT CreateFontIndexBuffer(); HRESULT DestroyFontIndexBuffer(); HRESULT CreateFontVertexBuffer(); HRESULT DestroyFontVertexBuffer(); protected: LPDIRECT3DDEVICE9 m_pD3DDevice; LPDIRECT3DINDEXBUFFER9 m_pFontIndexBuffer; KTextureArray m_aTexture; D3DFORMAT m_TextureFormat; UINT m_TextureFmtSkip; KRenderBatch m_RenderBatch[MAX_RENDER_BATCH]; KRenderBatch* m_pRenderBatch; UINT m_uFlushTextureIndex; }; #endif //_INCLUDE_KG3DFONTRENDERER_H_
[ "dark.hades.1102@GAMIL.COM" ]
dark.hades.1102@GAMIL.COM
98a06d12c3563d6901c2e52a51ec80b1ac2d100c
0b19358e4db6915003ee0190be580ee76d50977e
/Less Than Dungeon 0.3.1/begin_chapter_2.cpp
a92bf3e0fbf47e8b76fc5c38c577dec725b2298b
[]
no_license
DedushkaGnom/Less_Than_Dungeon_0.3.1
0507e34f999201d8991a7f3d78b725f7958674a8
9a1eb3c897787f300c1e179a999495d1e53263d6
refs/heads/master
2022-09-26T03:42:39.725959
2020-06-02T22:36:34
2020-06-02T22:36:34
268,896,889
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
8,382
cpp
#include "Header_game.h" void ammunition_check(MyHero& Hero); void items_check(MyHero& Hero); const unsigned int MAP_SIZE_X = 20; const unsigned int MAP_SIZE_Y = 20; const unsigned int START_POSITION_X = 10; const unsigned int START_POSITION_Y = 13; inline void location(int loc) { switch (loc) { case 80: cout << "Портал" << endl; break; case 84: cout << "Город" << endl; break; case 86: cout << "Деревня" << endl; break; case 77: cout << "Горы" << endl; break; case 70: cout << "Лес" << endl; break; case 82: cout << "Дорога" << endl; break; case 66: cout << "Мост" << endl; break; case 114: cout << "Река" << endl; break; case 67: cout << "Лагерь" << endl; break; case 83: cout << "Море" << endl; break; case 75: cout << "Лагерь" << endl; break; case 102: cout << "Поле" << endl; break; case 72: cout << "Нагорье" << endl; break; case 87: cout << "Пустошь" << endl; break; case 115: cout << "Болото" << endl; break; case 119: cout << "Городская стена" << endl; break; case 103: cout << "Городские ворота" << endl; break; default: cout << "Неизвестное место!" << endl; } } void Begin_chapter_2() { system("cls"); string choice_str; //Для письменных выборов int choice; //Для числовых выборов //Создание героя (ДОРАБОТКА) cout << "Введите имя героя: "; cin >> choice_str; cout << choice_str; _getch(); MyHero Hero(choice_str, START_POSITION_X, START_POSITION_Y); while (1) { system("cls"); cout << "Выберите класс героя: " << endl; cout << "1)Странник " << endl; cout << "2)Воин " << endl; cout << "3)Берсерк " << endl; cout << "4)Вор " << endl; cout << "5)Дворянин " << endl; cout << "6)Нищий " << endl; cout << "Выбор: "; cin >> choice; if ((choice > 6) or (choice < 1)) { cout << "Может всё-таки сделаете выбор?" << endl; _getch(); continue; } Hero.Class_choice(choice); break; } Hero.refresh(); MyWeapon weapon1("Меч", 1, 10, 2, 5, 5, 20); MyWeapon weapon2("Секира", 2, 25, 5,-10,-10, 15); Hero.item[0].create_item(weapon1); Hero.item[1].create_item(weapon2); //Загрузка карты char map_terrain[MAP_SIZE_X][MAP_SIZE_Y]; int map_event[MAP_SIZE_X][MAP_SIZE_Y]; string map_event_file_path = "map_event.txt"; string map_terrain_file_path = "map_terrain.txt"; ifstream map_terrain_out; ifstream map_event_out; map_terrain_out.open(map_terrain_file_path); map_event_out.open(map_event_file_path); if (!map_terrain_out.is_open()) { cout << "Error map_terrain opening!" << endl; } if (!map_event_out.is_open()) { cout << "Error map_event opening!" << endl; } for (int i = 0; i < MAP_SIZE_Y; i++) { for (int j = 0; j < MAP_SIZE_Y; j++) { map_terrain_out >> map_terrain[j][i]; map_event_out >> map_event[j][i]; cout << map_terrain[j][i] << " "; } cout << endl; } _getch(); map_terrain_out.close(); map_event_out.close(); //Основная часть while (true) { if (Hero.HP < 0) { cout << "Погибель настигла вас, вы ушли во тьму..." << endl; system("pause"); break; } while (true) { system("cls"); switch (static_cast<int>(map_terrain[Hero.position_x][Hero.position_y])) { case 80: cout << "Вы находитесь вблизи Портала." << endl; break; case 84: cout << "Вы находитесь в городе." << endl; break; case 86: cout << "Вы находитесь в деревне." << endl; break; case 70: cout << "Вы находитесь в лесу." << endl; break; case 82: cout << "Вы находитесь на дороге." << endl; break; case 66: cout << "Вы находитесь на мосту." << endl; break; case 114: cout << "Вы находитесь в реке." << endl; break; case 67: cout << "Вы находитесь в лагере." << endl; break; case 102: cout << "Вы находитесь в открытом поле." << endl; break; case 87: cout << "Вы находитесь в пустынном гиблом месте." << endl; break; case 72: cout << "Вы находитесь в скалистом нагорье." << endl; break; case 115: cout << "Вы находитесь среди болотных топей." << endl; break; default: cout << "Вы находитесь в неизвестном месте." << endl; } cout << endl; cout << "Север: "; location(static_cast<int>(map_terrain[Hero.position_x][Hero.position_y - 1])); cout << "Воcток: "; location(static_cast<int>(map_terrain[Hero.position_x + 1][Hero.position_y])); cout << "Запад: "; location(static_cast<int>(map_terrain[Hero.position_x - 1][Hero.position_y])); cout << "Юг: "; location(static_cast<int>(map_terrain[Hero.position_x][Hero.position_y + 1])); cout << endl; cout << Hero.name << ": Что теперь?" << endl << endl; cout << "1)Движение" << endl; cout << "2)Осмотреться" <<endl; cout << "3)Действия" << endl; cout << "4)Инвентарь" << endl; cout << "5)Экипировка" << endl; cout << "6)Информация о герое" << endl; cout << "0)Сдаться" << endl; cout << Hero.name << ": "; cin >> choice; switch (choice) { //Движение case 1: { while (true) { system("cls"); cout << Hero.name << ": В каком направлении?" << endl << endl; cout << "1)Север: "; location(static_cast<int>(map_terrain[Hero.position_x][Hero.position_y - 1])); cout << "2)Восток: "; location(static_cast<int>(map_terrain[Hero.position_x + 1][Hero.position_y])); cout << "3)Запад: "; location(static_cast<int>(map_terrain[Hero.position_x - 1][Hero.position_y])); cout << "4)Юг: "; location(static_cast<int>(map_terrain[Hero.position_x][Hero.position_y + 1])); cout << "0)Отмена" << endl; cout << Hero.name << ": "; cin >> choice; int path_location=0; switch(choice) { case 1: path_location = static_cast<int>(map_terrain[Hero.position_x][Hero.position_y - 1]); break; case 2: path_location = static_cast<int>(map_terrain[Hero.position_x + 1][Hero.position_y]); break; case 3: path_location = static_cast<int>(map_terrain[Hero.position_x - 1][Hero.position_y]); break; case 4: path_location = static_cast<int>(map_terrain[Hero.position_x][Hero.position_y + 1]); break; } switch (path_location) { case 77: cout << Hero.name << ": Через эти горы мне не перебраться." << endl; _getch(); continue; case 83: cout << Hero.name << ": С такими волнами я и на 10 метров от берега не отплыву!" << endl; _getch(); continue; case 114:cout << Hero.name << ": В реку лезть не стоит, течение очень быстрое." << endl; _getch(); continue; default: switch (choice) { case 0: break; case 1: Hero.position_y -= 1; break; case 2: Hero.position_x += 1; break; case 3: Hero.position_x -= 1; break; case 4: Hero.position_y += 1; break; default: cout << Hero.name << "Завёт дорога нас вперёд, в заманчивую даль..." << endl; _getch(); continue; } } break; } break; } //Осмотреться case 2: { break; } //Действия в данном месте case 3: { break; } //Просмотр и настройка аммуниции case 4: { items_check(Hero); break; } case 5: { ammunition_check(Hero); break; } case 6: { break; } default: { cout << Hero.name << "Надо бы уже что-то решить." << endl; _getch(); continue; } } break; } } system("pause"); }
[ "dimon.tuleninov@mail.ru" ]
dimon.tuleninov@mail.ru
c3b2f68d75aa38b8c0e30eaa0c9484e64f683b12
359df09204255c068816d102b97290ff039f0714
/app/src/main/cpp/nativelib/Daughter.cpp
147a996159f349e3d18f843e59e0b3da4b1c527d
[ "Apache-2.0" ]
permissive
coolxinxin/NDKStudy
bd00d1bc0c944fc98100dccc32a92aa60c72caf1
456085da1cba9b1bf4cab6b9aaa175b8fa291d03
refs/heads/master
2023-01-22T15:29:53.679899
2020-12-04T03:28:39
2020-12-04T03:28:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
393
cpp
// // // //@author : Leo //@date : 2020/10/12 18:45 //@since : lightingxin@qq.com //@desc : // // #include "Daughter.h" #include <iostream> using namespace std; void Daughter::eat() { LOGI("%s","女儿喜欢吃蛋糕") cout << "女儿喜欢吃蛋糕" << endl; } void Daughter::running() { LOGI("%s","女儿喜欢打羽毛球") cout << "女儿喜欢打羽毛球" << endl; }
[ "xinxiniscool@gmail.com" ]
xinxiniscool@gmail.com
4aad37e550d9e87213f9ac976c41fb3ff2c07706
c365d25ee2237b3c260198827b33b0253d43eaf4
/spoj/rpln.cpp
33b6abab4d1dc7532e9e9f0ebe5fefa40ab79f3b
[]
no_license
germanohn/competitive-programming
fb1249910ce951fe290e9a5be3876d3870ab8aa3
fab9dc0e2998dd395c1b9d6639f8c187cf637669
refs/heads/master
2021-06-12T08:17:52.907705
2021-03-17T19:06:19
2021-03-17T19:06:19
58,595,999
0
0
null
null
null
null
UTF-8
C++
false
false
1,037
cpp
#include <bits/stdc++.h> using namespace std; int seg[400005]; void update (int l, int r, int n, int val, int ind) { if (ind < l || ind > r) return; if (l == r) { seg[n] = val; return; } int m = (l+r)/2; update (l, m, 2*n, val, ind); update (m+1, r, 2*n + 1, val, ind); seg[n] = min (seg[2*n], seg[2*n + 1]); } int query (int l, int r, int a, int b, int n) { if (l >= a && r <= b) return seg[n]; if (l > b || r < a) return INT_MAX; int m = (l+r)/2; return min (query (l, m, a, b, 2*n), query (m+1, r, a, b, 2*n + 1)); } int main () { int t, n, q; scanf ("%d", &t); int cont = 1; while (t--) { printf ("Scenario #%d:\n\n", cont++); int a, b; scanf ("%d %d", &n, &q); for (int i = 0; i < n; i++) { scanf ("%d", &a); update (0, n-1, 1, a, i); } for (int i = 0; i < q; i++) { scanf ("%d %d", &a, &b); printf ("%d\n", query (0, n-1, a-1, b-1, 1)); } } }
[ "germanohn@hotmail.com" ]
germanohn@hotmail.com
ed61edbffb2bb707b8b16e9bf9b4d8c85c469575
4a4a283792fecb2e9dcbd5a256c6aec203a53ba7
/R-package/src/scave/indexedvectorfilereader.cc
ef0da65a0fb8b1aba23dfd9ca0ac74a009df7a79
[ "BSD-2-Clause" ]
permissive
mbyrenh/omnetpp-resultfiles
31c7cb6d2ccf1fffb792c28c018e6c1fa86be278
f61decaa60569367e2656f19b4256c7817d94c93
refs/heads/master
2021-11-09T03:48:51.234736
2021-10-30T16:58:36
2021-10-30T16:58:36
237,259,258
0
0
null
2020-01-30T16:51:47
2020-01-30T16:51:46
null
UTF-8
C++
false
false
6,933
cc
/* * Copyright (c) 2010, Andras Varga and Opensim Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Opensim Ltd. 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 Andras Varga or Opensim Ltd. 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 <algorithm> #include "platmisc.h" #include "opp_ctype.h" #include "channel.h" #include "scaveutils.h" #include "vectorfilereader.h" #include "indexedvectorfilereader.h" USING_NAMESPACE using namespace std; #define LL INT64_PRINTF_FORMAT IndexedVectorFileReaderNode::IndexedVectorFileReaderNode(const char *filename, size_t bufferSize) : ReaderNode(filename, bufferSize), index(NULL), currentBlockIndex(0) { } IndexedVectorFileReaderNode::~IndexedVectorFileReaderNode() { if (index) { delete index; index = NULL; } } Port *IndexedVectorFileReaderNode::addVector(const VectorResult &vector) { PortData& portdata = ports[vector.vectorId]; portdata.ports.push_back(Port(this)); Port& port = portdata.ports.back(); return &port; } bool IndexedVectorFileReaderNode::isReady() const { return true; } void IndexedVectorFileReaderNode::process() { if (!index) readIndexFile(); long bytesRead = 0; while (currentBlockIndex < blocksToRead.size() && bytesRead < 64 * 1024) { BlockAndPortData &blockAndPort = blocksToRead[currentBlockIndex++]; bytesRead += readBlock(blockAndPort.blockPtr, blockAndPort.portDataPtr); } } bool IndexedVectorFileReaderNode::isFinished() const { return index && currentBlockIndex >= blocksToRead.size(); } void IndexedVectorFileReaderNode::readIndexFile() { const char *fn = filename.c_str(); if (!IndexFile::isVectorFile(fn)) throw opp_runtime_error("indexed vector file reader: not a vector file, file %s", fn); string indexFileName = IndexFile::getIndexFileName(fn); IndexFileReader reader(indexFileName.c_str()); index = reader.readAll(); for (VectorIdToPortMap::iterator it = ports.begin(); it != ports.end(); ++it) { int vectorId = it->first; PortData &portData = it->second; portData.vector = index->getVectorById(vectorId); if (!portData.vector) throw opp_runtime_error("indexed vector file reader: vector %d not found, file %s", vectorId, indexFileName.c_str()); Blocks &blocks = portData.vector->blocks; for (Blocks::iterator it = blocks.begin(); it != blocks.end(); ++it) blocksToRead.push_back(BlockAndPortData(&(*it), &portData)); } sort(blocksToRead.begin(), blocksToRead.end()); } long IndexedVectorFileReaderNode::readBlock(const Block *blockPtr, const PortData *portDataPtr) { assert(blockPtr); assert(portDataPtr->vector); const char *file = filename.c_str(); file_offset_t offset; #define CHECK(cond, msg) {if (!cond) throw opp_runtime_error(msg ", file %s, offset %"LL"d", file, (int64)offset); } VectorData *vector = portDataPtr->vector; file_offset_t startOffset = blockPtr->startOffset; long count = blockPtr->getCount(); reader.seekTo(startOffset); long readTime=0; long tokenizeTime = 0; long parseTime = 0; // printf("readBlock "); char *line; for (long k = 0; k < count /*&& (line=reader.getNextLineBufferPointer())!=NULL*/; ++k) { TIME(readTime,line=reader.getNextLineBufferPointer()); if (!line) break; offset = reader.getCurrentLineStartOffset(); int length = reader.getCurrentLineLength(); TIME(tokenizeTime, tokenizer.tokenize(line, length)); int numtokens = tokenizer.numTokens(); char **vec = tokenizer.tokens(); int vectorId; // check vector id CHECK((numtokens >= 3) && opp_isdigit(vec[0][0]), "vector file reader: data line too short"); CHECK(parseInt(vec[0], vectorId), "invalid vector file syntax: invalid vector id column"); CHECK(vectorId == vector->vectorId, "vector file reader: unexpected vector id"); // parse columns Datum a; TIME(parseTime, a = parseColumns(vec, numtokens, vector->columns, file, -1, offset)); // write to port(s) for (PortVector::const_iterator port = portDataPtr->ports.begin(); port != portDataPtr->ports.end(); ++port) port->getChannel()->write(&a,1); } // printf("read: %ldms tokenize: %ldms parse: %ldms\n", // readTime/1000, tokenizeTime/1000, parseTime/1000); return blockPtr->size; } //----- const char *IndexedVectorFileReaderNodeType::getDescription() const { return "Reads indexed output vector files."; } void IndexedVectorFileReaderNodeType::getAttributes(StringMap& attrs) const { attrs["filename"] = "name of the output vector file (.vec)"; } Node *IndexedVectorFileReaderNodeType::create(DataflowManager *mgr, StringMap& attrs) const { checkAttrNames(attrs); const char *fname = attrs["filename"].c_str(); Node *node = new IndexedVectorFileReaderNode(fname); node->setNodeType(this); mgr->addNode(node); return node; } Port *IndexedVectorFileReaderNodeType::getPort(Node *node, const char *portname) const { // vector id is used as port name IndexedVectorFileReaderNode *node1 = dynamic_cast<IndexedVectorFileReaderNode *>(node); VectorResult vector; if (!parseInt(portname, vector.vectorId)) throw opp_runtime_error("indexed file reader node: port should be a vector id, received: %s", portname); return node1->addVector(vector); }
[ "andras@omnetpp.org" ]
andras@omnetpp.org
abb1e41062ae05023e6521ed54204641ec9b5a2a
20e12970672f035bac446576a037633a01fc8536
/homework3/code+scripts+makefiles/basic_cannons_algorithm_question_1_and_2/my_first_mpi.cpp
a8e9029622873f5b98d26bb9b773801a2f9ad19f
[]
no_license
aashray/parallel
56c5eeb7faa4c6dd37f55b5fd18ae1b32adb892f
fce8ea63ace14f6f23fbd3bf7bee6c766858ae32
refs/heads/master
2020-05-20T06:06:13.215615
2015-07-12T20:48:35
2015-07-12T20:48:35
32,417,280
0
2
null
null
null
null
UTF-8
C++
false
false
279
cpp
#include<stdio.h> #include<mpi.h> int main(int argc, char *argv[]) { int p, myrank; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &p); MPI_Comm_rank(MPI_COMM_WORLD, &myrank); printf("This is process %d out of process %d\n", p, myrank); MPI_Finalize(); return 0; }
[ "aashray.arora@stonybrook.edu" ]
aashray.arora@stonybrook.edu
a04764fd54d4de7e724ad2af1c8d03031522aba6
cda7f9857e57ff1d8fb981ac2a45a654a758fd64
/sender/sender.ino
d6740bde4762e58cae7343fa5db6a855be43ba8b
[]
no_license
RuslanIvanov/arduino
b57d1c78c708082b560e54c3dc30ecc87cacb869
818b453aab649d0e2bdc87ddef225af8770cf128
refs/heads/main
2023-03-31T19:46:03.265803
2021-03-19T03:53:21
2021-03-19T03:53:21
349,314,880
0
0
null
null
null
null
UTF-8
C++
false
false
954
ino
//Это код передатчика. #include <VirtualWire.h> const int led_pin = 13; const int transmit_pin = 12; const int receive_pin = 2; const int transmit_en_pin = 3; void setup() { // Initialise the IO and ISR vw_set_tx_pin(transmit_pin); vw_set_rx_pin(receive_pin); vw_set_ptt_pin(transmit_en_pin); vw_set_ptt_inverted(true); // Required for DR3100 vw_setup(2000); // Bits per sec pinMode(led_pin, OUTPUT); Serial.println("setup"); } byte count = 1; void loop() { char msg[7] = {'h','e','l','l','o',' ','#'}; Serial.println("loop.."); msg[6] = count; digitalWrite(led_pin, HIGH); // Flash a light to show transmitting vw_send((uint8_t *)msg, 7); vw_wait_tx(); // Wait until the whole message is gone digitalWrite(led_pin, LOW); int i; for (i = 0; i < 7; i++) { Serial.print(msg[i], HEX); Serial.print(' '); } Serial.println(); delay(1000); count = count + 1; }
[ "wert@.(none)" ]
wert@.(none)
d0e17e921d4d4ee4f887436dc5ef1e8b1aedfbe2
cff194b002d51cb716bb8a8fb4e4f05887e8258a
/1. Dynamic Programming/q6.cpp
1326a7392c6b1acb70548b12e8f15744706edc7c
[]
no_license
akjha992/Algorithms_topic_wise
1f75df76565e1586f1ab59b8ece1b5cf45d023e5
2a267252fb4992fb78b86175363c36200a20095b
refs/heads/master
2021-05-06T05:31:34.764400
2018-04-10T12:21:29
2018-04-10T12:21:29
115,091,236
0
0
null
null
null
null
UTF-8
C++
false
false
1,137
cpp
#include <iostream> #include <vector> using namespace std; int ins=1; int coin_change(vector<int> coin,int note,vector<vector<int> > &dp) { //cout<<"ins "<<ins++<<endl; if(note==0){ //cout<<"h1"; dp[note][coin.size()]=1; return 1; } if(coin.size()==0) { //cout<<"x:"<<note<<endl; dp[note][coin.size()]=0; //cout<<dp[note][0]<<endl; return 0; } if(dp[note][coin.size()]!=-1) { //cout<<"h4"; return dp[note][coin.size()]; } else { //cout<<"h3"; int val=0; if(note-coin[coin.size()-1]>=0) val = coin_change(coin,note-coin[coin.size()-1],dp); coin.pop_back(); val+=coin_change(coin,note,dp); dp[note][coin.size()+1]=val; //cout<<"yo"; return val; } } int main() { int tc; cin>>tc; while(tc--) { int n; cin>>n; vector<int> coin(n); for(int i=0;i<n;i++) { cin>>coin[i]; } int note; cin>>note; vector<vector<int> > dp(note+1,vector<int>(n+1,-1)); cout<<coin_change(coin,note,dp)<<endl; //cout<<coin.size()<<" "<<note<<endl; // for(int i=0;i<=note;i++) // { // for(int j=0;j<=n;j++) // { // cout<<dp[i][j]<<" "; // } // cout<<endl; // } } }
[ "akjha992@gmail.com" ]
akjha992@gmail.com
57d14638567fa3748b60e3e81fb107474ca8fc1c
6e5f69f4af5c1baa22c01655aaa7b62cf6708f1e
/lib/FirebaseESP8266/src/FirebaseESP8266.h
ddede2b4bd2ebf76c5201c636bfa6312c70f2be9
[ "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
N0urM/BoatLoader-OTA-Update
8342d66e25f619519d64ff07c46c30cab8674e9a
124deb170dbb547e8d920172ce4026f7759220b4
refs/heads/master
2023-02-18T11:06:47.750090
2021-01-24T22:59:50
2021-01-24T22:59:50
332,496,033
1
0
null
null
null
null
UTF-8
C++
false
false
117,682
h
/* * Google's Firebase Realtime Database Arduino Library for ESP8266, version 2.9.8 * * October 13, 2020 * * Updates: * - FirebaseJson bugs fixed * * * This library provides ESP8266 to perform REST API by GET PUT, POST, PATCH, DELETE data from/to with Google's Firebase database using get, set, update * and delete calls. * * The library was tested and work well with ESP8266 based module and add support for multiple stream event paths. * * The MIT License (MIT) * Copyright (c) 2019 K. Suwatchai (Mobizt) * * * Permission is hereby granted, free of charge, to any person returning 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. */ #ifndef FirebaseESP8266_H #define FirebaseESP8266_H #ifdef ESP8266 #include <Arduino.h> #include <SPI.h> #include <time.h> #include <SD.h> #include <vector> #include <functional> #include <Schedule.h> #include <ets_sys.h> #include <ESP8266WiFi.h> #include "FirebaseESP8266HTTPClient.h" #define FS_NO_GLOBALS #include <FS.h> #include "FirebaseJson.h" #define FIREBASE_PORT 443 #define KEEP_ALIVE_TIMEOUT 45000 #define STREAM_ERROR_NOTIFIED_INTERVAL 3000 #define STREAM_RECONNECT_INTERVAL 1000 #define SD_CS_PIN 15 #define MAX_REDIRECT 5 #define WIFI_RECONNECT_TIMEOUT 10000 #define STEAM_STACK_SIZE 8192 #define QUEUE_TASK_STACK_SIZE 8192 #define MAX_BLOB_PAYLOAD_SIZE 1024 struct StorageType { static const uint8_t FLASH = 0; static const uint8_t SD = 1; }; enum fb_esp_fcm_msg_type { msg_single, msg_multicast, msg_topic }; enum fb_esp_data_type { d_any, d_null, d_integer, d_float, d_double, d_boolean, d_string, d_json, d_array, d_blob, d_file, d_timestamp, d_shallow, }; enum fb_esp_method { m_put, m_put_nocontent, m_post, m_get, m_get_nocontent, m_stream, m_patch, m_patch_nocontent, m_delete, m_download, m_restore, m_read_rules, m_set_rules, m_get_shallow, m_get_priority, m_set_priority, }; struct server_response_data_t { int httpCode = -1; int payloadLen = -1; int contentLen = -1; fb_esp_data_type dataType = fb_esp_data_type::d_any; int payloadOfs = 0; bool boolData = false; int intData = 0; float floatData = 0.0f; double doubleData = 0.0f; std::vector<uint8_t> blobData; bool isEvent = false; bool noEvent = false; bool isChunkedEnc = false; bool hasEventData = false; bool noContent = false; bool eventPathChanged = false; bool dataChanged = false; std::string location = ""; std::string contentType = ""; std::string connection = ""; std::string eventPath = ""; std::string eventType = ""; std::string eventData = ""; std::string etag = ""; std::string pushName = ""; std::string fbError = ""; std::string transferEnc = ""; }; static const char fb_esp_pgm_str_1[] PROGMEM = "/"; static const char fb_esp_pgm_str_2[] PROGMEM = ".json?auth="; static const char fb_esp_pgm_str_3[] PROGMEM = "\""; static const char fb_esp_pgm_str_4[] PROGMEM = "."; static const char fb_esp_pgm_str_5[] PROGMEM = "HTTP/1.1 "; static const char fb_esp_pgm_str_6[] PROGMEM = " "; static const char fb_esp_pgm_str_7[] PROGMEM = ":"; static const char fb_esp_pgm_str_8[] PROGMEM = "Content-Type: "; static const char fb_esp_pgm_str_9[] PROGMEM = "text/event-stream"; static const char fb_esp_pgm_str_10[] PROGMEM = "Connection: "; static const char fb_esp_pgm_str_11[] PROGMEM = "keep-alive"; static const char fb_esp_pgm_str_12[] PROGMEM = "Content-Length: "; static const char fb_esp_pgm_str_13[] PROGMEM = "event: "; static const char fb_esp_pgm_str_14[] PROGMEM = "data: "; static const char fb_esp_pgm_str_15[] PROGMEM = "put"; static const char fb_esp_pgm_str_16[] PROGMEM = "patch"; static const char fb_esp_pgm_str_17[] PROGMEM = "\"path\":\""; static const char fb_esp_pgm_str_18[] PROGMEM = "\"data\":"; static const char fb_esp_pgm_str_19[] PROGMEM = "null"; static const char fb_esp_pgm_str_20[] PROGMEM = "{\"name\":\""; static const char fb_esp_pgm_str_21[] PROGMEM = "\r\n"; static const char fb_esp_pgm_str_22[] PROGMEM = "GET "; static const char fb_esp_pgm_str_23[] PROGMEM = "PUT"; static const char fb_esp_pgm_str_24[] PROGMEM = "POST"; static const char fb_esp_pgm_str_25[] PROGMEM = "GET"; static const char fb_esp_pgm_str_26[] PROGMEM = "PATCH"; static const char fb_esp_pgm_str_27[] PROGMEM = "DELETE"; static const char fb_esp_pgm_str_28[] PROGMEM = "&download="; static const char fb_esp_pgm_str_29[] PROGMEM = "&print=silent"; static const char fb_esp_pgm_str_30[] PROGMEM = " HTTP/1.1\r\n"; static const char fb_esp_pgm_str_31[] PROGMEM = "Host: "; static const char fb_esp_pgm_str_32[] PROGMEM = "User-Agent: ESP\r\n"; static const char fb_esp_pgm_str_33[] PROGMEM = "X-Firebase-Decoding: 1\r\n"; static const char fb_esp_pgm_str_34[] PROGMEM = "Connection: close\r\n"; static const char fb_esp_pgm_str_35[] PROGMEM = "Accept: text/event-stream\r\n"; static const char fb_esp_pgm_str_36[] PROGMEM = "Connection: keep-alive\r\n"; static const char fb_esp_pgm_str_37[] PROGMEM = "Keep-Alive: timeout=30, max=100\r\n"; static const char fb_esp_pgm_str_38[] PROGMEM = "Accept-Encoding: identity;q=1,chunked;q=0.1,*;q=0\r\n"; static const char fb_esp_pgm_str_39[] PROGMEM = "connection refused"; static const char fb_esp_pgm_str_40[] PROGMEM = "send header failed"; static const char fb_esp_pgm_str_41[] PROGMEM = "send payload failed"; static const char fb_esp_pgm_str_42[] PROGMEM = "not connected"; static const char fb_esp_pgm_str_43[] PROGMEM = "connection lost"; static const char fb_esp_pgm_str_44[] PROGMEM = "no HTTP server"; static const char fb_esp_pgm_str_45[] PROGMEM = "bad request, verify the Firebase credentials and the node path"; static const char fb_esp_pgm_str_46[] PROGMEM = "non-authoriative information"; static const char fb_esp_pgm_str_47[] PROGMEM = "no content"; static const char fb_esp_pgm_str_48[] PROGMEM = "moved permanently"; static const char fb_esp_pgm_str_49[] PROGMEM = "use proxy"; static const char fb_esp_pgm_str_50[] PROGMEM = "temporary redirect"; static const char fb_esp_pgm_str_51[] PROGMEM = "permanent redirect"; static const char fb_esp_pgm_str_52[] PROGMEM = "unauthorized"; static const char fb_esp_pgm_str_53[] PROGMEM = "forbidden"; static const char fb_esp_pgm_str_54[] PROGMEM = "not found"; static const char fb_esp_pgm_str_55[] PROGMEM = "method not allow"; static const char fb_esp_pgm_str_56[] PROGMEM = "not acceptable"; static const char fb_esp_pgm_str_57[] PROGMEM = "proxy authentication required"; static const char fb_esp_pgm_str_58[] PROGMEM = "request timeout"; static const char fb_esp_pgm_str_59[] PROGMEM = "length required"; static const char fb_esp_pgm_str_60[] PROGMEM = "too many requests"; static const char fb_esp_pgm_str_61[] PROGMEM = "request header fields too larg"; static const char fb_esp_pgm_str_62[] PROGMEM = "internal server error"; static const char fb_esp_pgm_str_63[] PROGMEM = "bad gateway"; static const char fb_esp_pgm_str_64[] PROGMEM = "service unavailable"; static const char fb_esp_pgm_str_65[] PROGMEM = "gateway timeout"; static const char fb_esp_pgm_str_66[] PROGMEM = "http version not support"; static const char fb_esp_pgm_str_67[] PROGMEM = "network authentication required"; static const char fb_esp_pgm_str_68[] PROGMEM = "data buffer overflow"; static const char fb_esp_pgm_str_69[] PROGMEM = "read Timeout"; static const char fb_esp_pgm_str_70[] PROGMEM = "data type mismatch"; static const char fb_esp_pgm_str_71[] PROGMEM = "path not exist"; static const char fb_esp_pgm_str_72[] PROGMEM = "task"; static const char fb_esp_pgm_str_73[] PROGMEM = "/esp.x"; static const char fb_esp_pgm_str_74[] PROGMEM = "json"; static const char fb_esp_pgm_str_75[] PROGMEM = "string"; static const char fb_esp_pgm_str_76[] PROGMEM = "float"; static const char fb_esp_pgm_str_77[] PROGMEM = "int"; static const char fb_esp_pgm_str_78[] PROGMEM = "null"; static const char fb_esp_pgm_str_79[] PROGMEM = ";"; static const char fb_esp_pgm_str_80[] PROGMEM = "Content-Disposition: "; static const char fb_esp_pgm_str_81[] PROGMEM = "application/octet-stream"; static const char fb_esp_pgm_str_82[] PROGMEM = "attachment"; static const char fb_esp_pgm_str_83[] PROGMEM = "The backup file is not exist"; static const char fb_esp_pgm_str_84[] PROGMEM = "The SD card is in use"; static const char fb_esp_pgm_str_85[] PROGMEM = "The SD card is not available"; static const char fb_esp_pgm_str_86[] PROGMEM = "Could not read/write the backup file"; static const char fb_esp_pgm_str_87[] PROGMEM = "Transmission error, "; static const char fb_esp_pgm_str_88[] PROGMEM = "Node path is not exist"; static const char fb_esp_pgm_str_89[] PROGMEM = ".json"; static const char fb_esp_pgm_str_90[] PROGMEM = "/root.json"; static const char fb_esp_pgm_str_91[] PROGMEM = "blob"; static const char fb_esp_pgm_str_92[] PROGMEM = "\"blob,base64,"; static const char fb_esp_pgm_str_93[] PROGMEM = "\"file,base64,"; static const char fb_esp_pgm_str_94[] PROGMEM = "http connection was used by other processes"; static const char fb_esp_pgm_str_95[] PROGMEM = "Location: "; static const char fb_esp_pgm_str_96[] PROGMEM = "&orderBy="; static const char fb_esp_pgm_str_97[] PROGMEM = "&limitToFirst="; static const char fb_esp_pgm_str_98[] PROGMEM = "&limitToLast="; static const char fb_esp_pgm_str_99[] PROGMEM = "&startAt="; static const char fb_esp_pgm_str_100[] PROGMEM = "&endAt="; static const char fb_esp_pgm_str_101[] PROGMEM = "&equalTo="; static const char fb_esp_pgm_str_102[] PROGMEM = "\"error\" : "; static const char fb_esp_pgm_str_103[] PROGMEM = "/.settings/rules"; static const char fb_esp_pgm_str_104[] PROGMEM = "{\"status\":\"ok\"}"; static const char fb_esp_pgm_str_105[] PROGMEM = "boolean"; static const char fb_esp_pgm_str_106[] PROGMEM = "false"; static const char fb_esp_pgm_str_107[] PROGMEM = "true"; static const char fb_esp_pgm_str_108[] PROGMEM = "double"; static const char fb_esp_pgm_str_109[] PROGMEM = "cancel"; static const char fb_esp_pgm_str_110[] PROGMEM = "auth_revoked"; static const char fb_esp_pgm_str_111[] PROGMEM = "http://"; static const char fb_esp_pgm_str_112[] PROGMEM = "https://"; static const char fb_esp_pgm_str_113[] PROGMEM = "_stream"; static const char fb_esp_pgm_str_114[] PROGMEM = "_error_queue"; static const char fb_esp_pgm_str_115[] PROGMEM = "get"; static const char fb_esp_pgm_str_116[] PROGMEM = "set"; static const char fb_esp_pgm_str_117[] PROGMEM = "push"; static const char fb_esp_pgm_str_118[] PROGMEM = "update"; static const char fb_esp_pgm_str_119[] PROGMEM = "delete"; static const char fb_esp_pgm_str_120[] PROGMEM = "fcm.googleapis.com"; static const char fb_esp_pgm_str_121[] PROGMEM = "/fcm/send"; static const char fb_esp_pgm_str_122[] PROGMEM = "\"notification\":{"; static const char fb_esp_pgm_str_123[] PROGMEM = "\"title\":\""; static const char fb_esp_pgm_str_124[] PROGMEM = "\"body\":\""; static const char fb_esp_pgm_str_125[] PROGMEM = "\"icon\":\""; static const char fb_esp_pgm_str_126[] PROGMEM = "\"click_action\":\""; static const char fb_esp_pgm_str_127[] PROGMEM = "}"; static const char fb_esp_pgm_str_128[] PROGMEM = "\"to\":\""; static const char fb_esp_pgm_str_129[] PROGMEM = "application/json"; static const char fb_esp_pgm_str_130[] PROGMEM = "\"registration_ids\":["; static const char fb_esp_pgm_str_131[] PROGMEM = "Authorization: key="; static const char fb_esp_pgm_str_132[] PROGMEM = ","; static const char fb_esp_pgm_str_133[] PROGMEM = "]"; static const char fb_esp_pgm_str_134[] PROGMEM = "/topics/"; static const char fb_esp_pgm_str_135[] PROGMEM = "\"data\":"; static const char fb_esp_pgm_str_136[] PROGMEM = "\"priority\":\""; static const char fb_esp_pgm_str_137[] PROGMEM = "\"time_to_live\":"; static const char fb_esp_pgm_str_138[] PROGMEM = "\"collapse_key\":\""; static const char fb_esp_pgm_str_139[] PROGMEM = "\"multicast_id\":"; static const char fb_esp_pgm_str_140[] PROGMEM = "\"success\":"; static const char fb_esp_pgm_str_141[] PROGMEM = "\"failure\":"; static const char fb_esp_pgm_str_142[] PROGMEM = "\"canonical_ids\":"; static const char fb_esp_pgm_str_143[] PROGMEM = "\"results\":"; static const char fb_esp_pgm_str_144[] PROGMEM = "No topic provided"; static const char fb_esp_pgm_str_145[] PROGMEM = "No device token provided"; static const char fb_esp_pgm_str_146[] PROGMEM = "No server key provided"; static const char fb_esp_pgm_str_147[] PROGMEM = "The index of recipient device registered token not found"; static const char fb_esp_pgm_str_148[] PROGMEM = "X-Firebase-ETag: true\r\n"; static const char fb_esp_pgm_str_149[] PROGMEM = "if-match: "; static const char fb_esp_pgm_str_150[] PROGMEM = "ETag: "; static const char fb_esp_pgm_str_151[] PROGMEM = "null_etag"; static const char fb_esp_pgm_str_152[] PROGMEM = "Precondition Failed (ETag is not match)"; static const char fb_esp_pgm_str_153[] PROGMEM = "X-HTTP-Method-Override: "; static const char fb_esp_pgm_str_154[] PROGMEM = "{\".sv\": \"timestamp\"}"; static const char fb_esp_pgm_str_155[] PROGMEM = "&shallow=true"; static const char fb_esp_pgm_str_156[] PROGMEM = "/.priority"; static const char fb_esp_pgm_str_157[] PROGMEM = ",\".priority\":"; static const char fb_esp_pgm_str_158[] PROGMEM = "&timeout="; static const char fb_esp_pgm_str_159[] PROGMEM = "ms"; static const char fb_esp_pgm_str_160[] PROGMEM = "&writeSizeLimit="; static const char fb_esp_pgm_str_161[] PROGMEM = "{\".value\":"; static const char fb_esp_pgm_str_162[] PROGMEM = "&format=export"; static const char fb_esp_pgm_str_163[] PROGMEM = "{"; static const char fb_esp_pgm_str_164[] PROGMEM = "Flash memory was not ready"; static const char fb_esp_pgm_str_165[] PROGMEM = "array"; static const char fb_esp_pgm_str_166[] PROGMEM = "\".sv\""; static const char fb_esp_pgm_str_167[] PROGMEM = "Transfer-Encoding: "; static const char fb_esp_pgm_str_168[] PROGMEM = "chunked"; static const char fb_esp_pgm_str_169[] PROGMEM = "Maximum Redirection reached"; static const char fb_esp_pgm_str_170[] PROGMEM = "?auth="; static const char fb_esp_pgm_str_171[] PROGMEM = "&auth="; static const char fb_esp_pgm_str_172[] PROGMEM = "&"; static const char fb_esp_pgm_str_173[] PROGMEM = "?"; static const char fb_esp_pgm_str_174[] PROGMEM = ".com"; static const char fb_esp_pgm_str_175[] PROGMEM = ".net"; static const char fb_esp_pgm_str_176[] PROGMEM = ".int"; static const char fb_esp_pgm_str_177[] PROGMEM = ".edu"; static const char fb_esp_pgm_str_178[] PROGMEM = ".gov"; static const char fb_esp_pgm_str_179[] PROGMEM = ".mil"; static const char fb_esp_pgm_str_180[] PROGMEM = "\n"; static const char fb_esp_pgm_str_181[] PROGMEM = "\r\n\r\n"; static const char fb_esp_pgm_str_182[] PROGMEM = "["; static const char fb_esp_pgm_str_183[] PROGMEM = "file"; static const char fb_esp_pgm_str_184[] PROGMEM = "/fb_bin_0.tmp"; static const char fb_esp_pgm_str_185[] PROGMEM = "The backup data should be the JSON object"; static const char fb_esp_pgm_str_186[] PROGMEM = "object"; static const char fb_esp_pgm_str_187[] PROGMEM = "pool.ntp.org"; static const char fb_esp_pgm_str_188[] PROGMEM = "time.nist.gov"; static const char fb_esp_pgm_str_189[] PROGMEM = "payload too large"; static const char fb_esp_pgm_str_190[] PROGMEM = "cannot config time"; static const char fb_esp_pgm_str_191[] PROGMEM = "SSL client rx buffer size is too small"; static const unsigned char ESP8266_FIREBASE_base64_table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; class FirebaseData; class StreamData; class MultiPathStreamData; class QueueInfo; class FirebaseESP8266; class FCMObject; typedef std::function<void(void)> callback_function_t; static std::vector<std::reference_wrapper<FirebaseData>> fbso; static uint8_t fbdoIdx __attribute__((used)) = 0; class FCMObject { public: FCMObject(); ~FCMObject(); /* Store Firebase Cloud Messaging's authentication credentials. @param serverKey - Server key found on Console: Project settings > Cloud Messaging */ void begin(const String &serverKey); /* Add recipient's device registration token or instant ID token. @param deviceToken - Recipient's device registration token to add that message will be sent to. */ void addDeviceToken(const String &deviceToken); /* Remove the recipient's device registration token or instant ID token. @param index - Index (start from zero) of the recipient's device registration token that added to FCM Data Object of Firebase Data object. */ void removeDeviceToken(uint16_t index); /* Clear all recipient's device registration tokens. */ void clearDeviceToken(); /* Set the notify message type information. @param title - The title text of notification message. @param body - The body text of notification message. */ void setNotifyMessage(const String &title, const String &body); /* Set the notify message type information. @param title - The title text of notification message. @param body - The body text of notification message. @param icon - The name and/or included URI/URL of the icon to show on notifying message. */ void setNotifyMessage(const String &title, const String &body, const String &icon); /* Set the notify message type information. @param title - The title text of notification message. @param body - The body text of notification message. @param icon - The name and/or included URI/URL of the icon to show on notifying message. @param click_action - The URL or intent to accept click event on the notification message. */ void setNotifyMessage(const String &title, const String &body, const String &icon, const String &click_action); /* Clear all notify message information. */ void clearNotifyMessage(); /* Set the custom data message type information. @param jsonString - The JSON structured data string. */ void setDataMessage(const String &jsonString); /* Set the custom data message type information. @param json - The FirebaseJson object. */ void setDataMessage(FirebaseJson &json); /* Clear custom data message type information. */ void clearDataMessage(); /* Set the priority of the message (notification and custom data). @param priority - The priority string i.e. normal and high. */ void setPriority(const String &priority); /* Set the collapse key of the message (notification and custom data). @param key - String of collapse key. */ void setCollapseKey(const String &key); /* Set the Time To Live of the message (notification and custom data). @param seconds - Number of seconds from 0 to 2,419,200 (4 weeks). */ void setTimeToLive(uint32_t seconds); /* Set the topic of the message will be sent to. @param topic - Topic string. */ void setTopic(const String &topic); /* Get the send result. @return String of payload returned from the server. */ String getSendResult(); private: void fcm_begin(FirebaseData &fbdo); bool fcm_send(FirebaseData &fbdo, fb_esp_fcm_msg_type messageType); void fcm_prepareHeader(std::string &header, size_t payloadSize); void fcm_preparePayload(std::string &msg, fb_esp_fcm_msg_type messageType); void clear(); std::string _notify_title = ""; std::string _notify_body = ""; std::string _notify_icon = ""; std::string _notify_click_action = ""; std::string _data_msg = ""; std::string _priority = ""; std::string _collapse_key = ""; std::string _topic = ""; std::string _server_key = ""; std::string _sendResult = ""; int _ttl = -1; uint16_t _index = 0; uint16_t _port = FIREBASE_PORT; std::vector<std::string> _deviceToken; friend class FirebaseESP8266; friend class FirebaseData; }; class QueryFilter { public: QueryFilter(); ~QueryFilter(); QueryFilter &orderBy(const String &); QueryFilter &limitToFirst(int); QueryFilter &limitToLast(int); QueryFilter &startAt(float); QueryFilter &endAt(float); QueryFilter &startAt(const String &); QueryFilter &endAt(const String &); QueryFilter &equalTo(int); QueryFilter &equalTo(const String &); QueryFilter &clear(); friend FirebaseESP8266; friend FirebaseData; protected: std::string _orderBy = ""; std::string _limitToFirst = ""; std::string _limitToLast = ""; std::string _startAt = ""; std::string _endAt = ""; std::string _equalTo = ""; }; class QueueInfo { public: QueueInfo(); ~QueueInfo(); uint8_t totalQueues(); uint32_t currentQueueID(); bool isQueueFull(); String dataType(); String firebaseMethod(); String dataPath(); private: void clear(); uint8_t _totalQueue = 0; uint32_t _currentQueueID = 0; bool _isQueueFull = false; bool _isQueue = false; std::string _dataType = ""; std::string _method = ""; std::string _path = ""; friend class FirebaseESP8266; }; struct QueueItem { fb_esp_data_type dataType = fb_esp_data_type::d_any; fb_esp_method method = fb_esp_method::m_put; uint32_t qID = 0; uint32_t timestamp = 0; uint8_t runCount = 0; uint8_t runIndex = 0; uint8_t storageType = 0; std::string path = ""; std::string payload = ""; std::vector<uint8_t> blob = std::vector<uint8_t>(); std::string filename = ""; QueryFilter queryFilter; int *intPtr = nullptr; float *floatPtr = nullptr; double *doublePtr = nullptr; bool *boolPtr = nullptr; String *stringPtr = nullptr; FirebaseJson *jsonPtr = nullptr; FirebaseJsonArray *arrPtr = nullptr; std::vector<uint8_t> *blobPtr = nullptr; }; class QueueManager { public: QueueManager(); ~QueueManager(); bool add(QueueItem q); void remove(uint8_t index); friend class FirebaseESP8266; friend class FirebaseData; private: void clear(); std::vector<QueueItem> _queueCollection = std::vector<QueueItem>(); uint8_t _maxQueue = 10; }; class FirebaseESP8266 { public: friend class StreamData; friend class FirebaseData; friend class FCMObject; friend class QueryFilter; friend class MultiPathStreamData; typedef void (*StreamEventCallback)(StreamData); typedef void (*MultiPathStreamEventCallback)(MultiPathStreamData); typedef void (*StreamTimeoutCallback)(bool); typedef void (*QueueInfoCallback)(QueueInfo); FirebaseESP8266(); ~FirebaseESP8266(); /* Store Firebase's authentication credentials. @param host - Your Firebase database project host e.g. Your_ProjectID.firebaseio.com. @param auth - Your database secret. @param caCert - Root CA certificate base64 string (PEM file). @param caCertFile - Root CA certificate DER file (binary). @param StorageType - Type of storage, StorageType::SD and StorageType::FLASH. @param GMTOffset - GMT time offset in hour is required to set time in order to make BearSSL data decryption/encryption to work. This parameter is only required for ESP8266 Core SDK v2.5.x or later. Root CA certificate DER file is only supported in Core SDK v2.5.x */ void begin(const String &host, const String &auth); void begin(const String &host, const String &auth, const char *caCert, float GMTOffset = 0.0); void begin(const String &host, const String &auth, const String &caCertFile, uint8_t storageType, float GMTOffset = 0.0); /* Stop Firebase and release all resources. @param fbdo - Firebase Data Object to hold data and instances. */ void end(FirebaseData &fbdo); /* Reconnect WiFi if lost connection. @param reconnect - The boolean to set/unset WiFi AP reconnection. */ void reconnectWiFi(bool reconnect); /* Set the decimal places for float value to be stored in database. @param digits - The decimal places. */ void setFloatDigits(uint8_t digits); /* Set the decimal places for double value to be stored in database. @param digits - The decimal places. */ void setDoubleDigits(uint8_t digits); /* Set the timeout of Firebase.get functions. @param fbdo - Firebase Data Object to hold data and instances. @param millisec - The milliseconds to limit the request (0 - 900,000 ms or 15 min). */ void setReadTimeout(FirebaseData &fbdo, int millisec); /* Set the size limit of payload data that will write to the database for each request. @param fbdo - Firebase Data Object to hold data and instances. @param size - The size identified string e.g. tiny, small, medium, large and unlimited. Size string and its write timeout in seconds e.g. tiny (1s), small (10s), medium (30s) and large (60s). */ void setwriteSizeLimit(FirebaseData &fbdo, const String &size); /* Read the database rules. @param fbdo - Firebase Data Object to hold data and instances. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].jsonData will return the JSON string value of database rules returned from the server. */ bool getRules(FirebaseData &fbdo); /* Write the database rules. @param fbdo - Firebase Data Object to hold data and instances. @param rules - Database rules in JSON String format. @return - Boolean type status indicates the success of the operation. */ bool setRules(FirebaseData &fbdo, const String &rules); /* Determine whether the defined database path exists or not. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path to be checked. @return - Boolean type result indicates whether the defined path existed or not. */ bool pathExist(FirebaseData &fbdo, const String &path); /* Determine the unique identifier (ETag) of current data at the defined database path. @return String of unique identifier. */ String getETag(FirebaseData &fbdo, const String &path); /* Get the shallowed data at a defined node path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path being read the data. @return - Boolean type status indicates the success of the operation. Return the child data with its value or JSON object (its values will be truncated to true). Call [FirebaseData object].stringData() to get shallowed string data (number, string and JSON object). */ bool getShallowData(FirebaseData &fbdo, const String &path); /* Enable the library to use only classic HTTP GET and POST methods. @param fbdo - Firebase Data Object to hold data and instances. @param flag - Boolean value to enable. This option used to escape the Firewall restriction (if the device is connected through Firewall) that allows only HTTP GET and POST HTTP PATCH request was sent as PATCH which not affected by this option. */ void enableClassicRequest(FirebaseData &fbdo, bool flag); /* Set the virtual child node ".priority" to the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which to set the priority value. @param priority - The priority value. @return - Boolean type status indicates the success of the operation. This allows us to set priority to any node other than a priority that set through setJSON, pushJSON, updateNode, and updateNodeSilent functions. The returned priority value from server can read from function [FirebaseData object].priority(). */ bool setPriority(FirebaseData &fbdo, const String &path, float priority); /* Read the virtual child node ".priority" value at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which to set the priority value. @return - Boolean type status indicates the success of the operation. The priority value from server can read from function [FirebaseData object].priority(). */ bool getPriority(FirebaseData &fbdo, const String &path); /* Append new integer value to the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which integer value will be appended. @param intValue - The appended value. @return - Boolean type status indicates the success of the operation. The new appended node's key will be stored in Firebase Data object, which its value can be accessed via function [FirebaseData object].pushName(). */ bool pushInt(FirebaseData &fbdo, const String &path, int intValue); bool push(FirebaseData &fbdo, const String &path, int intValue); /* Append new integer value and the virtual child ".priority" to the defined database path. */ bool pushInt(FirebaseData &fbdo, const String &path, int intValue, float priority); bool push(FirebaseData &fbdo, const String &path, int intValue, float priority); /* Append new float value to the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path in which float value will be appended. @param floatValue - The appended value. @return - Boolean type status indicates the success of the operation. The new appended node's key will be stored in Firebase Data object, which its value can be accessed via function [FirebaseData object].pushName(). */ bool pushFloat(FirebaseData &fbdo, const String &path, float floatValue); bool push(FirebaseData &fbdo, const String &path, float floatValue); /* Append new float value and the virtual child ".priority" to the defined database path. */ bool pushFloat(FirebaseData &fbdo, const String &path, float floatValue, float priority); bool push(FirebaseData &fbdo, const String &path, float floatValue, float priority); /* Append new double value (8 bytes) to the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path in which float value will be appended. @param doubleValue - The appended value. @return - Boolean type status indicates the success of the operation. The new appended node's key will be stored in Firebase Data object, which its value can be accessed via function [FirebaseData object].pushName(). */ bool pushDouble(FirebaseData &fbdo, const String &path, double doubleValue); bool push(FirebaseData &fbdo, const String &path, double doubleValue); /* Append new double value (8 bytes) and the virtual child ".priority" to the defined database path. */ bool pushDouble(FirebaseData &fbdo, const String &path, double doubleValue, float priority); bool push(FirebaseData &fbdo, const String &path, double doubleValue, float priority); /* Append new Boolean value to the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which Boolean value will be appended. @param boolValue - The appended value. @return - Boolean type status indicates the success of the operation. The new appended node's key will be stored in Firebase Data object, which its value can be accessed via function [FirebaseData object].pushName(). */ bool pushBool(FirebaseData &fbdo, const String &path, bool boolValue); bool push(FirebaseData &fbdo, const String &path, bool boolValue); /* Append the new Boolean value and the virtual child ".priority" to the defined database path. */ bool pushBool(FirebaseData &fbdo, const String &path, bool boolValue, float priority); bool push(FirebaseData &fbdo, const String &path, bool boolValue, float priority); /* Append a new string (text) to the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which string will be appended. @param StringValue - The appended value. @return - Boolean type status indicates the success of the operation. The new appended node's key stored in Firebase Data object, which can be accessed via function [FirebaseData object].pushName(). */ bool pushString(FirebaseData &fbdo, const String &path, const String &stringValue); bool push(FirebaseData &fbdo, const String &path, const char *stringValue); bool push(FirebaseData &fbdo, const String &path, const String &stringValue); bool push(FirebaseData &fbdo, const String &path, const StringSumHelper &stringValue); /* Append new string (text) and the virtual child ".priority" to the defined database path. */ bool pushString(FirebaseData &fbdo, const String &path, const String &stringValue, float priority); bool push(FirebaseData &fbdo, const String &path, const char *stringValue, float priority); bool push(FirebaseData &fbdo, const String &path, const String &stringValue, float priority); bool push(FirebaseData &fbdo, const String &path, const StringSumHelper &stringValue, float priority); /* Append new child nodes key and value (using FirebaseJson object) to the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which key and value in FirebaseJson object will be appended. @param json - The appended FirebaseJson object. @return - Boolean type status indicates the success of the operation. The new appended node key will be stored in Firebase Data object, which its value can be accessed via function [FirebaseData object].pushName(). */ bool pushJSON(FirebaseData &fbdo, const String &path, FirebaseJson &json); bool push(FirebaseData &fbdo, const String &path, FirebaseJson &json); /* Append new child node key and value (FirebaseJson object) and the virtual child ".priority" to the defined database path. */ bool pushJSON(FirebaseData &fbdo, const String &path, FirebaseJson &json, float priority); bool push(FirebaseData &fbdo, const String &path, FirebaseJson &json, float priority); /* Append child node array (using FirebaseJsonArray object) to the defined database path. This will replace any child nodes inside the defined path with array defined in FirebaseJsonArray object. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which key and value in FirebaseJsonArray object will be appended. @param arr - The appended FirebaseJsonArray object. @return - Boolean type status indicates the success of the operation. The new appended node's key will be stored in Firebase Data object, which its value can be accessed via function [FirebaseData object].pushName(). */ bool pushArray(FirebaseData &fbdo, const String &path, FirebaseJsonArray &arr); bool push(FirebaseData &fbdo, const String &path, FirebaseJsonArray &arr); /* Append FirebaseJsonArray object and virtual child ".priority" at the defined database path. */ bool pushArray(FirebaseData &fbdo, const String &path, FirebaseJsonArray &arr, float priority); bool push(FirebaseData &fbdo, const String &path, FirebaseJsonArray &arr, float priority); /* Append new blob (binary data) to the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which binary data will be appended. @param blob - Byte array of data. @param size - Size of the byte array. @return - Boolean type status indicates the success of the operation. The new appended node's key will be stored in Firebase Data object, which its value can be accessed via function [FirebaseData object].pushName(). */ bool pushBlob(FirebaseData &fbdo, const String &path, uint8_t *blob, size_t size); bool push(FirebaseData &fbdo, const String &path, uint8_t *blob, size_t size); /* Append new blob (binary data) and the virtual child ".priority" to the defined database path. */ bool pushBlob(FirebaseData &fbdo, const String &path, uint8_t *blob, size_t size, float priority); bool push(FirebaseData &fbdo, const String &path, uint8_t *blob, size_t size, float priority); /* Append new binary data from the file stores on SD card/Flash memory to the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param storageType - Type of storage to read file data, StorageType::SPIFS or StorageType::SD. @param path - Target database path in which binary data from the file will be appended. @param fileName - File name included its path in SD card/Flash memory. @return - Boolean type status indicates the success of the operation. The new appended node's key will be stored in Firebase Data object, which its value can be accessed via function [FirebaseData object].pushName(). */ bool pushFile(FirebaseData &fbdo, uint8_t storageType, const String &path, const String &fileName); bool push(FirebaseData &fbdo, uint8_t storageType, const String &path, const String &fileName); /* Append new binary data from the file stores on SD card/Flash memory and the virtual child ".priority" to the defined database path. */ bool pushFile(FirebaseData &fbdo, uint8_t storageType, const String &path, const String &fileName, float priority); bool push(FirebaseData &fbdo, uint8_t storageType, const String &path, const String &fileName, float priority); /* Append the new Firebase server's timestamp to the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which timestamp will be appended. @return - Boolean type status indicates the success of the operation. The new appended node's key will be stored in Firebase Data object, which its value can be accessed via function [FirebaseData object].pushName(). */ bool pushTimestamp(FirebaseData &fbdo, const String &path); /* Set integer data at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which integer data will be set. @param intValue - Integer value to set. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data that successfully stores in the database. Call [FirebaseData object].intData will return the integer value of payload returned from server. */ bool setInt(FirebaseData &fbdo, const String &path, int intValue); bool set(FirebaseData &fbdo, const String &path, int intValue); /* Set integer data and virtual child ".priority" at the defined database path. */ bool setInt(FirebaseData &fbdo, const String &path, int intValue, float priority); bool set(FirebaseData &fbdo, const String &path, int intValue, float priority); /* Set integer data at the defined database path if defined database path's ETag matched the ETag value. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which integer data will be set. @param intValue - Integer value to set. @param ETag - Known unique identifier string (ETag) of defined database path. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. If ETag at the defined database path does not match the provided ETag parameter, the operation will fail with HTTP code 412, Precondition Failed (ETag is not matched). If the operation failed due to ETag is not match, call [FirebaseData object].ETag() to get the current ETag value. Also call [FirebaseData object].intData to get the current integer value. */ bool setInt(FirebaseData &fbdo, const String &path, int intValue, const String &ETag); bool set(FirebaseData &fbdo, const String &path, int intValue, const String &ETag); /* Set integer data and the virtual child ".priority" if defined ETag matches at the defined database path */ bool setInt(FirebaseData &fbdo, const String &path, int intValue, float priority, const String &ETag); bool set(FirebaseData &fbdo, const String &path, int intValue, float priority, const String &ETag); /* Set float data at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path in which float data will be set. @param floatValue - Float value to set. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].floatData will return the float value of payload returned from server. */ bool setFloat(FirebaseData &fbdo, const String &path, float floatValue); bool set(FirebaseData &fbdo, const String &path, float floatValue); /* Set float data and virtual child ".priority" at the defined database path. */ bool setFloat(FirebaseData &fbdo, const String &path, float floatValue, float priority); bool set(FirebaseData &fbdo, const String &path, float floatValue, float priority); /* Set float data at the defined database path if defined database path's ETag matched the ETag value. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path in which float data will be set. @param floatValue - Float value to set. @param ETag - Known unique identifier string (ETag) of defined database path. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].floatData will return the float value of payload returned from server. If ETag at the defined database path does not match the provided ETag parameter, the operation will fail with HTTP code 412, Precondition Failed (ETag is not matched). If the operation failed due to ETag is not match, call [FirebaseData object].ETag() to get the current ETag value. Also call [FirebaseData object].floatData to get the current float value. */ bool setFloat(FirebaseData &fbdo, const String &path, float floatValue, const String &ETag); bool set(FirebaseData &fbdo, const String &path, float floatValue, const String &ETag); /* Set float data and the virtual child ".priority" if defined ETag matches at the defined database path */ bool setFloat(FirebaseData &fbdo, const String &path, float floatValue, float priority, const String &ETag); bool set(FirebaseData &fbdo, const String &path, float floatValue, float priority, const String &ETag); /* Set double data at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path in which float data will be set. @param doubleValue - Double value to set. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].doubleData will return the double value of the payload returned from the server. Due to bugs in Serial.print in Arduino, to print large double value with zero decimal place, use printf("%.9lf\n", firebaseData.doubleData()); for print the returned double value up to 9 decimal places. */ bool setDouble(FirebaseData &fbdo, const String &path, double doubleValue); bool set(FirebaseData &fbdo, const String &path, double doubleValue); /* Set double data and virtual child ".priority" at the defined database path. */ bool setDouble(FirebaseData &fbdo, const String &path, double doubleValue, float priority); bool set(FirebaseData &fbdo, const String &path, double doubleValue, float priority); /* Set double data at the defined database path if defined database path's ETag matched the ETag value. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path in which float data will be set. @param doubleValue - Double value to set. @param ETag - Known unique identifier string (ETag) of defined database path. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].doubleData will return the double value of the payload returned from the server. If ETag at the defined database path does not match the provided ETag parameter, the operation will fail with HTTP code 412, Precondition Failed (ETag is not matched). If the operation failed due to ETag is not match, call [FirebaseData object].ETag() to get the current ETag value. Also call [FirebaseData object].doubeData to get the current double value. */ bool setDouble(FirebaseData &fbdo, const String &path, double doubleValue, const String &ETag); bool set(FirebaseData &fbdo, const String &path, double doubleValue, const String &ETag); /* Set double data and the virtual child ".priority" if defined ETag matches at the defined database path */ bool setDouble(FirebaseData &fbdo, const String &path, double doubleValue, float priority, const String &ETag); bool set(FirebaseData &fbdo, const String &path, double doubleValue, float priority, const String &ETag); /* Set Boolean data at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which Boolean data will be set. @param boolValue - Boolean value to set. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].boolData will return the Boolean value of the payload returned from the server. */ bool setBool(FirebaseData &fbdo, const String &path, bool boolValue); bool set(FirebaseData &fbdo, const String &path, bool boolValue); /* Set boolean data and virtual child ".priority" at the defined database path. */ bool setBool(FirebaseData &fbdo, const String &path, bool boolValue, float priority); bool set(FirebaseData &fbdo, const String &path, bool boolValue, float priority); /* Set Boolean data at the defined database path if defined database path's ETag matched the ETag value. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which Boolean data will be set. @param boolValue - Boolean value to set. @param ETag - Known unique identifier string (ETag) of defined database path. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].boolData will return the Boolean value of the payload returned from the server. If ETag at the defined database path does not match the provided ETag parameter, the operation will fail with HTTP code 412, Precondition Failed (ETag is not matched). If the operation failed due to ETag is not match, call [FirebaseData object].ETag() to get the current ETag value. Also call [FirebaseData object].doubeData to get the current boolean value. */ bool setBool(FirebaseData &fbdo, const String &path, bool boolValue, const String &ETag); bool set(FirebaseData &fbdo, const String &path, bool boolValue, const String &ETag); /* Set boolean data and the virtual child ".priority" if defined ETag matches at the defined database path */ bool setBool(FirebaseData &fbdo, const String &path, bool boolValue, float priority, const String &ETag); bool set(FirebaseData &fbdo, const String &path, bool boolValue, float priority, const String &ETag); /* Set string (text) at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path in which string data will be set. @param stringValue - String or text to set. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data that successfully stores in the database. Call [FirebaseData object].stringData will return the string value of the payload returned from the server. */ bool setString(FirebaseData &fbdo, const String &path, const String &stringValue); bool set(FirebaseData &fbdo, const String &path, const char *stringValue); bool set(FirebaseData &fbdo, const String &path, const String &stringValue); bool set(FirebaseData &fbdo, const String &path, const StringSumHelper &stringValue); /* Set string data and virtual child ".priority" at the defined database path. */ bool setString(FirebaseData &fbdo, const String &path, const String &stringValue, float priority); bool set(FirebaseData &fbdo, const String &path, const char *stringValue, float priority); bool set(FirebaseData &fbdo, const String &path, const String &stringValue, float priority); bool set(FirebaseData &fbdo, const String &path, const StringSumHelper &stringValue, float priority); /* Set string (text) at the defined database path if defined database path's ETag matched the ETag value. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path in which string data will be set. @param stringValue - String or text to set. @param ETag - Known unique identifier string (ETag) of defined database path. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].stringData will return the string value of the payload returned from the server. If ETag at the defined database path does not match the provided ETag parameter, the operation will fail with HTTP code 412, Precondition Failed (ETag is not matched). If the operation failed due to ETag is not match, call [FirebaseData object].ETag() to get the current ETag value. Also, call [FirebaseData object].stringData to get the current string value. */ bool setString(FirebaseData &fbdo, const String &path, const String &stringValue, const String &ETag); bool set(FirebaseData &fbdo, const String &path, const char *stringValue, const String &ETag); bool set(FirebaseData &fbdo, const String &path, const String &stringValue, const String &ETag); bool set(FirebaseData &fbdo, const String &path, const StringSumHelper &stringValue, const String &ETag); /* Set string data and the virtual child ".priority" if defined ETag matches at the defined database path */ bool setString(FirebaseData &fbdo, const String &path, const String &stringValue, float priority, const String &ETag); bool set(FirebaseData &fbdo, const String &path, const char *stringValue, float priority, const String &ETag); bool set(FirebaseData &fbdo, const String &path, const String &stringValue, float priority, const String &ETag); bool set(FirebaseData &fbdo, const String &path, const StringSumHelper &stringValue, float priority, const String &ETag); /* Set the child node key and value (using FirebaseJson object) to the defined database path. This will replace any child nodes inside the defined path with node' s key and value defined in FirebaseJson object. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which key and value in FirebaseJson object will be replaced or set. @param json - The FirebaseJson object. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].jsonData will return the JSON string value of payload returned from server. */ bool setJSON(FirebaseData &fbdo, const String &path, FirebaseJson &json); bool set(FirebaseData &fbdo, const String &path, FirebaseJson &json); /* Set JSON data or FirebaseJson object and virtual child ".priority" at the defined database path. */ bool setJSON(FirebaseData &fbdo, const String &path, FirebaseJson &json, float priority); bool set(FirebaseData &fbdo, const String &path, FirebaseJson &json, float priority); /* Set child node key and value (using JSON data or FirebaseJson object) to the defined database path if defined database path's ETag matched the ETag value. This will replace any child nodes inside the defined path with node' s key and value defined in JSON data or FirebaseJson object. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which key and value in JSON data will be replaced or set. @param json - The FirebaseJson object. @param ETag - Known unique identifier string (ETag) of defined database path. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].jsonData will return the JSON string value of payload returned from server. If ETag at the defined database path does not match the provided ETag parameter, the operation will fail with HTTP code 412, Precondition Failed (ETag is not matched). If the operation failed due to ETag is not match, call [FirebaseData object].ETag() to get the current ETag value. Also call [FirebaseData object].jsonData to get the current JSON string value. */ bool setJSON(FirebaseData &fbdo, const String &path, FirebaseJson &json, const String &ETag); bool set(FirebaseData &fbdo, const String &path, FirebaseJson &json, const String &ETag); /* Set JSON data or FirebaseJson object and the virtual child ".priority" if defined ETag matches at the defined database path */ bool setJSON(FirebaseData &fbdo, const String &path, FirebaseJson &json, float priority, const String &ETag); bool set(FirebaseData &fbdo, const String &path, FirebaseJson &json, float priority, const String &ETag); /* Set child node array (using FirebaseJsonArray object) to the defined database path. This will replace any child nodes inside the defined path with array defined in FirebaseJsonArray object. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which key and value in FirebaseJsonArray object will be replaced or set. @param arr - The FirebaseJsonArray object. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data that successfully stores in the database. Call [FirebaseData object].jsonArray will return pointer to FirebaseJsonArray object contains array payload returned from server, get the array payload using FirebaseJsonArray *arr = firebaseData.jsonArray(); */ bool setArray(FirebaseData &fbdo, const String &path, FirebaseJsonArray &arr); bool set(FirebaseData &fbdo, const String &path, FirebaseJsonArray &arr); /* Set FirebaseJsonArray object and virtual child ".priority" at the defined database path. */ bool setArray(FirebaseData &fbdo, const String &path, FirebaseJsonArray &arr, float priority); bool set(FirebaseData &fbdo, const String &path, FirebaseJsonArray &arr, float priority); /* Set array (using JSON data or FirebaseJson object) to the defined database path if defined database path's ETag matched the ETag value. This will replace any child nodes inside the defined path with array defined in FirebaseJsonArray object. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which key and value in JSON data will be replaced or set. @param arr - The FirebaseJsonArray object. @param ETag - Known unique identifier string (ETag) of defined database path. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].jsonArray will return pointer to FirebaseJsonArray object contains array payload returned from server, get the array payload using FirebaseJsonArray *arr = firebaseData.jsonArray(); If ETag at the defined database path does not match the provided ETag parameter, the operation will fail with HTTP code 412, Precondition Failed (ETag is not matched). If the operation failed due to ETag is not match, call [FirebaseData object].ETag() to get the current ETag value. Also call [FirebaseData object].jsonArray to get the pointer to FirebaseJsonArray object of current array value. */ bool setArray(FirebaseData &fbdo, const String &path, FirebaseJsonArray &arr, const String &ETag); bool set(FirebaseData &fbdo, const String &path, FirebaseJsonArray &arr, const String &ETag); /* Set FirebaseJsonArray object and the virtual child ".priority" if defined ETag matches at the defined database path */ bool setArray(FirebaseData &fbdo, const String &path, FirebaseJsonArray &arr, float priority, const String &ETag); bool set(FirebaseData &fbdo, const String &path, FirebaseJsonArray &arr, float priority, const String &ETag); /* Set blob (binary data) at the defined database path. This will replace any child nodes inside the defined path with a blob or binary data. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which binary data will be set. @param blob - Byte array of data. @param size - Size of the byte array. @return - Boolean type status indicates the success of the operation. No payload returned from the server. */ bool setBlob(FirebaseData &fbdo, const String &path, uint8_t *blob, size_t size); bool set(FirebaseData &fbdo, const String &path, uint8_t *blob, size_t size); /* Set blob data and virtual child ".priority" at the defined database path. */ bool setBlob(FirebaseData &fbdo, const String &path, uint8_t *blob, size_t size, float priority); bool set(FirebaseData &fbdo, const String &path, uint8_t *blob, size_t size, float priority); /* Set blob (binary data) at the defined database path if defined database path's ETag matched the ETag value. This will replace any child nodes inside the defined path with a blob or binary data. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which binary data will be set. @param blob - Byte array of data. @param size - Size of the byte array. @param ETag - Known unique identifier string (ETag) of defined database path. @return - Boolean type status indicates the success of the operation. No payload returned from the server. If ETag at the defined database path does not match the provided ETag parameter, the operation will fail with HTTP code 412, Precondition Failed (ETag is not matched). */ bool setBlob(FirebaseData &fbdo, const String &path, uint8_t *blob, size_t size, const String &ETag); bool set(FirebaseData &fbdo, const String &path, uint8_t *blob, size_t size, const String &ETag); /* Set blob data and the virtual child ".priority" if defined ETag matches at the defined database path */ bool setBlob(FirebaseData &fbdo, const String &path, uint8_t *blob, size_t size, float priority, const String &ETag); bool set(FirebaseData &fbdo, const String &path, uint8_t *blob, size_t size, float priority, const String &ETag); /* Set binary data from the file store on SD card/Flash memory to the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param storageType - Type of storage to read file data, StorageType::SPIFS or StorageType::SD. @param path - Target database path in which binary data from the file will be set. @param fileName - File name included its path in SD card/Flash memory @return - Boolean type status indicates the success of the operation. No payload returned from the server. */ bool setFile(FirebaseData &fbdo, uint8_t storageType, const String &path, const String &fileName); bool set(FirebaseData &fbdo, uint8_t storageType, const String &path, const String &fileName); /* Set binary data from the file and virtual child ".priority" at the defined database path. */ bool setFile(FirebaseData &fbdo, uint8_t storageType, const String &path, const String &fileName, float priority); bool set(FirebaseData &fbdo, uint8_t storageType, const String &path, const String &fileName, float priority); /* Set binary data from file stored on SD card/Flash memory to the defined database path if defined database path's ETag matched the ETag value. @param fbdo - Firebase Data Object to hold data and instances. @param storageType - Type of storage to read file data, StorageType::SPIFS or StorageType::SD. @param path - Target database path in which binary data from the file will be set. @param fileName - File name included its path in SD card/Flash memory. @param ETag - Known unique identifier string (ETag) of defined database path. @return - Boolean type status indicates the success of the operation. No payload returned from the server. If ETag at the defined database path does not match the provided ETag parameter, the operation will fail with HTTP code 412, Precondition Failed (ETag is not matched). */ bool setFile(FirebaseData &fbdo, uint8_t storageType, const String &path, const String &fileName, const String &ETag); bool set(FirebaseData &fbdo, uint8_t storageType, const String &path, const String &fileName, const String &ETag); /* Set binary data from the file and the virtual child ".priority" if defined ETag matches at the defined database path */ bool setFile(FirebaseData &fbdo, uint8_t storageType, const String &path, const String &fileName, float priority, const String &ETag); bool set(FirebaseData &fbdo, uint8_t storageType, const String &path, const String &fileName, float priority, const String &ETag); /* Set Firebase server's timestamp to the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which timestamp will be set. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].intData will return the integer value of timestamp in seconds or [FirebaseData object].doubleData to get millisecond timestamp. Due to bugs in Serial.print in Arduino, to print large double value with zero decimal place, use printf("%.0lf\n", firebaseData.doubleData());. */ bool setTimestamp(FirebaseData &fbdo, const String &path); /* Update the child node key or existing key's value (using FirebaseJson object) under the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which key and value in FirebaseJson object will be updated. @param json - The FirebaseJson object used for the update. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].jsonData will return the json string value of payload returned from server. To reduce network data usage, use updateNodeSilent instead. */ bool updateNode(FirebaseData &fbdo, const String path, FirebaseJson &json); /* Update child node key or existing key's value and virtual child ".priority" (using JSON data or FirebaseJson object) under the defined database path. */ bool updateNode(FirebaseData &fbdo, const String &path, FirebaseJson &json, float priority); /* Update the child node key or existing key's value (using FirebaseJson object) under the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Target database path which key and value in FirebaseJson object will be updated. @param json - The FirebaseJson object used for the update. @return - Boolean type status indicates the success of the operation. Owing to the objective of this function to reduce network data usage, no payload will be returned from the server. */ bool updateNodeSilent(FirebaseData &fbdo, const String &path, FirebaseJson &json); /* Update child node key or existing key's value and virtual child ".priority" (using JSON data or FirebaseJson object) under the defined database path. */ bool updateNodeSilent(FirebaseData &fbdo, const String &path, FirebaseJson &json, float priority); /* Read any type of value at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the float value is being read. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].intData, [FirebaseData object].floatData, [FirebaseData object].doubleData, [FirebaseData object].boolData, [FirebaseData object].stringData, [FirebaseData object].jsonObject (pointer), [FirebaseData object].jsonArray (pointer) and [FirebaseData object].blobData corresponded to its type from [FirebaseData object].dataType. */ bool get(FirebaseData &fbdo, const String &path); /* Read the integer value at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the float value is being read. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object]. will return the integer value of payload returned from server. If the type of payload returned from server is not integer, float and double, the function [FirebaseData object].intData will return zero (0). */ bool getInt(FirebaseData &fbdo, const String &path); /* Read the integer value at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the float value is being read. @param target - The integer type variable to store value. @return - Boolean type status indicates the success of the operation. If the type of payload returned from the server is not an integer, float and double, the target variable's value will be zero (0). */ bool getInt(FirebaseData &fbdo, const String &path, int &target); /* Read the float value at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the float value is being read. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].floatData will return the float value of payload returned from server. If the payload returned from server is not integer, float and double, the function [FirebaseData object].floatData will return zero (0). */ bool getFloat(FirebaseData &fbdo, const String &path); /* Read the float value at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the float value is being read. @param target - The float type variable to store value. @return - Boolean type status indicates the success of the operation. If the type of payload returned from the server is not an integer, float and double, the target variable's value will be zero (0). */ bool getFloat(FirebaseData &fbdo, const String &path, float &target); /* Read the double value at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the float value is being read. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].doubleData will return the double value of the payload returned from the server. If the payload returned from server is not integer, float and double, the function [FirebaseData object].doubleData will return zero (0). Due to bugs in Serial.print in Arduino, to print large double value with zero decimal place, use printf("%.9lf\n", firebaseData.doubleData()); for print value up to 9 decimal places. */ bool getDouble(FirebaseData &fbdo, const String &path); /* Read the float value at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the float value is being read. @param target - The double type variable to store value. @return - Boolean type status indicates the success of the operation. If the type of payload returned from the server is not an integer, float and double, the target variable's value will be zero (0). */ bool getDouble(FirebaseData &fbdo, const String &path, double &target); /* Read the Boolean value at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the Boolean value is being read. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].boolData will return the Boolean value of the payload returned from the server. If the type of payload returned from the server is not Boolean, the function [FirebaseData object].boolData will return false. */ bool getBool(FirebaseData &fbdo, const String &path); /* Read the Boolean value at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the Boolean value is being read. @param target - The boolean type variable to store value. @return - Boolean type status indicates the success of the operation. If the type of payload returned from the server is not Boolean, the target variable's value will be false. */ bool getBool(FirebaseData &fbdo, const String &path, bool &target); /* Read the string at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the string value is being read. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data that successfully stores in the database. Call [FirebaseData object].stringData will return the string value of the payload returned from the server. If the type of payload returned from the server is not a string, the function [FirebaseData object].stringData will return empty string (String object). */ bool getString(FirebaseData &fbdo, const String &path); /* Read the string at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the string value is being read. @param target - The String object to store value. @return - Boolean type status indicates the success of the operation. If the type of payload returned from the server is not a string, the target String object's value will be empty. */ bool getString(FirebaseData &fbdo, const String &path, String &target); /* Read the JSON string at the defined database path. The returned payload JSON string represents the child nodes and their value. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the JSON string value is being read. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data that successfully stores in the database. Call [FirebaseData object].jsonObject will return the pointer to FirebaseJson object contains the value of the payload returned from the server. If the type of payload returned from server is not json, the function [FirebaseData object].jsonObject will contain empty object. */ bool getJSON(FirebaseData &fbdo, const String &path); /* Read the JSON string at the defined database path. The returned the pointer to FirebaseJson that contains JSON payload represents the child nodes and their value. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the JSON string value is being read. @param target - The FirebaseJson object pointer to get JSON data. @return - Boolean type status indicates the success of the operation. If the type of payload returned from the server is not JSON, the target FirebaseJson object will contain an empty object. */ bool getJSON(FirebaseData &fbdo, const String &path, FirebaseJson *target); /* Read the JSON string at the defined database path. The returned the pointer to FirebaseJson that contains JSON payload represents the child nodes and their value. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the JSON string value is being read. @param query - QueryFilter class to set query parameters to filter data. @return - Boolean type status indicates the success of the operation. Available query parameters for filtering the data are the following. QueryFilter.orderBy - Required parameter to specify which data used for data filtering included child key, key, and value. Use "$key" for filtering data by keys of all nodes at the defined database path. Use "$value" for filtering data by value of all nodes at the defined database path. Use "$priority" for filtering data by "virtual child" named .priority of all nodes. Use any child key to filter by that key. QueryFilter.limitToFirst - The total children (number) to filter from the first child. QueryFilter.limitToLast - The total last children (number) to filter. QueryFilter.startAt - Starting value of range (number or string) of query upon orderBy param. QueryFilter.endAt - Ending value of range (number or string) of query upon orderBy param. QueryFilter.equalTo - Value (number or string) matches the orderBy param Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].jsonObject will return the pointer to FirebaseJson object contains the value of the payload returned from the server. If the type of payload returned from server is not json, the function [FirebaseData object].jsonObject will contain empty object. */ bool getJSON(FirebaseData &fbdo, const String &path, QueryFilter &query); /* Read the JSON string at the defined database path as above @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the JSON string value is being read. @param target - The FirebaseJson object pointer to get JSON data. @return - Boolean type status indicates the success of the operation. If the type of payload returned from the server is not JSON, the target FirebaseJson object will contain an empty object. */ bool getJSON(FirebaseData &fbdo, const String &path, QueryFilter &query, FirebaseJson *target); /* Read the array data at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the array is being read. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data that successfully stores in the database. Call [FirebaseData object].jsonArray will return the pointer to FirebaseJsonArray object contains array value of payload returned from server. If the type of payload returned from the server is not an array, the array element in [FirebaseData object].jsonArray will be empty. */ bool getArray(FirebaseData &fbdo, const String &path); /* Read the array data at the defined database path, and assign data to the target. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the array is being read. @param target - The FirebaseJsonArray object pointer to get array value. @return - Boolean type status indicates the success of the operation. If the type of payload returned from the server is not an array, the target FirebaseJsonArray object will contain an empty array. */ bool getArray(FirebaseData &fbdo, const String &path, FirebaseJsonArray *target); /* Read the array data at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the array is being read. @param query - QueryFilter class to set query parameters to filter data. @return - Boolean type status indicates the success of the operation. Available query parameters for filtering the data are the following. QueryFilter.orderBy - Required parameter to specify which data used for data filtering included child key, key, and value. Use "$key" for filtering data by keys of all nodes at the defined database path. Use "$value" for filtering data by value of all nodes at the defined database path. Use "$priority" for filtering data by "virtual child" named .priority of all nodes. Use any child key to filter by that key. QueryFilter.limitToFirst - The total children (number) to filter from the first child. QueryFilter.limitToLast - The total last children (number) to filter. QueryFilter.startAt - Starting value of range (number or string) of query upon orderBy param. QueryFilter.endAt - Ending value of range (number or string) of query upon orderBy param. QueryFilter.equalTo - Value (number or string) matches the orderBy param Call [FirebaseData object].dataType to determine what type of data that successfully stores in the database. Call [FirebaseData object].jsonArray will return the pointer to FirebaseJsonArray object contains array of payload returned from server. If the type of payload returned from the server is not an array, the function [FirebaseData object].jsonArray will contain empty array. */ bool getArray(FirebaseData &fbdo, const String &path, QueryFilter &query); /* Read the array data at the defined database path as above @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the array is being read. @param target - The FirebaseJsonArray object to get array value. @return - Boolean type status indicates the success of the operation. If the type of payload returned from the server is not an array, the target FirebaseJsonArray object will contain an empty array. */ bool getArray(FirebaseData &fbdo, const String &path, QueryFilter &query, FirebaseJsonArray *target); /* Read the blob (binary data) at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the binary data is being read. @return - Boolean type status indicates the success of the operation. Call [FirebaseData object].dataType to determine what type of data successfully stores in the database. Call [FirebaseData object].blobData will return the dynamic array of unsigned 8-bit data (i.e. std::vector<uint8_t>) of payload returned from server. If the type of payload returned from the server is not a blob, the function [FirebaseData object].blobData will return empty array. */ bool getBlob(FirebaseData &fbdo, const String &path); /* Read the blob (binary data) at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path in which the binary data is being read. @param target - Dynamic array of unsigned 8-bit data (i.e. std::vector<uint8_t>) to store value. @return - Boolean type status indicates the success of the operation. If the type of payload returned from the server is not a blob, the target variable value will be an empty array. */ bool getBlob(FirebaseData &fbdo, const String &path, std::vector<uint8_t> &target); /* Download file data in a database at the defined database path and save it to SD card/Flash memory. The downloaded data will be decoded to binary and save to SD card/Flash memory, then please make sure that data at the defined database path is the file type. @param fbdo - Firebase Data Object to hold data and instances. @param storageType - Type of storage to write file data, StorageType::SPIFS or StorageType::SD. @param nodePath - Database path that file data will be downloaded. @param fileName - File name included its path in SD card/Flash memory. to save in SD card/Flash memory. @return Boolean type status indicates the success of the operation. */ bool getFile(FirebaseData &fbdo, uint8_t storageType, const String &nodePath, const String &fileName); /* Delete all child nodes at the defined database path. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path to be deleted. @return - Boolean type status indicates the success of the operation. */ bool deleteNode(FirebaseData &fbdo, const String &path); /* Delete all child nodes at the defined database path if defined database path's ETag matched the ETag value. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path to be deleted. @param ETag - Known unique identifier string (ETag) of defined database path. @return - Boolean type status indicates the success of the operation. If ETag at the defined database path does not match the provided ETag parameter, the operation will fail with HTTP code 412, Precondition Failed (ETag is not matched). */ bool deleteNode(FirebaseData &fbdo, const String &path, const String &ETag); /* Start subscribe to the value changes at the defined path and its children. @param fbdo - Firebase Data Object to hold data and instances. @param path - Database path to subscribe. @return - Boolean type status indicates the success of the operation. */ bool beginStream(FirebaseData &fbdo, const String &path); /* Start subscribe to the value changes at the defined parent node path with multiple nodes paths parsing. @param fbdo - Firebase Data Object to hold data and instances. @param parentPath - Database parent node path to subscribe. @param childPath - The string array of child nodes paths for parsing. @param size - The size of string array of child nodes paths for parsing. @return - Boolean type status indicates the success of the operation. */ bool beginMultiPathStream(FirebaseData &fbdo, const String &parentPath, const String *childPath, size_t size); /* Read the stream event data at the defined database path. Once beginStream was called e.g. in setup(), the readStream function should call inside the loop function. @param fbdo - Firebase Data Object to hold data and instances. @return - Boolean type status indicates the success of the operation. Using the same Firebase Data object for stream read/monitoring associated with getXXX, setXXX, pushXXX, updateNode and deleteNode will break or quit the current stream connection. The stream will be resumed or reconnected automatically when calling readStream. */ bool readStream(FirebaseData &fbdo); /* End the stream connection at a defined path. It can be restart again by calling beginStream. @param fbdo - Firebase Data Object to hold data and instances. @return - Boolean type status indicates the success of the operation. */ bool endStream(FirebaseData &fbdo); /* Set the stream callback functions. setStreamCallback should be called before Firebase.beginStream. @param fbdo - Firebase Data Object to hold data and instances. @param dataAvailablecallback - a Callback function that accepts streamData parameter. @param timeoutCallback - Callback function will be called when the stream connection was timed out (optional). dataAvailablecallback will be called When data in the defined path changed or the stream path changed or stream connection was resumed from getXXX, setXXX, pushXXX, updateNode, deleteNode. The payload returned from the server will be one of these integer, float, string, JSON and blob types. Call [streamData object].dataType to determine what type of data successfully stores in the database. Call [streamData object].xxxData will return the appropriate data type of the payload returned from the server. */ void setStreamCallback(FirebaseData &fbdo, StreamEventCallback dataAvailablecallback, StreamTimeoutCallback timeoutCallback = NULL); /* Set the multiple paths stream callback functions. setMultiPathStreamCallback should be called before Firebase.beginMultiPathStream. @param fbdo - Firebase Data Object to hold data and instances. @param multiPathDataCallback - a Callback function that accepts MultiPathStreamData parameter. @param timeoutCallback - a Callback function will be called when the stream connection was timed out (optional). multiPathDataCallback will be called When data in the defined path changed or the stream path changed or stream connection was resumed from getXXX, setXXX, pushXXX, updateNode, deleteNode. The payload returned from the server will be one of these integer, float, string and JSON. Call [MultiPathStreamData object].get to get the child node value, type and data path. The properties [MultiPathStreamData object].value, [MultiPathStreamData object].dataPath, and [MultiPathStreamData object].type will return the value, path of data, and type of data respectively. These properties will store the result from calling the function [MultiPathStreamData object].get. */ void setMultiPathStreamCallback(FirebaseData &fbdo, MultiPathStreamEventCallback multiPathDataCallback, StreamTimeoutCallback timeoutCallback = NULL); /* Remove stream callback functions. @param fbdo - Firebase Data Object to hold data and instances. */ void removeStreamCallback(FirebaseData &fbdo); /* Remove multiple paths stream callback functions. @param fbdo - Firebase Data Object to hold data and instances. */ void removeMultiPathStreamCallback(FirebaseData &fbdo); /* Backup (download) database at the defined database path to SD card/Flash memory. @param fbdo - Firebase Data Object to hold data and instances. @param storageType - Type of storage to save file, StorageType::SPIFS or StorageType::SD. @param nodePath - Database path to be backuped. @param fileName - File name to save. Only 8.3 DOS format (max. 8 bytes file name and 3 bytes file extension) can be saved to SD card/Flash memory. @return Boolean type status indicates the success of the operation. */ bool backup(FirebaseData &fbdo, uint8_t storageType, const String &nodePath, const String &fileName); /* Restore database at a defined path using backup file saved on SD card/Flash memory. @param fbdo - Firebase Data Object to hold data and instances. @param storageType - Type of storage to read file, StorageType::SPIFS or StorageType::SD. @param nodePath - Database path to be restored. @param fileName - File name to read @return Boolean type status indicates the success of the operation. */ bool restore(FirebaseData &fbdo, uint8_t storageType, const String &nodePath, const String &fileName); /* Set maximum Firebase read/store retry operation (0 - 255) in case of network problems and buffer overflow. @param fbdo - Firebase Data Object to hold data and instances. @param num - The maximum retry. */ void setMaxRetry(FirebaseData &fbdo, uint8_t num); /* Set the maximum Firebase Error Queues in the collection (0 - 255). Firebase read/store operation causes by network problems and buffer overflow will be added to Firebase Error Queues collection. @param fbdo - Firebase Data Object to hold data and instances. @param num - The maximum Firebase Error Queues. */ void setMaxErrorQueue(FirebaseData &fbdo, uint8_t num); /* Save Firebase Error Queues as SPIFFS file (save only database store queues). Firebase read (get) operation will not be saved. @param fbdo - Firebase Data Object to hold data and instances. @param filename - Filename to be saved. @param storageType - Type of storage to save file, StorageType::SPIFS or StorageType::SD. */ bool saveErrorQueue(FirebaseData &fbdo, const String &filename, uint8_t storageType); /* Delete file in Flash (SPIFFS) or SD card. @param filename - File name to delete. @param storageType - Type of storage to save file, StorageType::SPIFS or StorageType::SD. */ bool deleteStorageFile(const String &filename, uint8_t storageType); /* Restore Firebase Error Queues from the SPIFFS file. @param fbdo - Firebase Data Object to hold data and instances. @param filename - Filename to be read and restore queues. @param storageType - Type of storage to read file, StorageType::SPIFS or StorageType::SD. */ bool restoreErrorQueue(FirebaseData &fbdo, const String &filename, uint8_t storageType); /* Determine the number of Firebase Error Queues stored in a defined SPIFFS file. @param fbdo - Firebase Data Object to hold data and instances. @param filename - Filename to be read and count for queues. @param storageType - Type of storage to read file, StorageType::SPIFS or StorageType::SD. @return Number (0-255) of queues store in defined SPIFFS file. */ uint8_t errorQueueCount(FirebaseData &fbdo, const String &filename, uint8_t storageType); /* Determine number of queues in Firebase Data object Firebase Error Queues collection. @param fbdo - Firebase Data Object to hold data and instances. @return Number (0-255) of queues in Firebase Data object queue collection. */ uint8_t errorQueueCount(FirebaseData &fbdo); /* Determine whether the Firebase Error Queues collection was full or not. @param fbdo - Firebase Data Object to hold data and instances. @return Boolean type status indicates whether the Firebase Error Queues collection was full or not. */ bool isErrorQueueFull(FirebaseData &fbdo); /* Process all failed Firebase operation queue items when the network is available. @param fbdo - Firebase Data Object to hold data and instances. @param callback - a Callback function that accepts QueueInfo parameter. */ void processErrorQueue(FirebaseData &fbdo, QueueInfoCallback callback = NULL); /* Return Firebase Error Queue ID of last Firebase Error. Return 0 if there is no Firebase Error from the last operation. @param fbdo - Firebase Data Object to hold data and instances. @return Number of Queue ID. */ uint32_t getErrorQueueID(FirebaseData &fbdo); /* Determine whether the Firebase Error Queue currently exists is Error Queue collection or not. @param fbdo - Firebase Data Object to hold data and instances. @param errorQueueID - The Firebase Error Queue ID get from getErrorQueueID. @return - Boolean type status indicates the queue existence. */ bool isErrorQueueExisted(FirebaseData &fbdo, uint32_t errorQueueID); /* Start the Firebase Error Queues Auto Run Process. @param fbdo - Firebase Data Object to hold data and instances. @param callback - a Callback function that accepts QueueInfo Object as a parameter, optional. The following functions are available from QueueInfo Object accepted by callback. queueInfo.totalQueues(), get the total Error Queues in Error Queue Collection. queueInfo.currentQueueID(), get current Error Queue ID that being process. queueInfo.isQueueFull(), determine whether Error Queue Collection is full or not. queueInfo.dataType(), get a string of the Firebase call data type that being process of current Error Queue. queueInfo.method(), get a string of the Firebase call method that being process of current Error Queue. queueInfo.path(), get a string of the Firebase call path that being process of current Error Queue. */ void beginAutoRunErrorQueue(FirebaseData &fbdo, QueueInfoCallback callback = NULL); /* Stop the Firebase Error Queues Auto Run Process. @param fbdo - Firebase Data Object to hold data and instances. */ void endAutoRunErrorQueue(FirebaseData &fbdo); /* Clear all Firbase Error Queues in Error Queue collection. @param fbdo - Firebase Data Object to hold data and instances. */ void clearErrorQueue(FirebaseData &fbdo); /* Send Firebase Cloud Messaging to the device with the first registration token which added by firebaseData.fcm.addDeviceToken. @param fbdo - Firebase Data Object to hold data and instances. @param index - The index (starts from 0) of recipient device token which added by firebaseData.fcm.addDeviceToken @return - Boolean type status indicates the success of the operation. */ bool sendMessage(FirebaseData &fbdo, uint16_t index); /* Send Firebase Cloud Messaging to all devices (multicast) which added by firebaseData.fcm.addDeviceToken. @param fbdo - Firebase Data Object to hold data and instances. @return - Boolean type status indicates the success of the operation. */ bool broadcastMessage(FirebaseData &fbdo); /* Send Firebase Cloud Messaging to devices that subscribed to the topic. @param fbdo - Firebase Data Object to hold data and instances. @return - Boolean type status indicates the success of the operation. */ bool sendTopic(FirebaseData &fbdo); void errorToString(int httpCode, std::string &buff); template <typename T> bool set(FirebaseData &fbdo, const String &path, T value); template <typename T> bool set(FirebaseData &fbdo, const String &path, T value, size_t size); template <typename T> bool set(FirebaseData &fbdo, const String &path, T value, float priority); template <typename T> bool set(FirebaseData &fbdo, const String &path, T value, size_t size, float priority); template <typename T> bool set(FirebaseData &fbdo, const String &path, T value, const String &ETag); template <typename T> bool set(FirebaseData &fbdo, const String &path, T value, size_t size, const String &ETag); template <typename T> bool set(FirebaseData &fbdo, const String &path, T value, float priority, const String &ETag); template <typename T> bool set(FirebaseData &fbdo, const String &path, T value, size_t size, float priority, const String &ETag); template <typename T> bool push(FirebaseData &fbdo, const String &path, T value); template <typename T> bool push(FirebaseData &fbdo, const String &path, T value, size_t size); template <typename T> bool push(FirebaseData &fbdo, const String &path, T value, float priority); template <typename T> bool push(FirebaseData &fbdo, const String &path, T value, size_t size, float priority); private: callback_function_t _callback_function = nullptr; bool pushInt(FirebaseData &fbdo, const std::string &path, int intValue, bool queue, const std::string &priority); bool pushFloat(FirebaseData &fbdo, const std::string &path, float floatValue, bool queue, const std::string &priority); bool pushDouble(FirebaseData &fbdo, const std::string &path, double doubleValue, bool queue, const std::string &priority); bool pushBool(FirebaseData &fbdo, const std::string &path, bool boolValue, bool queue, const std::string &priority); bool pushBlob(FirebaseData &fbdo, const std::string &path, uint8_t *blob, size_t size, bool queue, const std::string &priority); bool setInt(FirebaseData &fbdo, const std::string &path, int intValue, bool queue, const std::string &priority, const std::string &etag); bool setFloat(FirebaseData &fbdo, const std::string &path, float floatValue, bool queue, const std::string &priority, const std::string &etag); bool setDouble(FirebaseData &fbdo, const std::string &path, double doubleValue, bool queue, const std::string &priority, const std::string &etag); bool setBool(FirebaseData &fbdo, const std::string &path, bool boolValue, bool queue, const std::string &priority, const std::string &etag); bool setBlob(FirebaseData &fbdo, const std::string &path, uint8_t *blob, size_t size, bool queue, const std::string &priority, const std::string &etag); void getUrlInfo(const std::string url, std::string &host, std::string &uri, std::string &auth); bool processRequest(FirebaseData &fbdo, fb_esp_method method, fb_esp_data_type dataType, const std::string &path, const char *buff, bool queue, const std::string &priority, const std::string &etag = ""); bool processRequestFile(FirebaseData &fbdo, uint8_t storageType, fb_esp_method method, const std::string &path, const std::string &fileName, bool queue, const std::string &priority, const std::string &etag = ""); bool handleRequest(FirebaseData &fbdo, uint8_t storageType, const std::string &path, fb_esp_method method, fb_esp_data_type dataType, const std::string &payload, const std::string &priority, const std::string &etag); bool handleStreamRequest(FirebaseData &fbdo, const std::string &path); bool handleStreamRead(FirebaseData &fbdo); void parseRespHeader(const char *buf, server_response_data_t &response); void parseRespPayload(const char *buf, server_response_data_t &response, bool getOfs); void setNumDataType(const char *buf, int ofs, server_response_data_t &response, bool dec); char *getHeader(const char *buf, PGM_P beginH, PGM_P endH, int &beginPos, int endPos); bool stringCompare(const char *buf, int ofs, PGM_P beginH); int readLine(WiFiClient *stream, char *buf, int bufLen); int readChunkedData(WiFiClient *stream, char *out, int &chunkState, int &chunkedSize, int &dataLen, int bufLen); bool waitResponse(FirebaseData &fbdo); void checkOvf(FirebaseData &fbdo, size_t len, server_response_data_t &resp); bool handleResponse(FirebaseData &fbdo); void closeFileHandle(FirebaseData &fbdo); void handlePayload(FirebaseData &fbdo, server_response_data_t &response, char *payload); bool reconnect(FirebaseData &fbdo, unsigned long dataTime = 0); void delS(char *p); char *newS(size_t len); char *newS(char *p, size_t len); char *newS(char *p, size_t len, char *d); void runStreamTask(); void runErrorQueueTask(); void preparePayload(fb_esp_method method, fb_esp_data_type dataType, const std::string &priority, const std::string &payload, std::string &buf); void prepareHeader(FirebaseData &fbdo, const std::string &host, fb_esp_method method, fb_esp_data_type dataType, const std::string &path, const std::string &auth, int payloadLength, std::string &header, bool sv); void clearDataStatus(FirebaseData &fbdo); void closeHTTP(FirebaseData &fbdo); int sendRequest(FirebaseData &fbdo, const std::string &path, fb_esp_method method, fb_esp_data_type dataType, const std::string &payload, const std::string &priority); void setSecure(FirebaseData &fbdo); bool connectionError(FirebaseData &fbdo); uint8_t openErrorQueue(FirebaseData &fbdo, const String &filename, uint8_t storageType, uint8_t mode); std::vector<std::string> splitString(int size, const char *str, const char delim); char *getPGMString(PGM_P pgm); char *getFloatString(float value); char *getDoubleString(double value); char *getIntString(int value); char *getBoolString(bool value); void pgm_appendStr(std::string &buf, PGM_P p, bool empty = false); void trimDigits(char *buf); void strcat_c(char *str, char c); int strpos(const char *haystack, const char *needle, int offset); char *rstrstr(const char *haystack, const char *needle); int rstrpos(const char *haystack, const char *needle, int offset); bool sdTest(); void createDirs(std::string dirs, uint8_t storageType); bool replace(std::string &str, const std::string &from, const std::string &to); std::string base64_encode_string(const unsigned char *src, size_t len); void send_base64_encoded_stream(WiFiClient *client, const std::string &filePath, uint8_t storageType); bool base64_decode_string(const std::string src, std::vector<uint8_t> &out); bool base64_decode_file(File &file, const char *src, size_t len); bool base64_decode_flash(fs::File &file, const char *src, size_t len); uint32_t hex2int(const char *hex); bool handleFCMRequest(FirebaseData &fbdo, fb_esp_fcm_msg_type messageType); void setClock(float offset); void set_scheduled_callback(callback_function_t callback) { _callback_function = std::move([callback]() { schedule_function(callback); }); _callback_function(); } std::string _host = ""; std::string _auth = ""; std::shared_ptr<const char> _caCert = nullptr; int _certType = -1; std::string _caCertFile = ""; uint8_t _caCertFileStoreageType = StorageType::FLASH; uint16_t _port = FIREBASE_PORT; uint8_t _sdPin = SD_CS_PIN; bool _reconnectWiFi = false; bool _sdOk = false; bool _sdInUse = false; bool _clockReady = false; unsigned long _lastReconnectMillis = 0; uint16_t _reconnectTimeout = WIFI_RECONNECT_TIMEOUT; File file; fs::File _file; float _gmtOffset = 0.0; uint8_t _floatDigits = 5; uint8_t _doubleDigits = 9; }; class FirebaseData { public: FirebaseData(); ~FirebaseData(); /* Set the receive and transmit buffer memory size for secured mode BearSSL WiFi client. @param rx - The number of bytes for receive buffer memory for secured mode BearSSL (512 is minimum, 16384 is maximum). @param tx - The number of bytes for transmit buffer memory for secured mode BearSSL (512 is minimum, 16384 is maximum). Set this option to false to support get large Blob and File operations. */ void setBSSLBufferSize(uint16_t rx, uint16_t tx); /* Set the HTTP response size limit. @param len - The server response buffer size limit. */ void setResponseSize(uint16_t len); /* Pause/Unpause WiFiClient from all Firebase operations. @param pause The boolean to set/unset pause operation. @return - Boolean type status indicates the success of operation. */ bool pauseFirebase(bool pause); /* Get a WiFi client instance. @return - WiFi client instance. */ SSL_CLIENT *getWiFiClient(); /* Close the keep-alive connection of the internal WiFi client. This will release the memory used by internal WiFi client. */ void stopWiFiClient(); /* Determine the data type of payload returned from the server. @return The one of these data type e.g. integer, float, double, boolean, string, JSON and blob. */ String dataType(); /* Determine the event type of stream. @return The one of these event type e.g. put, patch, cancel, and auth_revoked. The event type "put" indicated that data at an event path relative to the stream path was completely changed. The event path can be determined by dataPath(). The event type "patch" indicated that data at the event path relative to stream path was updated. The event path can be determined by dataPath(). The event type "cancel" indicated something wrong and cancel by the server. The event type "auth_revoked" indicated the provided Firebase Authentication Data (Database secret) is no longer valid. */ String eventType(); /* Determine the unique identifier (ETag) of current data. @return String of unique identifier. */ String ETag(); /* Determine the current stream path. @return The database streaming path. */ String streamPath(); /* Determine the current data path. @return The database path which belongs to the server's returned payload. The database path returned from this function in case of stream, also changed upon the child or parent's stream value changes. */ String dataPath(); /* Determine the error reason String from the process. @return The error description string (String object). */ String errorReason(); /* Return the integer data of server returned payload. @return integer value. */ int intData(); /* Return the float data of server returned payload. @return Float value. */ float floatData(); /* Return the double data of server returned payload. @return double value. */ double doubleData(); /* Return the Boolean data of server returned payload. @return Boolean value. */ bool boolData(); /* Return the String data of server returned payload. @return String (String object). */ String stringData(); /* Return the JSON String data of server returned payload. @return String (String object). */ String jsonString(); /* Return the Firebase JSON object of server returned payload. @return FirebaseJson object. */ FirebaseJson &jsonObject(); /* Return the Firebase JSON object pointer of server returned payload. @return FirebaseJson object pointer. */ FirebaseJson *jsonObjectPtr(); /* Return the Firebase JSON Array object of server returned payload. @return FirebaseJsonArray object. */ FirebaseJsonArray &jsonArray(); /* Return the Firebase JSON Array object pointer of server returned payload. @return FirebaseJsonArray object pointer. */ FirebaseJsonArray *jsonArrayPtr(); /* Return the Firebase JSON Data object that keeps the get(parse) result. @return FirebaseJsonData object. */ FirebaseJsonData &jsonData(); /* Return the Firebase JSON Data object pointer that keeps the get(parse) result. @return FirebaseJsonData object pointer. */ FirebaseJsonData *jsonDataPtr(); /* Return the blob data (uint8_t) array of server returned payload. @return Dynamic array of 8-bit unsigned integer i.e. std::vector<uint8_t>. */ std::vector<uint8_t> blobData(); /* Return the file stream of server returned payload. @return the file stream. */ fs::File fileStream(); /* Return the new appended node's name or key of server returned payload when calling pushXXX function. @return String (String object). */ String pushName(); /* Determine the stream connection status. @return Boolean type status indicates whether the Firebase Data object is working with a stream or not. */ bool isStream(); /* Determine the server connection status. @return Boolean type status indicates whether the Firebase Data object is connected to the server or not. */ bool httpConnected(); /* Determine the timeout event of the server's stream (30 sec is the default). Nothing to do when stream connection timeout, the stream connection will be automatically resumed. @return Boolean type status indicates whether the stream was a timeout or not. */ bool streamTimeout(); /* Determine the availability of data or payload returned from the server. @return Boolean type status indicates whether the server return the new payload or not. */ bool dataAvailable(); /* Determine the availability of stream event-data payload returned from the server. @return Boolean type status indicates whether the server returns the stream event-data payload or not. */ bool streamAvailable(); /* Determine the matching between data type that intends to get from/store to database and the server's return payload data type. @return Boolean type status indicates whether the type of data being get from/store to database and the server's returned payload is matched or not. */ bool mismatchDataType(); /* Determine the HTTP status code return from the server. @return integer number of HTTP status. */ int httpCode(); /* Check the overflow of the returned payload data buffer. @return The overflow status. Total default HTTP response buffer size is 400 bytes which can be set through FirebaseData.setResponseSize. */ bool bufferOverflow(); /* Determine the name (full path) of the backup file in SD card/Flash memory. @return String (String object) of the file name that stores on SD card/Flash memory after backup operation. */ String getBackupFilename(); /* Determine the size of the backup file. @return Size of backup file in byte after backup operation. */ size_t getBackupFileSize(); /* Clear or empty data in Firebase Data object. */ void clear(); /* Determine the error description for file transferring (push file, set file, backup and restore). @return Error description string (String object). */ String fileTransferError(); /* Return the server's payload data. @return Payload string (String object). The returned String will be empty when the response data is File, BLOB, JSON and JSON Array objects. For File data type, call fileStream to get the file stream. For BLOB data type, call blobData to get the dynamic array of unsigned 8-bit data. For JSON object data type, call jsonObject and jsonObjectPtr to get the object and its pointer. For JSON Array data type, call jsonArray and jsonArrayPtr to get the object and its pointer. */ String payload(); FCMObject fcm; FirebaseESP8266HTTPClient httpClient; QueryFilter queryFilter; private: FirebaseESP8266::StreamEventCallback _dataAvailableCallback = NULL; FirebaseESP8266::MultiPathStreamEventCallback _multiPathDataCallback = NULL; FirebaseESP8266::StreamTimeoutCallback _timeoutCallback = NULL; FirebaseESP8266::QueueInfoCallback _queueInfoCallback = NULL; int _QIdx = -1; int _idx = -1; uint8_t _dataTypeNum = 0; bool _isDataTimeout = false; bool _isStream = false; bool _isFCM = false; bool _isRTDB = false; bool _streamStop = false; bool _reqNoContent = false; bool _bufOvf = false; bool _streamDataChanged = false; bool _streamPathChanged = false; bool _dataAvailable = false; bool _keepAlive = false; bool _isChunkedEnc = false; bool _httpConnected = false; bool _mismatchDataType = false; bool _pathNotExist = false; bool _pause = false; bool _classicRequest = false; fb_esp_data_type resp_dataType = fb_esp_data_type::d_any; uint8_t _connectionStatus = 0; uint32_t _qID = 0; QueueManager _qMan; uint8_t _maxAttempt = 0; fb_esp_method _req_method = fb_esp_method::m_put; fb_esp_data_type _req_dataType = fb_esp_data_type::d_any; std::string _path = ""; std::string _data = ""; std::string _data2 = ""; std::string _streamPath = ""; std::string _pushName = ""; std::string _file_transfer_error = ""; std::string _fileName = ""; std::string _redirectURL = ""; std::string _fbError = ""; std::string _eventType = ""; std::string _resp_etag = ""; std::string _req_etag = ""; std::string _priority = ""; uint8_t _storageType = 0; uint8_t _redirectCount = 0; int _redirect = 0; FirebaseJson _json; FirebaseJsonArray _jsonArr; FirebaseJsonData _jsonData; uint16_t _maxBlobSize = MAX_BLOB_PAYLOAD_SIZE; uint16_t _bsslRxSize = 512; uint16_t _bsslTxSize = 512; uint16_t _responseBufSize = 1024; unsigned long _streamTimeoutMillis = 0; unsigned long _streamReconnectMillis = 0; std::vector<uint8_t> _blob = std::vector<uint8_t>(); std::vector<std::string> _childNodeList = std::vector<std::string>(); int _httpCode = -1000; int _contentLength = 0; bool _priority_val_flag = false; bool _priority_json_flag = false; bool _shallow_flag = false; int _readTimeout = -1; std::string _writeLimit = ""; unsigned long _dataMillis = 0; std::string _backupNodePath = ""; std::string _backupDir = ""; std::string _backupFilename = ""; size_t _backupzFileSize = 0; bool handleStreamRead(); bool handleResponse(); std::string getDataType(uint8_t type); std::string getMethod(uint8_t method); void addQueue(fb_esp_method method, uint8_t storageType, fb_esp_data_type dataType, const std::string path, const std::string filename, const std::string payload, bool isQuery, int *intTarget, float *floatTarget, double *doubleTarget, bool *boolTarget, String *stringTarget, std::vector<uint8_t> *blobTarget, FirebaseJson *jsonTarget, FirebaseJsonArray *arrTarget); void clearQueueItem(QueueItem &item); void setQuery(QueryFilter &query); void clearNodeList(); void addNodeList(const String *childPath, size_t size); friend class FirebaseESP8266; friend class QueueManager; friend class StreamData; friend class FCMObject; }; class StreamData { public: StreamData(); ~StreamData(); String dataPath(); String streamPath(); int intData(); float floatData(); double doubleData(); bool boolData(); String stringData(); String jsonString(); FirebaseJson *jsonObjectPtr(); FirebaseJson &jsonObject(); FirebaseJsonArray *jsonArrayPtr(); FirebaseJsonArray &jsonArray(); FirebaseJsonData *jsonDataPtr(); FirebaseJsonData &jsonData(); std::vector<uint8_t> blobData(); File fileStream(); String dataType(); String eventType(); void empty(); FirebaseJson *_json = nullptr; FirebaseJsonArray *_jsonArr = nullptr; FirebaseJsonData *_jsonData = nullptr; private: std::string _streamPath = ""; std::string _path = ""; std::string _data = ""; std::vector<uint8_t> _blob = std::vector<uint8_t>(); std::string _dataTypeStr = ""; std::string _eventTypeStr = ""; uint8_t _dataType = 0; int _idx = -1; friend class FirebaseESP8266; }; class MultiPathStreamData { friend class FirebaseESP8266; public: MultiPathStreamData(); ~MultiPathStreamData(); bool get(const String &path); String dataPath; String value; String type; private: uint8_t _type = 0; std::string _data = ""; std::string _path = ""; std::string _typeStr = ""; FirebaseJson *_json = nullptr; void empty(); }; extern FirebaseESP8266 Firebase; #endif /* ESP8266 */ #endif /* FirebaseESP8266_H */
[ "nourmansour91@gmail.com" ]
nourmansour91@gmail.com
678fbcedafca57d7e07ac90f8155fc7b47c69ecf
c279a2fcb56de70f5cac2c8e890f155e177e676e
/Source/Plugins/GraphicsPlugins/BladeModel/source/interface_imp/ModelBatchCombiner.cc
2184e293e0e60d9611ac4f21df8db8f724aaadff
[ "MIT" ]
permissive
crazii/blade
b4abacdf36677e41382e95f0eec27d3d3baa20b5
7670a6bdf48b91c5e2dd2acd09fb644587407f03
refs/heads/master
2021-06-06T08:41:55.603532
2021-05-20T11:50:11
2021-05-20T11:50:11
160,147,322
161
34
NOASSERTION
2019-01-18T03:36:11
2018-12-03T07:07:28
C++
UTF-8
C++
false
false
7,200
cc
/******************************************************************** created: 2017/12/09 filename: ModelBatchCombiner.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include <interface/public/graphics/IGraphicsResourceManager.h> #include "ModelBatchCombiner.h" #include "ModelConfigManager.h" namespace Blade { class CombinedMeshRenderable : public IRenderable, public Allocatable { public: CombinedMeshRenderable() :mType(NULL) { mGeometry.useIndexBuffer(true); mVertexSource = IVertexSource::create(); mGeometry.mVertexSource = mVertexSource; mGeometry.mVertexDecl = ModelConfigManager::getSingleton().getCombinedBatchDeclarartion(); } /** @brief */ virtual RenderType& getRenderType() const { return *mType; } /* @describe @param @return */ virtual const GraphicsGeometry& getGeometry() const { return mGeometry; } /* @describe @param @return */ virtual const MaterialInstance* getMaterial() const { return mMaterial; } /* @describe @param @return */ virtual const Matrix44& getWorldTransform() const { return Matrix44::IDENTITY; } /** @describe get hosted content @param @return */ virtual ISpaceContent* getSpaceContent() const { return NULL; } /** @describe @param @return */ virtual const AABB& getWorldBounding() const { return mWorldAABB; } /** @brief */ inline void setup(const AABB& aab, const HMATERIALINSTANCE& material, const HIBUFFER& ib, const HVBUFFER& vb, size_t ic, size_t vc, bool hasAlpha) { mWorldAABB = aab; IGraphicsType& t = ModelConfigManager::getSingleton().getStaticModelType(hasAlpha); mType = &static_cast<RenderType&>(t); mMaterial = material; //mGeometry = geom; mVertexSource->setSource(MVSI_POSITION, vb); mIndexBuffer = ib; mGeometry.mIndexBuffer = mIndexBuffer; mGeometry.mVertexStart = 0; mGeometry.mVertexCount = (uint32)vc; mGeometry.mIndexStart = 0; mGeometry.mIndexCount = (uint32)ic; mGeometry.mInstanceCount = 0; mGeometry.mPrimitiveType = GraphicsGeometry::GPT_TRIANGLE_LIST; mGeometry.mInstanceSourceIndex = 0; } protected: AABB mWorldAABB; HIBUFFER mIndexBuffer; HVERTEXSOURCE mVertexSource; HMATERIALINSTANCE mMaterial; GraphicsGeometry mGeometry; RenderType* mType; }; ////////////////////////////////////////////////////////////////////////// ModelBatchCombiner::ModelBatchCombiner() { } ////////////////////////////////////////////////////////////////////////// ModelBatchCombiner::~ModelBatchCombiner() { } ////////////////////////////////////////////////////////////////////////// void ModelBatchCombiner::initialize() { mRenderQueue[0].bind(IRenderSchemeManager::getSingleton().createRenderQueue()); mRenderQueue[0]->initialize(static_cast<RenderType&>(ModelConfigManager::getSingleton().getStaticModelType(false))); mRenderQueue[1].bind(IRenderSchemeManager::getSingleton().createRenderQueue()); mRenderQueue[1]->initialize(static_cast<RenderType&>(ModelConfigManager::getSingleton().getStaticModelType(true))); } ////////////////////////////////////////////////////////////////////////// void ModelBatchCombiner::shutdown() { for (size_t i = 0; i < countOf(mRenderQueue); ++i) { mRenderQueue[i].clear(); for (int j = IRenderQueue::RQU_START; j < IRenderQueue::RQU_COUNT; ++j) { for (size_t k = 0; k < IRenderQueue::MAX_INDEX; ++k) mCombinedBuffers[i][j][k].clear(); } } } ////////////////////////////////////////////////////////////////////////// void ModelBatchCombiner::processRenderQueue(IRenderQueue* queue, bool alpha) { IRenderQueue::EUsage usage = queue->getUsage(); index_t index = queue->getIndex(); if (usage != IRenderQueue::RQU_SHADOW) { return; } IGraphicsResourceManager& manager = IGraphicsResourceManager::getSingleton(); index_t alphaIndex = ModelBatchCombiner::getRenderQueueIndex(alpha); CombinedBufferList& list = mCombinedBuffers[alphaIndex][usage][index]; const size_t groupCount = mRenderQueue[alphaIndex]->getGroupCount(); assert(groupCount == queue->getGroupCount()); if (list.size() < groupCount) list.resize(groupCount); for (size_t j = 0; j < groupCount; ++j) { IRenderGroup* group = mRenderQueue[alphaIndex]->getRenderGroup(j); RenderOperation* meshList = NULL; size_t count = group->getROPArray(meshList); if (count == 0) continue; CombinedBuffer& cb = list[j]; index_t indexCount = 0; index_t vertexCount = 0; for (size_t n = 0; n < count; ++n) { const SubMesh* mesh = static_cast<const SubMesh*>(meshList[n].renderable); assert(!mesh->isAnimated() && mesh->getMeshData()->mPreTransformed); const GraphicsGeometry& geom = mesh->getGeometry(); indexCount += geom.mIndexCount; vertexCount += geom.mVertexCount; } if (cb.mIndices == NULL || cb.mIndices->getIndexCount() < indexCount) cb.mIndices = manager.createIndexBuffer(NULL, IIndexBuffer::IT_32BIT, indexCount, IGraphicsBuffer::GBU_DYNAMIC_WRITE); if (cb.mVertices == NULL || cb.mVertices->getVertexCount() < vertexCount) cb.mVertices = manager.createVertexBuffer(NULL, sizeof(POINT3), vertexCount, IGraphicsBuffer::GBU_DYNAMIC_WRITE); uint32* indices = (uint32*)cb.mIndices->lock(IGraphicsBuffer::GBLF_DISCARDWRITE); POINT3* vertices = (POINT3*)cb.mVertices->lock(IGraphicsBuffer::GBLF_DISCARDWRITE); size_t voffset = 0; size_t ioffset = 0; HMATERIALINSTANCE material; AABB aab = AABB::EMPTY; bool hasAlpha = false; bool* pAlpha = NULL; for (size_t n = 0; n < count; ++n) { const SubMesh* mesh = static_cast<const SubMesh*>(meshList[n].renderable); aab.merge(mesh->getWorldBounding()); if (pAlpha == NULL) { pAlpha = &hasAlpha; hasAlpha = mesh->isTransparent(); } else assert(hasAlpha == mesh->isTransparent()); if (material == NULL) material = mesh->getMaterialInstance(); const GraphicsGeometry& geom = mesh->getGeometry(); //TODO: lock buffer conflicts with scene query { IIndexBuffer* srcIB = geom.mIndexBuffer; const void* src = srcIB->lock(IGraphicsBuffer::GBLF_READONLY); ((const char*&)src) += geom.mIndexStart * srcIB->getIndexSize(); IndexBufferHelper::copyIndices(indices + ioffset, IIndexBuffer::IT_32BIT, src, srcIB->getIndexType(), voffset, geom.mIndexCount); srcIB->unlock(); } { const HVBUFFER& srcVB = geom.mVertexSource->getBuffer(MVSI_POSITION); const POINT3* src = (const POINT3*)srcVB->lock(IGraphicsBuffer::GBLF_READONLY); std::memcpy(vertices + voffset, src + geom.mVertexStart, geom.mVertexCount*sizeof(POINT3)); voffset += geom.mVertexCount; srcVB->unlock(); } } cb.mIndices->unlock(); cb.mVertices->unlock(); if (cb.mRenderable == NULL) cb.mRenderable = BLADE_NEW CombinedMeshRenderable(); static_cast<CombinedMeshRenderable*>(cb.mRenderable)->setup(aab, material, cb.mIndices, cb.mVertices, indexCount, vertexCount, hasAlpha); queue->addRenderable(cb.mRenderable); group->clear(); } } }//namespace Blade
[ "xiaofeng.he@mihoyo.com" ]
xiaofeng.he@mihoyo.com
22c52a1dcdc6ce39551687c9dab48edac82d1f8f
a8a313bace26a863af7f21c67b5d2b1abd60951f
/Sources/Site::show_post.cpp
65d8461710199ac81eeb6d59110bf81b543f85d4
[]
no_license
IvanDerlich/ProyectoCompuI
4f45b196ad54ac83747b2958d1ee8fbe130eacc1
9e8361270a6813b9b0834e336bfdb1b65b66a4de
refs/heads/master
2021-01-12T06:41:05.509410
2017-02-16T22:08:14
2017-02-16T22:08:14
77,410,995
0
0
null
null
null
null
UTF-8
C++
false
false
403
cpp
#include <iostream> #include "Site.h" using namespace std; void Site::show_post(MAP &Post){ //imprime todas las variables post y sus respectivos valores cout<<"Debugging info:"<< endl; cout<<"<p>navegacion: "<< Post["navegacion"]<<"</p>"<<endl; cout<<"<p>flujo: "<< Post["flujo"]<<"</p>"<<endl; cout<<"<p>parametrizacion: "<< Post["parametrizacion"]<<"</p>"<<endl; cout << "<hr>"<<endl; }
[ "ivanderlich@gmail.com" ]
ivanderlich@gmail.com
a9f840d261d47574795d11a51058574cbe7f4ca4
daf5d13186d5f50660fbd4b5613c807ac8403aee
/components/service/ucloud/imageprocess/include/alibabacloud/imageprocess/ImageprocessClient.h
07e3e00ea61c6314f7e66fcbe7a557724da6361b
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
kerrylinux/alios-things
4350a2535e3682309a35472928272f324f260bf3
fcd091e6f96f054caed0ecec02aad15717fd424c
refs/heads/master
2023-03-29T06:20:55.405541
2021-03-25T10:01:39
2021-03-25T10:01:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,644
h
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIBABACLOUD_IMAGEPROCESS_IMAGEPROCESSCLIENT_H_ #define ALIBABACLOUD_IMAGEPROCESS_IMAGEPROCESSCLIENT_H_ #include <future> #include <alibabacloud/core/AsyncCallerContext.h> #include <alibabacloud/core/EndpointProvider.h> #include <alibabacloud/core/RpcServiceClient.h> #include "ImageprocessExport.h" #include "model/CalcCACSRequest.h" #include "model/CalcCACSResult.h" #include "model/ClassifyFNFRequest.h" #include "model/ClassifyFNFResult.h" #include "model/DetectCovid19CadRequest.h" #include "model/DetectCovid19CadResult.h" #include "model/DetectHipKeypointXRayRequest.h" #include "model/DetectHipKeypointXRayResult.h" #include "model/DetectKneeKeypointXRayRequest.h" #include "model/DetectKneeKeypointXRayResult.h" #include "model/DetectKneeXRayRequest.h" #include "model/DetectKneeXRayResult.h" #include "model/DetectLungNoduleRequest.h" #include "model/DetectLungNoduleResult.h" #include "model/DetectSkinDiseaseRequest.h" #include "model/DetectSkinDiseaseResult.h" #include "model/DetectSpineMRIRequest.h" #include "model/DetectSpineMRIResult.h" #include "model/GetAsyncJobResultRequest.h" #include "model/GetAsyncJobResultResult.h" #include "model/RunCTRegistrationRequest.h" #include "model/RunCTRegistrationResult.h" #include "model/RunMedQARequest.h" #include "model/RunMedQAResult.h" #include "model/TranslateMedRequest.h" #include "model/TranslateMedResult.h" namespace AlibabaCloud { namespace Imageprocess { class ALIBABACLOUD_IMAGEPROCESS_EXPORT ImageprocessClient : public RpcServiceClient { public: typedef Outcome<Error, Model::CalcCACSResult> CalcCACSOutcome; typedef std::future<CalcCACSOutcome> CalcCACSOutcomeCallable; typedef std::function<void(const ImageprocessClient*, const Model::CalcCACSRequest&, const CalcCACSOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> CalcCACSAsyncHandler; typedef Outcome<Error, Model::ClassifyFNFResult> ClassifyFNFOutcome; typedef std::future<ClassifyFNFOutcome> ClassifyFNFOutcomeCallable; typedef std::function<void(const ImageprocessClient*, const Model::ClassifyFNFRequest&, const ClassifyFNFOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> ClassifyFNFAsyncHandler; typedef Outcome<Error, Model::DetectCovid19CadResult> DetectCovid19CadOutcome; typedef std::future<DetectCovid19CadOutcome> DetectCovid19CadOutcomeCallable; typedef std::function<void(const ImageprocessClient*, const Model::DetectCovid19CadRequest&, const DetectCovid19CadOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> DetectCovid19CadAsyncHandler; typedef Outcome<Error, Model::DetectHipKeypointXRayResult> DetectHipKeypointXRayOutcome; typedef std::future<DetectHipKeypointXRayOutcome> DetectHipKeypointXRayOutcomeCallable; typedef std::function<void(const ImageprocessClient*, const Model::DetectHipKeypointXRayRequest&, const DetectHipKeypointXRayOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> DetectHipKeypointXRayAsyncHandler; typedef Outcome<Error, Model::DetectKneeKeypointXRayResult> DetectKneeKeypointXRayOutcome; typedef std::future<DetectKneeKeypointXRayOutcome> DetectKneeKeypointXRayOutcomeCallable; typedef std::function<void(const ImageprocessClient*, const Model::DetectKneeKeypointXRayRequest&, const DetectKneeKeypointXRayOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> DetectKneeKeypointXRayAsyncHandler; typedef Outcome<Error, Model::DetectKneeXRayResult> DetectKneeXRayOutcome; typedef std::future<DetectKneeXRayOutcome> DetectKneeXRayOutcomeCallable; typedef std::function<void(const ImageprocessClient*, const Model::DetectKneeXRayRequest&, const DetectKneeXRayOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> DetectKneeXRayAsyncHandler; typedef Outcome<Error, Model::DetectLungNoduleResult> DetectLungNoduleOutcome; typedef std::future<DetectLungNoduleOutcome> DetectLungNoduleOutcomeCallable; typedef std::function<void(const ImageprocessClient*, const Model::DetectLungNoduleRequest&, const DetectLungNoduleOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> DetectLungNoduleAsyncHandler; typedef Outcome<Error, Model::DetectSkinDiseaseResult> DetectSkinDiseaseOutcome; typedef std::future<DetectSkinDiseaseOutcome> DetectSkinDiseaseOutcomeCallable; typedef std::function<void(const ImageprocessClient*, const Model::DetectSkinDiseaseRequest&, const DetectSkinDiseaseOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> DetectSkinDiseaseAsyncHandler; typedef Outcome<Error, Model::DetectSpineMRIResult> DetectSpineMRIOutcome; typedef std::future<DetectSpineMRIOutcome> DetectSpineMRIOutcomeCallable; typedef std::function<void(const ImageprocessClient*, const Model::DetectSpineMRIRequest&, const DetectSpineMRIOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> DetectSpineMRIAsyncHandler; typedef Outcome<Error, Model::GetAsyncJobResultResult> GetAsyncJobResultOutcome; typedef std::future<GetAsyncJobResultOutcome> GetAsyncJobResultOutcomeCallable; typedef std::function<void(const ImageprocessClient*, const Model::GetAsyncJobResultRequest&, const GetAsyncJobResultOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> GetAsyncJobResultAsyncHandler; typedef Outcome<Error, Model::RunCTRegistrationResult> RunCTRegistrationOutcome; typedef std::future<RunCTRegistrationOutcome> RunCTRegistrationOutcomeCallable; typedef std::function<void(const ImageprocessClient*, const Model::RunCTRegistrationRequest&, const RunCTRegistrationOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> RunCTRegistrationAsyncHandler; typedef Outcome<Error, Model::RunMedQAResult> RunMedQAOutcome; typedef std::future<RunMedQAOutcome> RunMedQAOutcomeCallable; typedef std::function<void(const ImageprocessClient*, const Model::RunMedQARequest&, const RunMedQAOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> RunMedQAAsyncHandler; typedef Outcome<Error, Model::TranslateMedResult> TranslateMedOutcome; typedef std::future<TranslateMedOutcome> TranslateMedOutcomeCallable; typedef std::function<void(const ImageprocessClient*, const Model::TranslateMedRequest&, const TranslateMedOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> TranslateMedAsyncHandler; ImageprocessClient(const Credentials &credentials, const ClientConfiguration &configuration); ImageprocessClient(const std::shared_ptr<CredentialsProvider> &credentialsProvider, const ClientConfiguration &configuration); ImageprocessClient(const std::string &accessKeyId, const std::string &accessKeySecret, const ClientConfiguration &configuration); ~ImageprocessClient(); CalcCACSOutcome calcCACS(const Model::CalcCACSRequest &request)const; void calcCACSAsync(const Model::CalcCACSRequest& request, const CalcCACSAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; CalcCACSOutcomeCallable calcCACSCallable(const Model::CalcCACSRequest& request) const; ClassifyFNFOutcome classifyFNF(const Model::ClassifyFNFRequest &request)const; void classifyFNFAsync(const Model::ClassifyFNFRequest& request, const ClassifyFNFAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; ClassifyFNFOutcomeCallable classifyFNFCallable(const Model::ClassifyFNFRequest& request) const; DetectCovid19CadOutcome detectCovid19Cad(const Model::DetectCovid19CadRequest &request)const; void detectCovid19CadAsync(const Model::DetectCovid19CadRequest& request, const DetectCovid19CadAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; DetectCovid19CadOutcomeCallable detectCovid19CadCallable(const Model::DetectCovid19CadRequest& request) const; DetectHipKeypointXRayOutcome detectHipKeypointXRay(const Model::DetectHipKeypointXRayRequest &request)const; void detectHipKeypointXRayAsync(const Model::DetectHipKeypointXRayRequest& request, const DetectHipKeypointXRayAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; DetectHipKeypointXRayOutcomeCallable detectHipKeypointXRayCallable(const Model::DetectHipKeypointXRayRequest& request) const; DetectKneeKeypointXRayOutcome detectKneeKeypointXRay(const Model::DetectKneeKeypointXRayRequest &request)const; void detectKneeKeypointXRayAsync(const Model::DetectKneeKeypointXRayRequest& request, const DetectKneeKeypointXRayAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; DetectKneeKeypointXRayOutcomeCallable detectKneeKeypointXRayCallable(const Model::DetectKneeKeypointXRayRequest& request) const; DetectKneeXRayOutcome detectKneeXRay(const Model::DetectKneeXRayRequest &request)const; void detectKneeXRayAsync(const Model::DetectKneeXRayRequest& request, const DetectKneeXRayAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; DetectKneeXRayOutcomeCallable detectKneeXRayCallable(const Model::DetectKneeXRayRequest& request) const; DetectLungNoduleOutcome detectLungNodule(const Model::DetectLungNoduleRequest &request)const; void detectLungNoduleAsync(const Model::DetectLungNoduleRequest& request, const DetectLungNoduleAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; DetectLungNoduleOutcomeCallable detectLungNoduleCallable(const Model::DetectLungNoduleRequest& request) const; DetectSkinDiseaseOutcome detectSkinDisease(const Model::DetectSkinDiseaseRequest &request)const; void detectSkinDiseaseAsync(const Model::DetectSkinDiseaseRequest& request, const DetectSkinDiseaseAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; DetectSkinDiseaseOutcomeCallable detectSkinDiseaseCallable(const Model::DetectSkinDiseaseRequest& request) const; DetectSpineMRIOutcome detectSpineMRI(const Model::DetectSpineMRIRequest &request)const; void detectSpineMRIAsync(const Model::DetectSpineMRIRequest& request, const DetectSpineMRIAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; DetectSpineMRIOutcomeCallable detectSpineMRICallable(const Model::DetectSpineMRIRequest& request) const; GetAsyncJobResultOutcome getAsyncJobResult(const Model::GetAsyncJobResultRequest &request)const; void getAsyncJobResultAsync(const Model::GetAsyncJobResultRequest& request, const GetAsyncJobResultAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; GetAsyncJobResultOutcomeCallable getAsyncJobResultCallable(const Model::GetAsyncJobResultRequest& request) const; RunCTRegistrationOutcome runCTRegistration(const Model::RunCTRegistrationRequest &request)const; void runCTRegistrationAsync(const Model::RunCTRegistrationRequest& request, const RunCTRegistrationAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; RunCTRegistrationOutcomeCallable runCTRegistrationCallable(const Model::RunCTRegistrationRequest& request) const; RunMedQAOutcome runMedQA(const Model::RunMedQARequest &request)const; void runMedQAAsync(const Model::RunMedQARequest& request, const RunMedQAAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; RunMedQAOutcomeCallable runMedQACallable(const Model::RunMedQARequest& request) const; TranslateMedOutcome translateMed(const Model::TranslateMedRequest &request)const; void translateMedAsync(const Model::TranslateMedRequest& request, const TranslateMedAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; TranslateMedOutcomeCallable translateMedCallable(const Model::TranslateMedRequest& request) const; private: std::shared_ptr<EndpointProvider> endpointProvider_; }; } } #endif // !ALIBABACLOUD_IMAGEPROCESS_IMAGEPROCESSCLIENT_H_
[ "noreply@github.com" ]
noreply@github.com
fc9e263dc00d05764fddbd4ef1fc716b81d63d44
e2459f679460f6c957f09e17b8544316481831ad
/Algorithmic Problems/hw3/main.cpp
e78fb1b2ea29eabc1c26a0d4a6ec8d3c6ab0aad8
[]
no_license
Matyxus/CPP
462c2ea6d7064ebc948df88250a06570ec539b2b
aa0409f7e25496043856f37f77be90c6dd59fb81
refs/heads/master
2023-07-06T18:33:15.110271
2023-07-01T13:51:21
2023-07-01T13:51:21
338,757,161
0
0
null
null
null
null
UTF-8
C++
false
false
5,823
cpp
#include <iostream> #include <vector> #include <queue> #include <assert.h> #define ROUTER 0 #define VALIDATOR 1 #define EXTRACTOR 2 // Check hw3_image for graphical representation of second test case (.in file). /* Every working station is connected with exactly one computer, which is always ROUTER Every ROUTER is connected with 2 or 3 computers. There is atlease one router connectd with two computers. For every two computers A, B: exists exactly one sequence of different computers P_1...P_n (n ≥ 2), where A=P_1, B=P_n and P_1 is connected with P_(i+1) (i = 1,...,n-1). Given topology of computer network, list of EXTRACTORs and VALIDATORs, find maximal number of pairs EXTRACTOR-VALIDATOR, that can be paired. */ typedef struct node { int id; int type = ROUTER; std::vector<int> connections; node* left = nullptr; node* right = nullptr; node* parent = nullptr; node (int index) { id = index; } } node; class graph { private: int search = 0; int pairs = 0; int P = 0; // number of computers int S = 0; // number of pairs connected by cable int E = 0; // number of extractors int V = 0; // number of validators node* root = NULL; std::vector<node*> nodes; std::vector<std::pair<int, int>> to_remove; public: graph() {} ~graph() { for (unsigned int i = 0; i < nodes.size(); i++) { delete nodes[i]; } } inline void getInt(int &n) { n = 0; int ch = getchar(); // if the input character is not a digit while (ch < '0' || ch > '9') { ch = getchar(); } while (ch >= '0' && ch <= '9') { n = (n << 3) + (n << 1) + ch - '0'; //multiply by 10 ch = getchar(); } } void init() { scanf("%d %d %d %d", &P, &S, &E, &V); for (int i = 0; i < P; i++) { nodes.push_back(new node(i)); } int j, k; for (int i = 0; i < S; i++) { getInt(j); getInt(k); nodes[j-1]->connections.push_back(k-1); nodes[k-1]->connections.push_back(j-1); } for (int i = 0; i < E; i++) { getInt(j); nodes[j-1]->type = EXTRACTOR; } for (int i = 0; i < V; i++) { getInt(j); nodes[j-1]->type = VALIDATOR; } // find first router, that has 2 connections, guaranteed to be with routers int i = 0; for (; i < P; i++) { if (nodes[i]->connections.size() == 2) { break; } } // Construct binary tree. root = nodes[i]; root->left = nodes[root->connections[0]]; root->right = nodes[root->connections[1]]; NodeImpl(nodes[root->connections[0]], root); NodeImpl(nodes[root->connections[1]], root); // Remove unwanted. for (auto const &pair : to_remove) { if (nodes[pair.first]->left->id == pair.second) { nodes[pair.first]->left = nodes[pair.first]->right; nodes[pair.first]->right = nullptr; } else { nodes[pair.first]->right = nullptr; } } explore(root); // Find solution. printf("%d\n", pairs); } void NodeImpl(node* ptr, node* parent) { ptr->parent = parent; if (ptr->connections.size() == 1) { ptr->left = nullptr; ptr->right = nullptr; if (ptr->type == ROUTER) { to_remove.push_back({parent->id, ptr->id}); } return; } else { int index_left; int index_right; if (ptr->connections[0] != parent->id) { index_left = ptr->connections[0]; } else { index_left = ptr->connections[1]; } ptr->left = nodes[index_left]; assert(ptr->left != nullptr); NodeImpl(nodes[index_left], ptr); if (ptr->connections.size() == 2) { ptr->right = nullptr; } else { if (ptr->connections[2] != parent->id) { index_right = ptr->connections[2]; } else { index_right = ptr->connections[1]; } ptr->right = nodes[index_right]; assert(ptr->right != nullptr); NodeImpl(nodes[index_right], ptr); } } } int explore(node* ptr) { // ending node, Extracor or Validator, return its type if (ptr->connections.size() == 1) { return ptr->type; } int type1 = 0, type2 = 0; int ret_val = 0; if (ptr->left != nullptr) { type1 = explore(ptr->left); } if (ptr->right != nullptr) { type2 = explore(ptr->right); } // Compare types if (type1+type2 == EXTRACTOR+VALIDATOR) { // Extractor == 1, Validator == 2 -> 3 pairs++; ret_val = 0; } else { // return found type ret_val = (type1 == 0) ? type2:type1; } return ret_val; } }; int main() { graph g; g.init(); return 0; }
[ "maty.svadlenka@seznam.cz" ]
maty.svadlenka@seznam.cz