blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8a2cf2d70916dd3b4441b8148015022324ef5dde | 6072b1458e1bad2e9595fff4f62af42a44958f81 | /coverinfodialog.h | 2be3b0e777d2e835039c1221209112a914480ede | [] | no_license | longchaopei/CopyNetworkConfig | c8e16b7b9d4ff8fa9a0e0712ea1dbfb09ab09b7c | 3eae002582d4bcea6c65481f9a81737d44b929b4 | refs/heads/master | 2021-01-20T04:18:38.809651 | 2017-04-18T17:35:24 | 2017-04-18T17:35:24 | 89,675,705 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 968 | h | #ifndef COVERINFODIALOG_H
#define COVERINFODIALOG_H
#include <QDialog>
#include "datatype.h"
class TableModel;
class QStandardItem;
namespace Ui {
class CoverInfoDialog;
}
class CoverInfoDialog : public QDialog
{
Q_OBJECT
public:
explicit CoverInfoDialog(QWidget *parent = 0);
~CoverInfoDialog();
private slots:
void appendRow(const COUNTRY_INFO before, const COUNTRY_INFO after);
void clearTable();
void openWindow();
void updateVerticalScrollBar(int value);
private:
void initView();
void initBeforeTableview();
void initAfterTableview();
void beforeTableAppendRow(const COUNTRY_INFO before);
void afterTableAppendRow(const COUNTRY_INFO after);
bool initItems(QList<QStandardItem*> &items, const COUNTRY_INFO info);
int mRowCount;
TableModel* mBeforeModel;
TableModel* mAfterModel;
Ui::CoverInfoDialog *ui;
};
#endif // COVERINFODIALOG_H
| [
"1784857911@qq.com"
] | 1784857911@qq.com |
1cee7e7629c24be4b367ad4359739436a7cea693 | c60e4f97890cc7329123d18fd5bc55734815caa5 | /3rd/xulrunner-sdk/include/nsIDOMHTMLStyleElement.h | 13b40d607d285b4a30b73b6bb433b34e9229e896 | [
"Apache-2.0"
] | permissive | ShoufuLuo/csaw | cbdcd8d51bb7fc4943e66b82ee7bc9c25ccbc385 | 0d030d5ab93e61b62dff10b27a15c83fcfce3ff3 | refs/heads/master | 2021-01-19T10:02:51.209070 | 2014-04-30T19:53:32 | 2014-04-30T19:53:32 | 16,976,394 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,009 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/rel-m-rel-xr-osx64-bld/build/dom/interfaces/html/nsIDOMHTMLStyleElement.idl
*/
#ifndef __gen_nsIDOMHTMLStyleElement_h__
#define __gen_nsIDOMHTMLStyleElement_h__
#ifndef __gen_nsIDOMHTMLElement_h__
#include "nsIDOMHTMLElement.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIDOMHTMLStyleElement */
#define NS_IDOMHTMLSTYLEELEMENT_IID_STR "675aff34-07c5-491f-b92f-ccaf616ef8b3"
#define NS_IDOMHTMLSTYLEELEMENT_IID \
{0x675aff34, 0x07c5, 0x491f, \
{ 0xb9, 0x2f, 0xcc, 0xaf, 0x61, 0x6e, 0xf8, 0xb3 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMHTMLStyleElement : public nsIDOMHTMLElement {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMHTMLSTYLEELEMENT_IID)
/* attribute boolean disabled; */
NS_SCRIPTABLE NS_IMETHOD GetDisabled(PRBool *aDisabled) = 0;
NS_SCRIPTABLE NS_IMETHOD SetDisabled(PRBool aDisabled) = 0;
/* attribute DOMString media; */
NS_SCRIPTABLE NS_IMETHOD GetMedia(nsAString & aMedia) = 0;
NS_SCRIPTABLE NS_IMETHOD SetMedia(const nsAString & aMedia) = 0;
/* attribute DOMString type; */
NS_SCRIPTABLE NS_IMETHOD GetType(nsAString & aType) = 0;
NS_SCRIPTABLE NS_IMETHOD SetType(const nsAString & aType) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMHTMLStyleElement, NS_IDOMHTMLSTYLEELEMENT_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMHTMLSTYLEELEMENT \
NS_SCRIPTABLE NS_IMETHOD GetDisabled(PRBool *aDisabled); \
NS_SCRIPTABLE NS_IMETHOD SetDisabled(PRBool aDisabled); \
NS_SCRIPTABLE NS_IMETHOD GetMedia(nsAString & aMedia); \
NS_SCRIPTABLE NS_IMETHOD SetMedia(const nsAString & aMedia); \
NS_SCRIPTABLE NS_IMETHOD GetType(nsAString & aType); \
NS_SCRIPTABLE NS_IMETHOD SetType(const nsAString & aType);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMHTMLSTYLEELEMENT(_to) \
NS_SCRIPTABLE NS_IMETHOD GetDisabled(PRBool *aDisabled) { return _to GetDisabled(aDisabled); } \
NS_SCRIPTABLE NS_IMETHOD SetDisabled(PRBool aDisabled) { return _to SetDisabled(aDisabled); } \
NS_SCRIPTABLE NS_IMETHOD GetMedia(nsAString & aMedia) { return _to GetMedia(aMedia); } \
NS_SCRIPTABLE NS_IMETHOD SetMedia(const nsAString & aMedia) { return _to SetMedia(aMedia); } \
NS_SCRIPTABLE NS_IMETHOD GetType(nsAString & aType) { return _to GetType(aType); } \
NS_SCRIPTABLE NS_IMETHOD SetType(const nsAString & aType) { return _to SetType(aType); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMHTMLSTYLEELEMENT(_to) \
NS_SCRIPTABLE NS_IMETHOD GetDisabled(PRBool *aDisabled) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDisabled(aDisabled); } \
NS_SCRIPTABLE NS_IMETHOD SetDisabled(PRBool aDisabled) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetDisabled(aDisabled); } \
NS_SCRIPTABLE NS_IMETHOD GetMedia(nsAString & aMedia) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetMedia(aMedia); } \
NS_SCRIPTABLE NS_IMETHOD SetMedia(const nsAString & aMedia) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetMedia(aMedia); } \
NS_SCRIPTABLE NS_IMETHOD GetType(nsAString & aType) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetType(aType); } \
NS_SCRIPTABLE NS_IMETHOD SetType(const nsAString & aType) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetType(aType); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsDOMHTMLStyleElement : public nsIDOMHTMLStyleElement
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMHTMLSTYLEELEMENT
nsDOMHTMLStyleElement();
private:
~nsDOMHTMLStyleElement();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMHTMLStyleElement, nsIDOMHTMLStyleElement)
nsDOMHTMLStyleElement::nsDOMHTMLStyleElement()
{
/* member initializers and constructor code */
}
nsDOMHTMLStyleElement::~nsDOMHTMLStyleElement()
{
/* destructor code */
}
/* attribute boolean disabled; */
NS_IMETHODIMP nsDOMHTMLStyleElement::GetDisabled(PRBool *aDisabled)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsDOMHTMLStyleElement::SetDisabled(PRBool aDisabled)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute DOMString media; */
NS_IMETHODIMP nsDOMHTMLStyleElement::GetMedia(nsAString & aMedia)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsDOMHTMLStyleElement::SetMedia(const nsAString & aMedia)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute DOMString type; */
NS_IMETHODIMP nsDOMHTMLStyleElement::GetType(nsAString & aType)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsDOMHTMLStyleElement::SetType(const nsAString & aType)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIDOMHTMLStyleElement_h__ */
| [
"luoshoufu@gmail.com"
] | luoshoufu@gmail.com |
bad70bafec8ef3adc83bfc75747d84d3e7d96866 | 5468c8df91fba33676aa392f5b110508d8be976e | /LogicLib/ServerHost.cpp | 9cab1de2ab50ac35844fd393fe7a4608dc4058e1 | [] | no_license | highfence/ChattingServerProject | 2ae47ddab30bbaaffe96c902fa2817ee97b79a31 | 63a186963282ea54d328184bc5350b23eebec77c | refs/heads/master | 2020-12-02T11:06:45.135809 | 2017-07-14T15:55:43 | 2017-07-14T15:55:43 | 96,062,150 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,161 | cpp | #include <thread>
#include <chrono>
#include "../NetworkLib/ServerNetErrorCode.h"
#include "../NetworkLib/Define.h"
#include "../NetworkLib/TcpNetwork.h"
#include "ConsoleLogger.h"
#include "LobbyManager.h"
#include "PacketProcess.h"
#include "UserManager.h"
#include "ServerHost.h"
using LOG_TYPE = NetworkLib::LOG_TYPE;
using NET_ERROR_CODE = NetworkLib::NET_ERROR_CODE;
namespace LogicLib
{
ServerHost::ServerHost() {}
ServerHost::~ServerHost()
{
release();
}
ERROR_CODE ServerHost::Init()
{
_logger = std::make_unique<ConsoleLog>();
loadConfig();
_network = std::make_unique<NetworkLib::TcpNetwork>();
auto result = _network->Init(_serverConfig.get(), _logger.get());
if (result != NET_ERROR_CODE::NONE)
{
_logger->Write(LOG_TYPE::L_ERROR, "%s | Init Fail. NetErrorCode(%s)", __FUNCTION__, (short)result);
return ERROR_CODE::ServerHost_INIT_NETWORK_INIT_FAIL;
}
_userMgr = std::make_unique<UserManager>();
_userMgr->Init(_serverConfig->MaxClientCount);
_lobbyMgr = std::make_unique<LobbyManager>();
_lobbyMgr->Init({ _serverConfig->MaxLobbyCount,
_serverConfig->MaxLobbyUserCount,
_serverConfig->MaxRoomCountByLobby,
_serverConfig->MaxRoomUserCount },
_network.get(), _logger.get());
_packetProc = std::make_unique<PacketProcess>();
_packetProc->Init(_network.get(), _userMgr.get(), _lobbyMgr.get(), _serverConfig.get(), _logger.get());
_isRun = true;
_logger->Write(LOG_TYPE::L_INFO, "%s | Init Success. Server Run", __FUNCTION__);
return ERROR_CODE::NONE;
}
void ServerHost::release()
{
if (_network)
{
_network->Release();
}
}
void ServerHost::Stop()
{
_isRun = false;
}
void ServerHost::Run()
{
while (_isRun)
{
while (true)
{
auto packetInfo = _network->GetPacketInfo();
if (packetInfo.PacketId == 0)
{
break;
}
else
{
_packetProc->Process(packetInfo);
}
if (_network->IsPacketTaskRemaining())
{
continue;
}
WaitForSingleObject(_processEvent, 1);
ResetEvent(_processEvent);
}
_packetProc->StateCheck();
}
}
ERROR_CODE ServerHost::loadConfig()
{
_serverConfig = std::make_unique<NetworkLib::ServerConfig>();
wchar_t sPath[MAX_PATH] = { 0, };
::GetCurrentDirectory(MAX_PATH, sPath);
wchar_t inipath[MAX_PATH] = { 0, };
_snwprintf_s(inipath, _countof(inipath), _TRUNCATE, L"%s\\ServerConfig.ini", sPath);
_serverConfig->Port = (unsigned short)GetPrivateProfileInt(L"Config", L"Port", 0, inipath);
_serverConfig->BackLogCount = GetPrivateProfileInt(L"Config", L"BackLogCount", 0, inipath);
_serverConfig->MaxClientCount = GetPrivateProfileInt(L"Config", L"MaxClientCount", 0, inipath);
_serverConfig->MaxClientSockOptRecvBufferSize = (short)GetPrivateProfileInt(L"Config", L"MaxClientSockOptRecvBufferSize", 0, inipath);
_serverConfig->MaxClientSockOptSendBufferSize = (short)GetPrivateProfileInt(L"Config", L"MaxClientSockOptSendBufferSize", 0, inipath);
_serverConfig->MaxClientRecvBufferSize = (short)GetPrivateProfileInt(L"Config", L"MaxClientRecvBufferSize", 0, inipath);
_serverConfig->MaxClientSendBufferSize = (short)GetPrivateProfileInt(L"Config", L"MaxClientSendBufferSize", 0, inipath);
_serverConfig->IsLoginCheck = GetPrivateProfileInt(L"Config", L"IsLoginCheck", 0, inipath) == 1 ? true : false;
_serverConfig->ExtraClientCount = GetPrivateProfileInt(L"Config", L"ExtraClientCount", 0, inipath);
_serverConfig->MaxLobbyCount = GetPrivateProfileInt(L"Config", L"MaxLobbyCount", 0, inipath);
_serverConfig->MaxLobbyUserCount = GetPrivateProfileInt(L"Config", L"MaxLobbyUserCount", 0, inipath);
_serverConfig->MaxRoomCountByLobby = GetPrivateProfileInt(L"Config", L"MaxRoomCountByLobby", 0, inipath);
_serverConfig->MaxRoomUserCount = GetPrivateProfileInt(L"Config", L"MaxRoomUserCount", 0, inipath);
_logger->Write(NetworkLib::LOG_TYPE::L_INFO, "%s | Port(%d), Backlog(%d)", __FUNCTION__, _serverConfig->Port, _serverConfig->BackLogCount);
_logger->Write(NetworkLib::LOG_TYPE::L_INFO, "%s | IsLoginCheck(%d)", __FUNCTION__, _serverConfig->IsLoginCheck);
return ERROR_CODE::NONE;
}
} | [
"highfence@naver.com"
] | highfence@naver.com |
5176b032bbbf4d9455c63f925fc6d9f820d845a3 | d56fdd6d9d16bdba48d54c2c8df31e32be50c909 | /运算符重载两个复数类操作/运算符重载两个复数类操作/main.cpp | baf025bb7a41515c80cc1e1ee0de8c438e3d0564 | [] | no_license | KoreHuang/CPPfolder | 1a2512e53c5d57a7b0049083d64ed872e735c692 | e5f06b5970d667a63545cd9d9fcf01c32af662f9 | refs/heads/master | 2020-04-05T10:39:24.651340 | 2017-07-17T02:02:01 | 2017-07-17T02:02:01 | 81,519,646 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 704 | cpp | //
// main.cpp
// 运算符重载两个复数类操作
//
// Created by mac on 16/4/17.
// Copyright © 2016年 mac. All rights reserved.
//
#include <iostream>
using namespace std;
class complex{
public:
double imag,real;
complex(double i=0,double r=0):real(r),imag(i){}
~complex(){};
};
complex operator+(complex a,complex b){
return complex(a.imag+b.imag,a.real+b.real);
}
int main(int argc, const char * argv[]) {
// insert code here...
//std::cout << "Hello, World!\n";
complex obj1(1.1,1.1);
complex obj2(2.2,2.2);
complex obj3;
obj3=obj1+obj2;
cout<<"This two complex addly reasult is:"<<obj3.real<<"+"<<obj3.imag<<"i"<<endl;
return 0;
}
| [
"huangke7296@foxmail.com"
] | huangke7296@foxmail.com |
32c0b0f11a79367150f2a15d14fc911c354b4d4d | 7ef1a3023df63a424dc38f840671da7c3dd65d79 | /source/sympp/node/function/cosh.h | 171095d9b80a50e7178e0f278d4ef8829e63e9e8 | [
"MIT"
] | permissive | alandefreitas/sympp | 6815f7b8e768b29e732e88eb46216458ae2393ff | f8f0249de72355f513d0b9e61300eef715ca8895 | refs/heads/master | 2023-01-29T04:54:55.464616 | 2020-09-29T06:48:25 | 2020-09-29T06:48:25 | 299,464,590 | 12 | 2 | MIT | 2020-10-20T21:47:52 | 2020-09-29T00:35:52 | C++ | UTF-8 | C++ | false | false | 1,587 | h | //
// Created by Alan Freitas on 18/09/20.
//
#ifndef SYMPP_COSH_H
#define SYMPP_COSH_H
#include <sympp/core/sym.h>
#include <sympp/node/function/function_interface.h>
namespace sympp {
class cosh : public function_interface {
public:
cosh(const cosh &);
explicit cosh(const sym &);
/// Move constructor
cosh(cosh &&) noexcept;
~cosh() override;
public /* implement node interface */:
[[nodiscard]] double
evaluate(const std::vector<uint8_t> &bool_values,
const std::vector<int> &int_values,
const std::vector<double> &double_values) const override;
[[nodiscard]] sym
evaluate_sym(const std::vector<uint8_t> &bool_values,
const std::vector<int> &int_values,
const std::vector<double> &double_values) const override;
[[nodiscard]] node_lambda lambdify() const override;
void c_code(int &function_level, int &sum_level, int &prod_level,
bool &leaf, std::stack<std::string> &code_aux,
std::string &code) const override;
public /* override node interface */:
public /* override internal node interface */:
[[nodiscard]] const std::type_info &type() const override;
[[nodiscard]] node_interface *clone() const override;
public /* override function interface */:
std::optional<sym> simplify(double ratio,
complexity_lambda func) override;
};
} // namespace sympp
#endif // SYMPP_COSH_H
| [
"alandefreitas@gmail.com"
] | alandefreitas@gmail.com |
de59a0908a126cada7a32bc80733d8f1fe8364be | 12ceca2646c1a1fcc399bfaa17368426fad3d6a1 | /Command/ICommand.cpp | 69bd54e044487d81bbb2a989fac2b7179202fc3c | [] | no_license | AInsolence/DesignPatterns | e725338db4cd10a36a231692a5fa396cb6bf0b68 | 34de288b60d2679e8d7d2c2cfa2f75a4d16d11a8 | refs/heads/master | 2021-09-12T08:20:01.235167 | 2018-04-14T16:27:53 | 2018-04-14T16:27:53 | 115,539,217 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177 | cpp | #include "ICommand.h"
ICommand::ICommand()
{
}
ICommand::~ICommand()
{
}
void ICommand::undo()
{
//override this method if you want undo functionality for the command;
}
| [
"antonpythondev@gmail.com"
] | antonpythondev@gmail.com |
d6db43137398ebdb0255b13bf0d769b13fc59921 | 9d1d93f1165dc25d90b7bef17d03b1dbd642bb49 | /Chapter 4/strtype4.cpp | ccaebe73fa7bc386328e9f13bd1b25a67d4b0477 | [] | no_license | LiangXuanhan/C- | d7f99a134f398494f727a0b002c60897c0ca7f79 | a114d0df6ab6738648bb72923cb63a9d0b115aae | refs/heads/master | 2021-10-09T08:59:52.558490 | 2018-12-25T04:22:45 | 2018-12-25T04:22:45 | 113,460,269 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 971 | cpp | // strtype4.cpp -- line input
#include <iostream>
#include <string> // make string class available
#include <cstring> // C-style string library
int main()
{
using namespace std;
char charr3[20];
string str;
cout << "Length of string in charr before input: "
<< strlen(charr3) << endl;
cout << "Length of string in str before input: "
<< str.size() << endl;
// cout << charr3 <<endl;
cout << "Enter a line of text:\n";
cin.getline(charr3, 20); // indicate maximum length
cout << "You entered: " << charr3 << endl;
cout << "Enter another line of text:\n";
getline(cin, str); // cin now an argument; no length specifier
cout << "You entered: " << str << endl;
cout << "Length of string in charr after input: "
<< strlen(charr3) << endl;
cout << "Length of string in str after input: "
<< str.size() << endl;
cin.get();
return 0;
}
| [
"liangxuanhan@126.com"
] | liangxuanhan@126.com |
ae2cc20a6c3a6635a476c30c8233277f05145c3c | dd7f3d248173d8b660c57471f13c0fcb306d7f55 | /day19.cpp | 58ee64f4492f26df5e9a786de74a0459ea1c597a | [] | no_license | MrSimbax/Advent_Of_Code_2020 | e3d1d511f3c63c26cfe8b3b7b4d5a3ded4c10d3a | 39fb6196d4f2310f40118417cb59730aca777585 | refs/heads/main | 2023-02-06T01:51:14.690896 | 2020-12-25T08:40:14 | 2020-12-25T08:40:14 | 319,066,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,461 | cpp | #include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <cctype>
#include <array>
#include <numeric>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <memory>
using Int = long long int;
struct ValidatorResult
{
std::string::const_iterator newMsgBegin;
bool isMessageValid;
};
struct Rule
{
Int index;
std::vector<std::vector<Int>> subrules;
char character{0};
ValidatorResult isMessageValid(std::string::const_iterator msgBegin, std::string::const_iterator msgEnd,
const std::vector<Rule>& rules) const
{
if (msgBegin == msgEnd)
return {msgEnd, false};
if (!subrules.empty())
{
for (const auto& subrule : subrules)
{
bool subruleValidationSuccessful = true;
std::string::const_iterator it = msgBegin;
for (const auto rule : subrule)
{
const auto& result = rules[rule].isMessageValid(it, msgEnd, rules);
if (!result.isMessageValid)
{
subruleValidationSuccessful = false;
break;
}
else
{
it = result.newMsgBegin;
}
}
if (subruleValidationSuccessful)
{
return {it, subruleValidationSuccessful};
}
}
return {msgEnd, false};
}
else
{
return {msgBegin + 1, *msgBegin == character};
}
}
};
Rule loadRule(const std::string& line)
{
Rule rule{};
std::istringstream iss{line};
iss >> rule.index;
std::string str;
iss >> str; // :
std::vector<Int> subrule;
while (iss >> str)
{
if (str == "|")
{
rule.subrules.push_back(subrule);
subrule.clear();
}
else if (str[0] == '"')
{
rule.character = str[1];
}
else
{
subrule.push_back(std::stoll(str));
}
}
if (!subrule.empty())
{
rule.subrules.push_back(subrule);
}
return rule;
}
struct Input
{
std::vector<Rule> rules;
std::vector<std::string> messages;
};
Input loadInput(const std::string& filename)
{
std::ifstream ifs{filename};
Input input{};
std::string line;
while (std::getline(ifs, line) && !line.empty())
input.rules.push_back(loadRule(line));
std::sort(input.rules.begin(), input.rules.end(),
[](const Rule& a, const Rule& b) { return a.index < b.index; });
while (std::getline(ifs, line))
input.messages.push_back(line);
return input;
}
Int part1(const Input& input)
{
return std::count_if(input.messages.begin(), input.messages.end(),
[&input](const std::string& msg)
{
const auto& result = input.rules[0].isMessageValid(msg.begin(), msg.end(), input.rules);
return result.isMessageValid && result.newMsgBegin == msg.end();
});
}
int main()
{
auto input = loadInput("day19.txt");
std::cout << "part 1: " << part1(input) << std::endl;
}
| [
"matt@przybyl.io"
] | matt@przybyl.io |
2f06c9b7ea28f6f8de408e8f3c87e34e9878daf3 | 46a609ae37d3f93cd5aeb98308ea8abfdf4785d2 | /item/CursorArea.h | 978585674166e0b24f7e31b2c8d593f65d6f5705 | [] | no_license | leiyuming/Components-qt4 | 96c1c990b4cc4e6cf0a62963fe33860713d6312b | b0be68a599039f9b2d86541c3e4c98c369a1e377 | refs/heads/master | 2021-01-19T06:43:22.178866 | 2016-06-22T10:46:14 | 2016-06-22T10:46:14 | 61,711,252 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,716 | h | /****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Components project on Qt Labs.
**
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions contained
** in the Technology Preview License Agreement accompanying this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
****************************************************************************/
#ifndef CURSORAREA_H
#define CURSORAREA_H
#include <QDeclarativeItem>
class CursorArea : public QDeclarativeItem
{
Q_OBJECT
Q_PROPERTY(Qt::CursorShape cursor READ cursor WRITE setCursor NOTIFY cursorChanged)
public:
explicit CursorArea(QDeclarativeItem *parent = 0);
void setCursor(Qt::CursorShape cursor);
Qt::CursorShape cursor() const { return m_cursor; }
signals:
void cursorChanged();
private:
Qt::CursorShape m_cursor;
};
QML_DECLARE_TYPE(CursorArea)
#endif // CURSORAREA_H
| [
"leiyuming@zjmedia.com"
] | leiyuming@zjmedia.com |
c3c83f9f405ec0d2bcce9836bb67146b29cc28b4 | f8c766a29f45bc05eca58004cc2c38d265afd848 | /concurrent/GuardedThread.hpp | 0a65798119e866d0a9693775d33c27a262058d83 | [
"MIT"
] | permissive | codetalks-new/learn-cpp | 36b59bf681623845c8da4e9754b67efb4117f371 | ec91c2cfba70c4c5aad52898f97e5bd2d35d9d8b | refs/heads/master | 2023-01-01T05:05:28.389552 | 2020-10-25T01:14:38 | 2020-10-25T01:14:38 | 230,690,644 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 187 | hpp | #pragma once
#include <thread>
class GuardedThread : std::thread {
public:
using std::thread::thread;
~GuardedThread() {
if (this->joinable()) {
this->join();
}
}
}; | [
"banxi1988@gmail.com"
] | banxi1988@gmail.com |
9cd5bef99cfaa7be8868b4e1a1ffe101e6748cd9 | 45711d378b4d9a677bdc15948ade07dcbb49a186 | /test/hm3/geometry/square.cpp | b275bdbbf9b71fd3e6ca21df6262b3a1797a51e4 | [
"BSL-1.0"
] | permissive | gnzlbg/hm3 | 1978c70abd4dcee6f194474cca4e87c22366834e | 8c254d0ca96b9b379e4af3264e2dd431792ae076 | refs/heads/master | 2023-08-18T21:05:08.549131 | 2015-10-26T23:50:34 | 2015-10-26T23:50:34 | 44,331,524 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,199 | cpp | /// \file
///
/// Geometry square tests
#include <hm3/geometry/square.hpp>
#include <hm3/utility/test.hpp>
using namespace hm3;
#define UNWRAP(...) __VA_ARGS__
#define CHECK_UNIT_SQUARE(nd_, pL_, pR_, xc_, corners_) \
do { \
using namespace geometry; \
static constexpr uint_t nd = nd_; \
constexpr auto pL = point<nd> UNWRAP pL_; \
constexpr auto pR = point<nd> UNWRAP pR_; \
\
constexpr auto xc = point<nd> UNWRAP xc_; \
constexpr auto len = 1.; \
\
const auto s1 = square<nd>{pL, pR}; \
constexpr auto s2 = square<nd>{xc, len}; \
\
constexpr auto s3 = s2; \
square<nd> s4; \
s4 = s3; \
\
constexpr auto s5 = square<nd>{xc, len + 1.}; \
\
CHECK(s1 == s2); \
CHECK(s1 != s5); \
\
const auto s1_xc = center(s1); \
constexpr auto s2_xc = center(s2); \
\
const auto s1_v = volume(s1); \
constexpr auto s2_v = volume(s2); \
\
static_assert(dimension(s1) == nd, ""); \
static_assert(dimension(s2) == dimension(s1), ""); \
static_assert(dimension(s2) == dimension(s3), ""); \
\
static_assert(length(s2) == 1., ""); \
CHECK(math::approx(length(s1), 1.)); \
\
CHECK(s2_xc() == xc()); \
CHECK(s1_xc() == xc()); \
\
CHECK(math::approx(s1_v, 1.)); \
static_assert(s2_v == 1., ""); \
\
constexpr std::array<point<nd>, math::ipow(2_u, nd)> corners{ \
{UNWRAP corners_}}; \
CHECK(size(corners) == size(geometry::corners(s1))); \
\
CHECK(equal(corners, geometry::corners(s1), [](auto i, auto j) { \
return equal(i, j, \
[](auto xi, auto xj) { return math::approx(xi, xj); }); \
})); \
} while (false)
int main() {
CHECK_UNIT_SQUARE(1, ({0.}), ({1.}), ({0.5}), ({0.}, {1.}));
CHECK_UNIT_SQUARE(2, ({0., 0.}), ({1., 1.}), ({0.5, 0.5}),
({0., 0.}, {1., 0.}, {1., 1.}, {0., 1.}));
CHECK_UNIT_SQUARE(3, ({0., 0., 0.}), ({1., 1., 1.}), ({0.5, 0.5, 0.5}),
({0., 0., 0.}, {1., 0., 0.}, {1., 1., 0.}, {0., 1., 0.},
{0., 0., 1.}, {1., 0., 1.}, {1., 1., 1.}, {0., 1., 1.}));
#define CHECK_CORNER_POS(p, v0, v1, v2) \
static_assert(geometry::relative_corner_position(p, 0) == (v0), ""); \
static_assert(geometry::relative_corner_position(p, 1) == (v1), ""); \
static_assert(geometry::relative_corner_position(p, 2) == (v2), ""); \
CHECK(equal(geometry::relative_corner_position<3>(p), \
geometry::point<3>{{(v0), (v1), (v2)}}, \
[](auto i, auto j) { return math::approx(i, j); }))
CHECK_CORNER_POS(0, -1, -1, -1);
CHECK_CORNER_POS(1, +1, -1, -1);
CHECK_CORNER_POS(2, +1, +1, -1);
CHECK_CORNER_POS(3, -1, +1, -1);
CHECK_CORNER_POS(4, -1, -1, +1);
CHECK_CORNER_POS(5, +1, -1, +1);
CHECK_CORNER_POS(6, +1, +1, +1);
CHECK_CORNER_POS(7, -1, +1, +1);
return test::result();
}
| [
"gonzalobg88@gmail.com"
] | gonzalobg88@gmail.com |
36bf1bfe86ac13c524896e83750dbb0e18c43000 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /third_party/skia/src/effects/SkTileImageFilter.cpp | a140db216b744e75058b3c6fe167a724933251fd | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"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 | 5,332 | cpp | /*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTileImageFilter.h"
#include "SkCanvas.h"
#include "SkImage.h"
#include "SkMatrix.h"
#include "SkOffsetImageFilter.h"
#include "SkPaint.h"
#include "SkReadBuffer.h"
#include "SkShader.h"
#include "SkSpecialImage.h"
#include "SkSpecialSurface.h"
#include "SkSurface.h"
#include "SkValidationUtils.h"
#include "SkWriteBuffer.h"
sk_sp<SkImageFilter> SkTileImageFilter::Make(const SkRect& srcRect, const SkRect& dstRect,
sk_sp<SkImageFilter> input) {
if (!SkIsValidRect(srcRect) || !SkIsValidRect(dstRect)) {
return nullptr;
}
if (srcRect.width() == dstRect.width() && srcRect.height() == dstRect.height()) {
SkRect ir = dstRect;
if (!ir.intersect(srcRect)) {
return input;
}
CropRect cropRect(ir);
return SkOffsetImageFilter::Make(dstRect.x() - srcRect.x(),
dstRect.y() - srcRect.y(),
std::move(input),
&cropRect);
}
return sk_sp<SkImageFilter>(new SkTileImageFilter(srcRect, dstRect, std::move(input)));
}
sk_sp<SkSpecialImage> SkTileImageFilter::onFilterImage(SkSpecialImage* source,
const Context& ctx,
SkIPoint* offset) const {
SkIPoint inputOffset = SkIPoint::Make(0, 0);
sk_sp<SkSpecialImage> input(this->filterInput(0, source, ctx, &inputOffset));
if (!input) {
return nullptr;
}
SkRect dstRect;
ctx.ctm().mapRect(&dstRect, fDstRect);
if (!dstRect.intersect(SkRect::Make(ctx.clipBounds()))) {
return nullptr;
}
const SkIRect dstIRect = dstRect.roundOut();
if (!fSrcRect.width() || !fSrcRect.height() || !dstIRect.width() || !dstIRect.height()) {
return nullptr;
}
SkRect srcRect;
ctx.ctm().mapRect(&srcRect, fSrcRect);
SkIRect srcIRect;
srcRect.roundOut(&srcIRect);
srcIRect.offset(-inputOffset);
const SkIRect inputBounds = SkIRect::MakeWH(input->width(), input->height());
if (!SkIRect::Intersects(srcIRect, inputBounds)) {
return nullptr;
}
// We create an SkImage here b.c. it needs to be a tight fit for the tiling
sk_sp<SkImage> subset;
if (inputBounds.contains(srcIRect)) {
subset = input->makeTightSubset(srcIRect);
if (!subset) {
return nullptr;
}
} else {
sk_sp<SkSurface> surf(input->makeTightSurface(ctx.outputProperties(), srcIRect.size()));
if (!surf) {
return nullptr;
}
SkCanvas* canvas = surf->getCanvas();
SkASSERT(canvas);
SkPaint paint;
paint.setBlendMode(SkBlendMode::kSrc);
input->draw(canvas,
SkIntToScalar(inputOffset.x()), SkIntToScalar(inputOffset.y()),
&paint);
subset = surf->makeImageSnapshot();
}
SkASSERT(subset->width() == srcIRect.width());
SkASSERT(subset->height() == srcIRect.height());
sk_sp<SkSpecialSurface> surf(source->makeSurface(ctx.outputProperties(), dstIRect.size()));
if (!surf) {
return nullptr;
}
SkCanvas* canvas = surf->getCanvas();
SkASSERT(canvas);
SkPaint paint;
paint.setBlendMode(SkBlendMode::kSrc);
paint.setShader(subset->makeShader(SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
canvas->translate(-dstRect.fLeft, -dstRect.fTop);
canvas->drawRect(dstRect, paint);
offset->fX = dstIRect.fLeft;
offset->fY = dstIRect.fTop;
return surf->makeImageSnapshot();
}
SkIRect SkTileImageFilter::onFilterNodeBounds(const SkIRect& src, const SkMatrix& ctm,
MapDirection direction) const {
SkRect rect = kReverse_MapDirection == direction ? fSrcRect : fDstRect;
ctm.mapRect(&rect);
return rect.roundOut();
}
SkIRect SkTileImageFilter::onFilterBounds(const SkIRect& src, const SkMatrix&, MapDirection) const {
// Don't recurse into inputs.
return src;
}
SkRect SkTileImageFilter::computeFastBounds(const SkRect& src) const {
return fDstRect;
}
sk_sp<SkFlattenable> SkTileImageFilter::CreateProc(SkReadBuffer& buffer) {
SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1);
SkRect src, dst;
buffer.readRect(&src);
buffer.readRect(&dst);
return Make(src, dst, common.getInput(0));
}
void SkTileImageFilter::flatten(SkWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writeRect(fSrcRect);
buffer.writeRect(fDstRect);
}
#ifndef SK_IGNORE_TO_STRING
void SkTileImageFilter::toString(SkString* str) const {
str->appendf("SkTileImageFilter: (");
str->appendf("src: %.2f %.2f %.2f %.2f",
fSrcRect.fLeft, fSrcRect.fTop, fSrcRect.fRight, fSrcRect.fBottom);
str->appendf(" dst: %.2f %.2f %.2f %.2f",
fDstRect.fLeft, fDstRect.fTop, fDstRect.fRight, fDstRect.fBottom);
if (this->getInput(0)) {
str->appendf("input: (");
this->getInput(0)->toString(str);
str->appendf(")");
}
str->append(")");
}
#endif
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
df07286ecd41a1ece931929da3496226f2b4a00f | d670eb969f362257294bc49184962a3f47badcbf | /include/thursday.h | c45feab30584778e69af255934e504ac570f05a8 | [] | no_license | Augustine129/primers-portfolio-Augustine129 | 8aac3fcb5494f175f44038a4594685c7b6a3975b | 39e7e33263ac395407dfb92061002970545ee414 | refs/heads/main | 2023-08-23T21:55:25.260281 | 2021-08-22T23:04:48 | 2021-08-22T23:04:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 179 | h | void sleepTimer(void) {
std::cout << " - sleepTimer: not yet implemented\n\n";
}
void joinDetachThreads(void) {
std::cout << " - joinDetachThreads: not yet implemented\n\n";
} | [
"66690702+github-classroom[bot]@users.noreply.github.com"
] | 66690702+github-classroom[bot]@users.noreply.github.com |
1fdfc5101d75885e7e508ace793d887efbdad500 | c96686863f5fa03a45efaefc0ab5ca415e24b4a4 | /EjemploSerial/Master/Master.ino | f2280e1ae083460cbbb600bd283283caac7a89ff | [] | no_license | amartinb/MiDesarrolloArduino | 96a9400f0a40d92e1d571db1ed2729d0cb5e37e1 | 16ba0e76dba0e171d2e64a7932f3a886baeb0fe1 | refs/heads/master | 2021-01-20T19:05:13.854012 | 2016-06-22T15:03:16 | 2016-06-22T15:03:16 | 61,728,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,440 | ino | // Programa del Arduino 1 (transmisor) Maestro
// En mi caso el Arduino 1 es el Nano v3 conectado al usb
const int boton2 = 2; // pin 2 conectado al pulsador (conectado a masa y una resistencia+5v)
const int led9 = 9; // pin 9 conectado a un led + resistencia +GND
// variable que cambiara:
int estadoBoton = 0; // variable para ver el estado del boton
int contador = 0; // cuando sea 2 paso b
void setup()
{
Serial.begin(9600); // Inicia la velocidad de transmision para Tx y Rx
pinMode(led9, OUTPUT); // pin 9 (led) modo SALIDA
pinMode(boton2, INPUT); // pin 2 (boton) modo ENTRADA
}
void loop()
{
// lee si el pulsador esta suelto 0 o pulsado 1
estadoBoton = digitalRead(boton2);
if (estadoBoton == HIGH)
{ // si el boton ha sido pulsado:
digitalWrite(led9, HIGH); // encendemos el led
if (contador == 2){
Serial.print('b'); // envío 'b' para blinking
contador = 0;
} else
{
Serial.print('a'); // Enviamos 'a' por Tx (puerto serie)
contador += 1;
}
delay(500); // Retardo de 0,5 s
}
else
{ // si el boton no ha sido pulsado
digitalWrite(led9, LOW); // apagamos el led
Serial.print('o'); // Enviamos 'o' (OFF) por Tx
delay(500); // Retardo de 0,5s
}
}
| [
"AMARTIN"
] | AMARTIN |
d879da4ef2fa41b91869240dbbb1ec5ba8d02c1d | f66ca7e6d96638d129c73e4dab57223ee57bd7fe | /p74/p74.cpp | f3023dc1bdb51cc32d5f0a9d5dadbf71e523a019 | [
"MIT"
] | permissive | suzyz/leetcode_practice | e4a5ab30b60318dc087452daef7dab51727d396a | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | refs/heads/master | 2021-01-19T01:17:49.194902 | 2019-01-12T13:27:56 | 2019-01-12T13:27:56 | 95,619,304 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,140 | cpp | class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int n = matrix.size();
if (n == 0)
return false;
int m = matrix[0].size();
if (m == 0)
return false;
int st = 0, en = n-1;
while (st < en)
{
int mid = st + ((en-st)>>1);
if (matrix[mid][0] == target)
return true;
else
if (matrix[mid][0] > target)
en = mid;
else
{ // matrix[mid][0] < target
if (matrix[mid][m-1] == target)
return true;
else
if (matrix[mid][m-1] > target)
st = en = mid;
else
st = mid + 1;
}
}
if (matrix[st][0] > target || matrix[st][m-1] < target)
return false;
int l = 0, r = m-1;
while (l <= r)
{
int mid = l + ((r-l)>>1);
if (matrix[st][mid] == target)
return true;
else
if (matrix[st][mid] < target)
l = mid+1;
else
r = mid-1;
}
return false;
}
};
| [
"suzyzhang0@gmail.com"
] | suzyzhang0@gmail.com |
22516de166410f5aa892bd6e37b6ca2c4450f68c | 73bd731e6e755378264edc7a7b5d16132d023b6a | /CodeForces/CodeForces - 1333A.cpp | f609d5737c561f508e2f7aaf9526054f365063a9 | [] | no_license | IHR57/Competitive-Programming | 375e8112f7959ebeb2a1ed6a0613beec32ce84a5 | 5bc80359da3c0e5ada614a901abecbb6c8ce21a4 | refs/heads/master | 2023-01-24T01:33:02.672131 | 2023-01-22T14:34:31 | 2023-01-22T14:34:31 | 163,381,483 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,086 | cpp | //BISMILLAHIR RAHMANIR RAHIM
#include <bits/stdc++.h>
#define mem(a, b) (memset(a, b, sizeof(a)))
#define pb push_back
#define mk make_pair
#define ff first
#define ss second
#define PI acos(-1)
#define INF 2147483647
#define MOD 1000000007
#define MAX 100005
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef pair<int, ii> pii;
typedef vector<ii> vii;
typedef priority_queue<int,vector<int>,greater<int> > PQ;
int Set(int mask, int pos){return mask = mask | (1<<pos);}
bool check(int mask, int pos){return (bool)(mask & (1<<pos));}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int test;
cin>>test;
while(test--){
int n, m;
cin>>n>>m;
cout<<"W";
for(int i = 1; i <= n; i++) {
for(int j = (i == 1) ? 2 : 1; j <= m; j++) {
cout<<"B";
}
cout<<endl;
}
}
return 0;
} | [
"iqbalhrasel95@gmail.com"
] | iqbalhrasel95@gmail.com |
366c32cfc187c10a1809332c7355c178de1cc1de | 1518b89cac3afff7ed7c4cd48ca25574d8357d75 | /src/rpc/misc.cpp | 3a46765248888df0c3bc1b8c975ecd5f20a1aed3 | [
"MIT"
] | permissive | HelioNetwork/Helio | b036c488d0b276783ee909be9ce4805aff966cab | af6bd585231fd54dbbc6570369c8b0cdaef7c6f0 | refs/heads/master | 2022-12-26T03:48:33.305335 | 2020-10-08T05:31:26 | 2020-10-08T05:31:26 | 302,241,086 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 31,379 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2020 The PIVX developers
// Copyright (c) 2020 The Helio Coin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "clientversion.h"
#include "httpserver.h"
#include "init.h"
#include "main.h"
#include "masternode-sync.h"
#include "net.h"
#include "netbase.h"
#include "rpc/server.h"
#include "spork.h"
#include "timedata.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#include "wallet/walletdb.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include <univalue.h>
extern std::vector<CSporkDef> sporkDefs;
/**
* @note Do not add or change anything in the information returned by this
* method. `getinfo` exists for backwards-compatibility only. It combines
* information from wildly different sources in the program, which is a mess,
* and is thus planned to be deprecated eventually.
*
* Based on the source of the information, new information should be added to:
* - `getblockchaininfo`,
* - `getnetworkinfo` or
* - `getwalletinfo`
*
* Or alternatively, create a specific query method for the information.
**/
UniValue getinfo(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getinfo\n"
"\nReturns an object containing various state info.\n"
"\nResult:\n"
"{\n"
" \"version\": xxxxx, (numeric) the server version\n"
" \"protocolversion\": xxxxx, (numeric) the protocol version\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total helio balance of the wallet\n"
" \"staking status\": true|false, (boolean) if the wallet is staking or not\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"timeoffset\": xxxxx, (numeric) the time offset\n"
" \"connections\": xxxxx, (numeric) the number of connections\n"
" \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"testnet\": true|false, (boolean) if the server is using testnet or not\n"
" \"moneysupply\" : \"supply\" (numeric) The money supply when this block was added to the blockchain\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
" \"paytxfee\": x.xxxx, (numeric) the transaction fee set in helio/kb\n"
" \"relayfee\": x.xxxx, (numeric) minimum relay fee for non-free transactions in helio/kb\n"
" \"errors\": \"...\" (string) any error messages\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getinfo", "") + HelpExampleRpc("getinfo", ""));
#ifdef ENABLE_WALLET
LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL);
#else
LOCK(cs_main);
#endif
std::string services;
for (int i = 0; i < 8; i++) {
uint64_t check = 1 << i;
if (nLocalServices & check) {
switch (check) {
case NODE_NETWORK:
services+= "NETWORK/";
break;
case NODE_BLOOM:
case NODE_BLOOM_WITHOUT_MN:
services+= "BLOOM/";
break;
default:
services+= "UNKNOWN/";
}
}
}
proxyType proxy;
GetProxy(NET_IPV4, proxy);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("version", CLIENT_VERSION));
obj.push_back(Pair("protocolversion", PROTOCOL_VERSION));
obj.push_back(Pair("services", services));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("staking status", (pwalletMain->pStakerStatus->IsActive() ?
"Staking Active" :
"Staking Not Active")));
}
#endif
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("timeoffset", GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string())));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", Params().NetworkID() == CBaseChainParams::TESTNET));
// During inital block verification chainActive.Tip() might be not yet initialized
if (chainActive.Tip() == NULL) {
obj.push_back(Pair("status", "Blockchain information not yet available"));
return obj;
}
obj.push_back(Pair("moneysupply",ValueFromAmount(nMoneySupply)));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
size_t kpExternalSize = pwalletMain->KeypoolCountExternalKeys();
obj.push_back(Pair("keypoolsize", (int64_t)kpExternalSize));
}
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
#endif
obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
UniValue mnsync(const JSONRPCRequest& request)
{
std::string strMode;
if (request.params.size() == 1)
strMode = request.params[0].get_str();
if (request.fHelp || request.params.size() != 1 || (strMode != "status" && strMode != "reset")) {
throw std::runtime_error(
"mnsync \"status|reset\"\n"
"\nReturns the sync status or resets sync.\n"
"\nArguments:\n"
"1. \"mode\" (string, required) either 'status' or 'reset'\n"
"\nResult ('status' mode):\n"
"{\n"
" \"IsBlockchainSynced\": true|false, (boolean) 'true' if blockchain is synced\n"
" \"lastMasternodeList\": xxxx, (numeric) Timestamp of last MN list message\n"
" \"lastMasternodeWinner\": xxxx, (numeric) Timestamp of last MN winner message\n"
" \"lastBudgetItem\": xxxx, (numeric) Timestamp of last MN budget message\n"
" \"lastFailure\": xxxx, (numeric) Timestamp of last failed sync\n"
" \"nCountFailures\": n, (numeric) Number of failed syncs (total)\n"
" \"sumMasternodeList\": n, (numeric) Number of MN list messages (total)\n"
" \"sumMasternodeWinner\": n, (numeric) Number of MN winner messages (total)\n"
" \"sumBudgetItemProp\": n, (numeric) Number of MN budget messages (total)\n"
" \"sumBudgetItemFin\": n, (numeric) Number of MN budget finalization messages (total)\n"
" \"countMasternodeList\": n, (numeric) Number of MN list messages (local)\n"
" \"countMasternodeWinner\": n, (numeric) Number of MN winner messages (local)\n"
" \"countBudgetItemProp\": n, (numeric) Number of MN budget messages (local)\n"
" \"countBudgetItemFin\": n, (numeric) Number of MN budget finalization messages (local)\n"
" \"RequestedMasternodeAssets\": n, (numeric) Status code of last sync phase\n"
" \"RequestedMasternodeAttempt\": n, (numeric) Status code of last sync attempt\n"
"}\n"
"\nResult ('reset' mode):\n"
"\"status\" (string) 'success'\n"
"\nExamples:\n" +
HelpExampleCli("mnsync", "\"status\"") + HelpExampleRpc("mnsync", "\"status\""));
}
if (strMode == "status") {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("IsBlockchainSynced", masternodeSync.IsBlockchainSynced()));
obj.push_back(Pair("lastMasternodeList", masternodeSync.lastMasternodeList));
obj.push_back(Pair("lastMasternodeWinner", masternodeSync.lastMasternodeWinner));
obj.push_back(Pair("lastBudgetItem", masternodeSync.lastBudgetItem));
obj.push_back(Pair("lastFailure", masternodeSync.lastFailure));
obj.push_back(Pair("nCountFailures", masternodeSync.nCountFailures));
obj.push_back(Pair("sumMasternodeList", masternodeSync.sumMasternodeList));
obj.push_back(Pair("sumMasternodeWinner", masternodeSync.sumMasternodeWinner));
obj.push_back(Pair("sumBudgetItemProp", masternodeSync.sumBudgetItemProp));
obj.push_back(Pair("sumBudgetItemFin", masternodeSync.sumBudgetItemFin));
obj.push_back(Pair("countMasternodeList", masternodeSync.countMasternodeList));
obj.push_back(Pair("countMasternodeWinner", masternodeSync.countMasternodeWinner));
obj.push_back(Pair("countBudgetItemProp", masternodeSync.countBudgetItemProp));
obj.push_back(Pair("countBudgetItemFin", masternodeSync.countBudgetItemFin));
obj.push_back(Pair("RequestedMasternodeAssets", masternodeSync.RequestedMasternodeAssets));
obj.push_back(Pair("RequestedMasternodeAttempt", masternodeSync.RequestedMasternodeAttempt));
return obj;
}
if (strMode == "reset") {
masternodeSync.Reset();
return "success";
}
return "failure";
}
#ifdef ENABLE_WALLET
class DescribeAddressVisitor : public boost::static_visitor<UniValue>
{
private:
isminetype mine;
public:
DescribeAddressVisitor(isminetype mineIn) : mine(mineIn) {}
UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); }
UniValue operator()(const CKeyID &keyID) const {
UniValue obj(UniValue::VOBJ);
CPubKey vchPubKey;
obj.push_back(Pair("isscript", false));
if (bool(mine & ISMINE_ALL)) {
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
}
return obj;
}
UniValue operator()(const CScriptID &scriptID) const {
UniValue obj(UniValue::VOBJ);
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)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
UniValue a(UniValue::VARR);
for (const CTxDestination& addr : addresses)
a.push_back(EncodeDestination(addr));
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
#endif
/*
Used for updating/reading spork settings on the network
*/
UniValue spork(const JSONRPCRequest& request)
{
if (request.params.size() == 1 && request.params[0].get_str() == "show") {
UniValue ret(UniValue::VOBJ);
for (const auto& sporkDef : sporkDefs) {
ret.push_back(Pair(sporkDef.name, sporkManager.GetSporkValue(sporkDef.sporkId)));
}
return ret;
} else if (request.params.size() == 1 && request.params[0].get_str() == "active") {
UniValue ret(UniValue::VOBJ);
for (const auto& sporkDef : sporkDefs) {
ret.push_back(Pair(sporkDef.name, sporkManager.IsSporkActive(sporkDef.sporkId)));
}
return ret;
} else if (request.params.size() == 2) {
// advanced mode, update spork values
SporkId nSporkID = sporkManager.GetSporkIDByName(request.params[0].get_str());
if (nSporkID == SPORK_INVALID) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid spork name");
}
// SPORK VALUE
int64_t nValue = request.params[1].get_int64();
//broadcast new spork
if (sporkManager.UpdateSpork(nSporkID, nValue)) {
return "success";
} else {
return "failure";
}
}
throw std::runtime_error(
"spork \"name\" ( value )\n"
"\nReturn spork values or their active state.\n"
"\nArguments:\n"
"1. \"name\" (string, required) \"show\" to show values, \"active\" to show active state.\n"
" When set up as a spork signer, the name of the spork can be used to update it's value.\n"
"2. value (numeric, required when updating a spork) The new value for the spork.\n"
"\nResult (show):\n"
"{\n"
" \"spork_name\": nnn (key/value) Key is the spork name, value is it's current value.\n"
" ,...\n"
"}\n"
"\nResult (active):\n"
"{\n"
" \"spork_name\": true|false (key/value) Key is the spork name, value is a boolean for it's active state.\n"
" ,...\n"
"}\n"
"\nResult (name):\n"
" \"success|failure\" (string) Whether or not the update succeeded.\n"
"\nExamples:\n" +
HelpExampleCli("spork", "show") + HelpExampleRpc("spork", "show"));
}
UniValue validateaddress(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"validateaddress \"helioaddress\"\n"
"\nReturn information about the given helio address.\n"
"\nArguments:\n"
"1. \"helioaddress\" (string, required) The helio address to validate\n"
"\nResult:\n"
"{\n"
" \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
" \"address\" : \"helioaddress\", (string) The helio address validated\n"
" \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\n"
" \"ismine\" : true|false, (boolean) If the address is yours or not\n"
" \"isstaking\" : true|false, (boolean) If the address is a staking address for Helio_Coin cold staking\n"
" \"iswatchonly\" : true|false, (boolean) If the address is watchonly\n"
" \"isscript\" : true|false, (boolean) If the key is a script\n"
" \"hex\" : \"hex\", (string, optional) The redeemscript for the P2SH address\n"
" \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n"
" \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
" \"account\" : \"account\" (string) DEPRECATED. The account associated with the address, \"\" is the default account\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"") + HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\""));
#ifdef ENABLE_WALLET
LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL);
#else
LOCK(cs_main);
#endif
std::string currentAddress = request.params[0].get_str();
bool isStakingAddress = false;
CTxDestination dest = DecodeDestination(currentAddress, isStakingAddress);
bool isValid = IsValidDestination(dest);
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("isvalid", isValid));
if (isValid) {
ret.push_back(Pair("address", currentAddress));
CScript scriptPubKey = GetScriptForDestination(dest);
ret.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
#ifdef ENABLE_WALLET
isminetype mine = pwalletMain ? IsMine(*pwalletMain, dest) : ISMINE_NO;
ret.push_back(Pair("ismine", bool(mine & (ISMINE_SPENDABLE_ALL | ISMINE_COLD))));
ret.push_back(Pair("isstaking", isStakingAddress));
ret.push_back(Pair("iswatchonly", bool(mine & ISMINE_WATCH_ONLY)));
UniValue detail = boost::apply_visitor(DescribeAddressVisitor(mine), dest);
ret.pushKVs(detail);
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest].name));
#endif
}
return ret;
}
/**
* Used by addmultisigaddress / createmultisig:
*/
CScript _createmultisig_redeemScript(const UniValue& params)
{
int nRequired = params[0].get_int();
const UniValue& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw std::runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw std::runtime_error(
strprintf("not enough keys supplied "
"(got %u keys, but need at least %d to redeem)",
keys.size(), nRequired));
if (keys.size() > 16)
throw std::runtime_error("Number of addresses involved in the multisignature address creation > 16\nReduce the number");
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++) {
const std::string& ks = keys[i].get_str();
#ifdef ENABLE_WALLET
// Case 1: Helio_Coin address and we have full public key:
CTxDestination dest = DecodeDestination(ks);
if (pwalletMain && IsValidDestination(dest)) {
const CKeyID* keyID = boost::get<CKeyID>(&dest);
if (!keyID) {
throw std::runtime_error(
strprintf("%s does not refer to a key", ks));
}
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(*keyID, vchPubKey))
throw std::runtime_error(
strprintf("no full public key for address %s", ks));
if (!vchPubKey.IsFullyValid())
throw std::runtime_error(" Invalid public key: " + ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else
#endif
if (IsHex(ks)) {
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw std::runtime_error(" Invalid public key: " + ks);
pubkeys[i] = vchPubKey;
} else {
throw std::runtime_error(" Invalid public key: " + ks);
}
}
CScript result = GetScriptForMultisig(nRequired, pubkeys);
if (result.size() > MAX_SCRIPT_ELEMENT_SIZE)
throw std::runtime_error(
strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE));
return result;
}
UniValue createmultisig(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 2 || request.params.size() > 2)
throw std::runtime_error(
"createmultisig nrequired [\"key\",...]\n"
"\nCreates a multi-signature address with n signature of m keys required.\n"
"It returns a json object with the address and redeemScript.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keys\" (string, required) A json array of keys which are helio addresses or hex-encoded public keys\n"
" [\n"
" \"key\" (string) helio address or hex-encoded public key\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"{\n"
" \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
" \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
"}\n"
"\nExamples:\n"
"\nCreate a multisig address from 2 addresses\n" +
HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
"\nAs a json rpc call\n" +
HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\""));
// Construct using pay-to-script-hash:
CScript inner = _createmultisig_redeemScript(request.params);
CScriptID innerID(inner);
UniValue result(UniValue::VOBJ);
result.push_back(Pair("address", EncodeDestination(innerID)));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
UniValue verifymessage(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 3)
throw std::runtime_error(
"verifymessage \"helioaddress\" \"signature\" \"message\"\n"
"\nVerify a signed message\n"
"\nArguments:\n"
"1. \"helioaddress\" (string, required) The helio address to use for the signature.\n"
"2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
"3. \"message\" (string, required) The message that was signed.\n"
"\nResult:\n"
"true|false (boolean) If the signature is verified or not.\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n" +
HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n" +
HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") +
"\nVerify the signature\n" +
HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") +
"\nAs json rpc\n" +
HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"signature\", \"my message\""));
LOCK(cs_main);
std::string strAddress = request.params[0].get_str();
std::string strSign = request.params[1].get_str();
std::string strMessage = request.params[2].get_str();
CTxDestination destination = DecodeDestination(strAddress);
if (!IsValidDestination(destination))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
const CKeyID* keyID = boost::get<CKeyID>(&destination);
if (!keyID) {
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
}
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == *keyID);
}
UniValue setmocktime(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"setmocktime timestamp\n"
"\nSet the local time to given timestamp (-regtest only)\n"
"\nArguments:\n"
"1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n"
" Pass 0 to go back to using the system time.");
if (!Params().IsRegTestNet())
throw std::runtime_error("setmocktime for regression testing (-regtest mode) only");
LOCK(cs_main);
RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VNUM));
SetMockTime(request.params[0].get_int64());
return NullUniValue;
}
void EnableOrDisableLogCategories(UniValue cats, bool enable) {
cats = cats.get_array();
for (unsigned int i = 0; i < cats.size(); ++i) {
std::string cat = cats[i].get_str();
bool success;
if (enable) {
success = g_logger->EnableCategory(cat);
} else {
success = g_logger->DisableCategory(cat);
}
if (!success)
throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
}
}
UniValue logging(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 2) {
throw std::runtime_error(
"logging [include,...] <exclude>\n"
"Gets and sets the logging configuration.\n"
"When called without an argument, returns the list of categories that are currently being debug logged.\n"
"When called with arguments, adds or removes categories from debug logging.\n"
"The valid logging categories are: " + ListLogCategories() + "\n"
"libevent logging is configured on startup and cannot be modified by this RPC during runtime."
"Arguments:\n"
"1. \"include\" (array of strings) add debug logging for these categories.\n"
"2. \"exclude\" (array of strings) remove debug logging for these categories.\n"
"\nResult: <categories> (string): a list of the logging categories that are active.\n"
"\nExamples:\n"
+ HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
+ HelpExampleRpc("logging", "[\"all\"], \"[libevent]\"")
);
}
uint32_t original_log_categories = g_logger->GetCategoryMask();
if (request.params.size() > 0 && request.params[0].isArray()) {
EnableOrDisableLogCategories(request.params[0], true);
}
if (request.params.size() > 1 && request.params[1].isArray()) {
EnableOrDisableLogCategories(request.params[1], false);
}
uint32_t updated_log_categories = g_logger->GetCategoryMask();
uint32_t changed_log_categories = original_log_categories ^ updated_log_categories;
// Update libevent logging if BCLog::LIBEVENT has changed.
// If the library version doesn't allow it, UpdateHTTPServerLogging() returns false,
// in which case we should clear the BCLog::LIBEVENT flag.
// Throw an error if the user has explicitly asked to change only the libevent
// flag and it failed.
if (changed_log_categories & BCLog::LIBEVENT) {
if (!UpdateHTTPServerLogging(g_logger->WillLogCategory(BCLog::LIBEVENT))) {
g_logger->DisableCategory(BCLog::LIBEVENT);
if (changed_log_categories == BCLog::LIBEVENT) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "libevent logging cannot be updated when using libevent before v2.1.1.");
}
}
}
UniValue result(UniValue::VOBJ);
std::vector<CLogCategoryActive> vLogCatActive = ListActiveLogCategories();
for (const auto& logCatActive : vLogCatActive) {
result.pushKV(logCatActive.category, logCatActive.active);
}
return result;
}
#ifdef ENABLE_WALLET
UniValue getstakingstatus(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getstakingstatus\n"
"\nReturns an object containing various staking information.\n"
"\nResult:\n"
"{\n"
" \"staking_status\": true|false, (boolean) whether the wallet is staking or not\n"
" \"staking_enabled\": true|false, (boolean) whether staking is enabled/disabled in helio.conf\n"
" \"coldstaking_enabled\": true|false, (boolean) whether cold-staking is enabled/disabled in helio.conf\n"
" \"haveconnections\": true|false, (boolean) whether network connections are present\n"
" \"mnsync\": true|false, (boolean) whether the required masternode/spork data is synced\n"
" \"walletunlocked\": true|false, (boolean) whether the wallet is unlocked\n"
" \"stakeablecoins\": n (numeric) number of stakeable UTXOs\n"
" \"stakingbalance\": d (numeric) HLO value of the stakeable coins (minus reserve balance, if any)\n"
" \"stakesplitthreshold\": d (numeric) value of the current threshold for stake split\n"
" \"lastattempt_age\": n (numeric) seconds since last stake attempt\n"
" \"lastattempt_depth\": n (numeric) depth of the block on top of which the last stake attempt was made\n"
" \"lastattempt_hash\": xxx (hex string) hash of the block on top of which the last stake attempt was made\n"
" \"lastattempt_coins\": n (numeric) number of stakeable coins available during last stake attempt\n"
" \"lastattempt_tries\": n (numeric) number of stakeable coins checked during last stake attempt\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getstakingstatus", "") + HelpExampleRpc("getstakingstatus", ""));
if (!pwalletMain)
throw JSONRPCError(RPC_IN_WARMUP, "Try again after active chain is loaded");
{
LOCK2(cs_main, &pwalletMain->cs_wallet);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("staking_status", pwalletMain->pStakerStatus->IsActive()));
obj.push_back(Pair("staking_enabled", GetBoolArg("-staking", true)));
bool fColdStaking = GetBoolArg("-coldstaking", true);
obj.push_back(Pair("coldstaking_enabled", fColdStaking));
obj.push_back(Pair("haveconnections", !vNodes.empty()));
obj.push_back(Pair("mnsync", !masternodeSync.NotCompleted()));
obj.push_back(Pair("walletunlocked", !pwalletMain->IsLocked()));
std::vector<COutput> vCoins;
pwalletMain->StakeableCoins(&vCoins);
obj.push_back(Pair("stakeablecoins", (int)vCoins.size()));
obj.push_back(Pair("stakingbalance", ValueFromAmount(pwalletMain->GetStakingBalance(fColdStaking))));
obj.push_back(Pair("stakesplitthreshold", ValueFromAmount(pwalletMain->nStakeSplitThreshold)));
CStakerStatus* ss = pwalletMain->pStakerStatus;
if (ss) {
obj.push_back(Pair("lastattempt_age", (int)(GetTime() - ss->GetLastTime())));
obj.push_back(Pair("lastattempt_depth", (chainActive.Height() - ss->GetLastHeight())));
obj.push_back(Pair("lastattempt_hash", ss->GetLastHash().GetHex()));
obj.push_back(Pair("lastattempt_coins", ss->GetLastCoins()));
obj.push_back(Pair("lastattempt_tries", ss->GetLastTries()));
}
return obj;
}
}
#endif // ENABLE_WALLET
| [
"72230497+HelioNetwork@users.noreply.github.com"
] | 72230497+HelioNetwork@users.noreply.github.com |
1880244195ee080d32b5fb9b07b8a115a028387b | 430f33376ff1cb59e424ed6448925530291b1ea8 | /src/3party/navigation/navex/navex_navigation/src/FuzzyLocalPlanner.cpp | 834b692c64e3e83d8e42a08b73bc6e8a6f77f31d | [] | no_license | robotil/robil3 | 78ad31ba5e42b15cb7c53aefa038ccf520340b69 | c04dbcf58f45c984d0ad2172cacd9bafca8bcf2c | refs/heads/master | 2020-12-19T03:45:33.167937 | 2020-07-02T04:58:24 | 2020-07-02T04:58:24 | 235,611,490 | 0 | 2 | null | 2020-03-25T13:31:52 | 2020-01-22T16:11:34 | C++ | UTF-8 | C++ | false | false | 10,974 | cpp | /*
* FuzzyLocalPlanner.cpp
*
* Created on: Jan 15, 2017
* Author: assaf
*/
#include <navex_navigation/FuzzyLocalPlanner.h>
FuzzyLocalPlanner::FuzzyLocalPlanner(CostMap* localCostmap,
CostMap* globalCostmap,
IController* robotController,
const std::string & global_navigation_frame_id,
double simulationTime,
double granularity)
: LocalPlannerBase(localCostmap, globalCostmap, robotController),
trajectorySimulator_(simulationTime, granularity),
localGoalFinder_(localCostmap->getFrameId()), configServer_(ros::NodeHandle("~/local_planner")),
global_navigation_frame_id_(global_navigation_frame_id)
{
configServer_.setCallback(
boost::bind(&FuzzyLocalPlanner::dynamicConfigCallback, this, _1, _2));
generateTrajectories();
trajectoryMathcer_ = new FuzzyTrajectoryMatcher(&config_);
ros::NodeHandle node;
localGoalPublisher_ = node.advertise<geometry_msgs::PointStamped>(
"local_goal", 10, true);
localPlanPublisher_ = node.advertise<nav_msgs::Path>(
"local_plan", 10, true);
trajectoriesPublisher_ = node.advertise<visualization_msgs::MarkerArray>(
"trajectories", 5, true);
}
FuzzyLocalPlanner::~FuzzyLocalPlanner()
{
delete trajectoryMathcer_;
}
TrajectoryMatch::SetPtr FuzzyLocalPlanner::evaluateTrajectories( ITrajectoryMatcher::MatchStrategy strategy )
{
TrajectoryMatch::SetPtr matches = trajectoryMathcer_->ITrajectoryMatcher::match(
*getLocalCostmap(), *getGlobalCostmap(), trajectories_, strategy);
return matches;
}
bool FuzzyLocalPlanner::updateLocalGoal()
{
const nav_msgs::Path& path = getPlan();
const CostMap* costmap = getLocalCostmap();
size_t localGoalIndexOnPath = localGoalFinder_.findLocalGoal();
geometry_msgs::PoseStamped localGoalPose = path.poses[localGoalIndexOnPath];
localGoalPose.header.stamp = ros::Time::now();
cv::Point localGoal = costmap->poseToPixel(localGoalPose);
trajectoryMathcer_->setGoal(localGoal);
publishLocalGoal(localGoalPose);
// Check if the goal is valid
CostMapCell::CellType cell = costmap->getCellValue(localGoalPose);
if (cell >= CostMapCell::CELL_BLOCKED)
{
// Goal is blocked
// Replanning needed
return false;
}
return true;
}
LocalPlannerBase::PlannerStatus FuzzyLocalPlanner::update()
{
bool validLocalGoal = updateLocalGoal();
if (!isForceNavigation() && !validLocalGoal) {
// Local goal (= part of the global plan) falls on a blocked
// cells, recovery should me executed
// note: if force navigation activated (can occur while planning is active)
// the goal will be valid
return LocalPlannerBase::STATUS_PATH_BLOCKED;
}
const size_t strategies_numbers=2;
ITrajectoryMatcher::MatchStrategy strategies[] = {
ITrajectoryMatcher::MS_NORMAL,
ITrajectoryMatcher::MS_RECOVERY
};
TrajectoryMatch::SetPtr matches;
TrajectoryMatch::Ptr bestMatch;
for(size_t i=0;i<strategies_numbers;i++)
{
matches = evaluateTrajectories(strategies[i]);
bestMatch = *matches->begin();
if(bestMatch->isFatal()) continue; else break;
}
if(not bestMatch)
{
std::cout<<"NAV: LocalPlannerBase::STATUS_NO_PLAN_FOUND ["<<__FILE__<<":"<<__LINE__<<"]"<<std::endl;
return LocalPlannerBase::STATUS_NO_PLAN_FOUND;
}
trajectoryMathcer_->setLastBestTrajectory(bestMatch->getTrajectory());
publishTrajectories(matches);
if (!isForceNavigation() && bestMatch->getTrajectory()->isInPlace()) {
std::cout<<"NAV: isInPlace"<<std::endl;
// In place best trajectory means, the other are blocked
// This means we are in a potentially dangerous position
// so better call a recovery behavior
// NOTE: inPlace turn can't be fatal, because
// GoalTrajectoryMatcher gives a fatal, in place turns a small positive score
bool dangerousPosition = true;
BOOST_FOREACH(const TrajectoryMatch::Ptr& match, *matches) {
if (!match->getTrajectory()->isInPlace() && !match->isFatal())
dangerousPosition = false;
}
if (dangerousPosition)
{
std::cout<<"NAV: LocalPlannerBase::STATUS_NO_PLAN_FOUND ["<<__FILE__<<":"<<__LINE__<<"]"<<std::endl;
return LocalPlannerBase::STATUS_NO_PLAN_FOUND;
}
}
driveCommand(bestMatch->getTrajectory()->getMotionModel());
localPlanPublisher_.publish(bestMatch->getTrajectory()->getPath(
true, getLocalCostmap()->getFrameId()));
return LocalPlannerBase::STATUS_OK;
}
void FuzzyLocalPlanner::createTrajectory(double angle, double speed, Trajectory::VectorPtr& trajectories)
{
Trajectory::Ptr trajectory = trajectorySimulator_.simulate(
new SkidSteerModel(speed, angle));
trajectories->push_back(trajectory);
}
inline double __f(double x, double mp){ return (mp-1)*x+1; }
void FuzzyLocalPlanner::generateTrajectories_angle_iterations(
Trajectory::VectorPtr trajectories, double speed, double skip_angles_range, bool dynamic_step,
double _minSpeed, double _maxSpeed)
{
double minSpeed = fmin( fabs(_minSpeed), fabs(_maxSpeed) );
double maxSpeed = fmax( fabs(_minSpeed), fabs(_maxSpeed) );
double minAngle = config_.min_angular_speed;
double maxAngle = config_.max_angular_speed;
double speedStep = config_.speed_step;
double angular_speed_step = config_.angular_speed_step;
const double minPerc = 0.75; // greater value of the variable leads to greater angle for faster speed.
double speed_rate = maxSpeed==minSpeed? 0 : 1 - (maxSpeed-fabs(speed))/(maxSpeed-minSpeed);
double speedPercent = __f(speed_rate, minPerc);
double speedMinAngle = minAngle * speedPercent;
double speedMaxAngle = maxAngle * speedPercent;
double angleStep = angular_speed_step;
double f = angleStep;
angleStep+=f;
double lastMaxAngle(0), lastMinAngle(0);
for (double angle = f; angle <= fmax(fabs(speedMaxAngle),fabs(speedMinAngle));angle+=angleStep,angleStep+=(dynamic_step?f:0))
{
if( angle < skip_angles_range )continue;
if( angle <= speedMaxAngle)
{
lastMaxAngle = angle;
createTrajectory(angle, speed, trajectories);
}
if( speedMinAngle <= (-angle) )
{
lastMinAngle = -angle;
createTrajectory(-angle, speed, trajectories);
}
}
if(skip_angles_range<0.00001) createTrajectory(0, speed, trajectories);
if(lastMaxAngle < (speedMaxAngle-f*0.5))
createTrajectory(speedMaxAngle, speed, trajectories);
if(lastMinAngle > (speedMinAngle+f*0.5))
createTrajectory(speedMinAngle, speed, trajectories);
}
void FuzzyLocalPlanner::generateTrajectories_forward(Trajectory::VectorPtr trajectories)
{
double minSpeed = config_.min_speed;
double maxSpeed = config_.max_speed;
double minAngle = config_.min_angular_speed;
double maxAngle = config_.max_angular_speed;
double speedStep = config_.speed_step;
double angular_speed_step = config_.angular_speed_step;
double speed=0;
bool done =false;
while(not done)
{
speed+=speedStep;
if(speed>maxSpeed)
{
done=true;
speed = maxSpeed;
}
generateTrajectories_angle_iterations(trajectories, speed, 0, false, 0, maxSpeed);
}
}
void FuzzyLocalPlanner::generateTrajectories_backward(Trajectory::VectorPtr trajectories)
{
double minSpeed = config_.min_speed;
double maxSpeed = config_.max_speed;
double minAngle = config_.min_angular_speed;
double maxAngle = config_.max_angular_speed;
double speedStep = config_.speed_step;
double speed=0;
bool done =false;
while(not done)
{
speed-=speedStep;
if(speed<minSpeed)
{
done=true;
speed = minSpeed;
}
generateTrajectories_angle_iterations(trajectories, speed, 0, false, minSpeed, 0);
}
}
void FuzzyLocalPlanner::generateTrajectories_inplace_turn(Trajectory::VectorPtr trajectories)
{
double minSpeed = config_.min_speed;
double maxSpeed = config_.max_speed;
double minAngle = config_.min_angular_speed;
double maxAngle = config_.max_angular_speed;
double speedStep = config_.speed_step;
double speed = speedStep*0.25;
maxAngle = fabs(minAngle)*(2./3.);
generateTrajectories_angle_iterations(trajectories, speed, maxAngle,false, speed,speed);
}
void FuzzyLocalPlanner::generateTrajectories()
{
double minSpeed = config_.min_speed;
double maxSpeed = config_.max_speed;
double minAngle = config_.min_angular_speed;
double maxAngle = config_.max_angular_speed;
double speedStep = config_.speed_step;
trajectorySimulator_ = TrajectorySimulator(config_.simulation_time, config_.granularity);
Trajectory::VectorPtr trajectories(new Trajectory::Vector());
generateTrajectories_forward(trajectories);
generateTrajectories_backward(trajectories);
generateTrajectories_inplace_turn(trajectories);
trajectories_ = trajectories;
}
void FuzzyLocalPlanner::publishLocalGoal(
const geometry_msgs::PoseStamped pose)
{
geometry_msgs::PointStamped point;
point.header.frame_id = pose.header.frame_id;
point.header.stamp = ros::Time::now();
point.point = pose.pose.position;
localGoalPublisher_.publish(point);
}
void FuzzyLocalPlanner::publishTrajectories(const TrajectoryMatch::SetPtr& matches)
{
visualization_msgs::MarkerArray markers;
int id = 1;
bool scoreColorize = config_.trajectory_score_color;
bool first = true;
double max_score = (*(*matches).begin())->getScore();
ros::Time t = ros::Time::now();
std::string err = "";
tfListener_.getLatestCommonTime(global_navigation_frame_id_,getLocalCostmap()->getFrameId(),t, &err);
if(err != "")
t = ros::Time::now();
BOOST_FOREACH(const TrajectoryMatch::Ptr& match, *matches)
{
visualization_msgs::Marker marker;
marker.id = id++;
marker.header.frame_id = getLocalCostmap()->getFrameId();
marker.header.stamp = t;
marker.type = visualization_msgs::Marker::LINE_STRIP;
marker.action = 0;
marker.scale.x = first ? 0.05 : 0.01f;
if (first) {
marker.color.b = 1.0;
first = false;
} else {
// if (scoreColorize) {
// Color intensity reflects the score
double norm_score = match->getScore() / max_score;
marker.color.r = 1.0 - norm_score;
marker.color.g = norm_score;
// double colorNormalized = ((match->getScore()) + 1.0) / 2.0;
//
// marker.color.r = 1 - colorNormalized * 0.5;
// marker.color.g = colorNormalized * 0.5;
// } else {
// Color reflect the danger
if (match->isFatal()) {
marker.color.r = 0.0;
marker.color.g = 0.0;
marker.color.b = 0.0;
}
// else if (match->isBlocked()) {
// marker.color.r = 1.0;
// marker.color.g = 0.8;
// } else {
// marker.color.b = 1.0;
// }
// }
}
marker.color.a = 1.0f;
const nav_msgs::Path::Ptr& path = match->getTrajectory()->getPath();
BOOST_FOREACH(const geometry_msgs::PoseStamped& pose, path->poses) {
marker.points.push_back(pose.pose.position);
}
marker.pose.orientation.w = 1;
marker.lifetime = ros::Duration(1.0 / 20.0);
marker.frame_locked = true;
markers.markers.push_back(marker);
if(not scoreColorize) break;
}
trajectoriesPublisher_.publish(markers);
}
void FuzzyLocalPlanner::dynamicConfigCallback(
navex_navigation::NavexLocalPlannerConfig& config, uint32_t level)
{
config_ = config;
localGoalFinder_.setGoalDistance(config.local_goal_distance);
generateTrajectories();
}
| [
"cogniteam@gmail.com"
] | cogniteam@gmail.com |
f7f3e568262bb323104d09547a39052a693c2d9a | 3a3b937f684f2a25419f13c694685fc991c55ab5 | /src/Commands/Autonomous/Auto Cross Defense/AutoCrossDefense.cpp | dfee22638cd7d7343a2d03ddf11a13b54314501e | [] | no_license | FRC-Team-1410/FS2016-FRC1410 | 073d93ecf0627555107ba3ab9cb7bba041b810ce | d5b5a5ee318d038642a248549417ef9cc3b17ba6 | refs/heads/master | 2021-05-03T06:54:43.746822 | 2016-11-01T20:20:33 | 2016-11-01T20:20:33 | 49,347,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 185 | cpp | #include "AutoCrossDefense.h"
#include "Auto Cross Defense Command Groups/AutoCrossDefenseDrive.h"
AutoCrossDefense::AutoCrossDefense(){
AddSequential(new AutoCrossDefenseDrive());
}
| [
"kingnerdthethird@outlook.com"
] | kingnerdthethird@outlook.com |
55fe4eb985ebe29e265779e36f33f7bfbde403b8 | bb7645bab64acc5bc93429a6cdf43e1638237980 | /Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.0 Samples/[C++]-Windows Driver Kit (WDK) 8.0 Samples/C++/WDK 8.0 Samples/HID client sample driver/Solution/Fx2Hid/ControlQueue.h | 6338cd3a891d5da77472b18f6718a4bca6975665 | [
"MIT"
] | permissive | Violet26/msdn-code-gallery-microsoft | 3b1d9cfb494dc06b0bd3d509b6b4762eae2e2312 | df0f5129fa839a6de8f0f7f7397a8b290c60ffbb | refs/heads/master | 2020-12-02T02:00:48.716941 | 2020-01-05T22:39:02 | 2020-01-05T22:39:02 | 230,851,047 | 1 | 0 | MIT | 2019-12-30T05:06:00 | 2019-12-30T05:05:59 | null | UTF-8 | C++ | false | false | 1,455 | h | /*++
Copyright (c) Microsoft Corporation, All Rights Reserved
Module Name:
ControlQueue.h
Abstract:
This file defines the queue callback object for handling device I/O
control requests. This is a serialized queue.
Environment:
Windows User-Mode Driver Framework (WUDF)
--*/
#pragma once
//
// Queue Callback Object.
//
class CMyControlQueue : public IQueueCallbackDeviceIoControl,
public CMyQueue
{
HRESULT
Initialize(
VOID
);
public:
CMyControlQueue(
_In_ PCMyDevice Device
);
virtual
~CMyControlQueue(
VOID
)
{
return;
}
static
HRESULT
CreateInstance(
_In_ PCMyDevice Device,
_Out_ PCMyControlQueue *Queue
);
HRESULT
Configure(
VOID
)
{
return S_OK;
}
IQueueCallbackDeviceIoControl *
QueryIQueueCallbackDeviceIoControl(
VOID
)
{
AddRef();
return static_cast<IQueueCallbackDeviceIoControl *>(this);
}
//
// IUnknown
//
STDMETHOD_(ULONG,AddRef) (VOID) {return CUnknown::AddRef();}
_At_(this, __drv_freesMem(object))
STDMETHOD_(ULONG,Release) (VOID) {return CUnknown::Release();}
STDMETHOD_(HRESULT, QueryInterface)(
_In_ REFIID InterfaceId,
_Out_ PVOID *Object
);
//
// Wdf Callbacks
//
//
// IQueueCallbackDeviceIoControl
//
STDMETHOD_ (void, OnDeviceIoControl)(
_In_ IWDFIoQueue *pWdfQueue,
_In_ IWDFIoRequest *pWdfRequest,
_In_ ULONG ControlCode,
_In_ SIZE_T InputBufferSizeInBytes,
_In_ SIZE_T OutputBufferSizeInBytes
);
};
| [
"v-tiafe@microsoft.com"
] | v-tiafe@microsoft.com |
627466f7280156aa5dcb0d53e3a420664caf87d7 | d8fc67fe7e0377a7133fd165941fe00166c246a0 | /visual_studio/raytracer/Src/quaternionJuliaSet.cpp | 4296f304e69b63512350b69efca55b13da9ec07e | [] | no_license | wangyix/PathTracer | 8ab8dfa7b559b3d9c9ed963cd355a9f1bfa85c89 | 6a6495198fd1bfe78885197e9a9522d9db91c772 | refs/heads/master | 2020-12-24T15:22:14.137382 | 2015-10-17T01:49:54 | 2015-10-17T01:49:54 | 27,092,900 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,047 | cpp | //
// quaternionJuliaSet.cpp
// RayTracer
//
// Created by Marianna Neubauer on 11/21/14.
// Copyright (c) 2014 Tianye Lu. All rights reserved.
//
#include "quaternionJuliaSet.h"
#include "SceneObject.h"
#include "STVector3.h"
#include "STPoint3.h"
#define DELTA (1e-5f)
#define ITERATIONS (12)
#define ESCAPE_COEFFICIENT (2)
#define RADIUS (1.5f)
// begin code from "OpenCL RayTraced Quaternion Julia-Set Example" in Mac Developer Library
float4 qmult(const float4& q1, const float4& q2)
{
float4 r;
float3 t;
float3 q1yzw = float3(q1.y(), q1.z(), q1.w());
float3 q2yzw = float3(q2.y(), q2.z(), q2.w());
float3 c = q1yzw.cross(q2yzw); //cross(q1yzw, q2yzw);
t = q2yzw * q1.x() + q1yzw * q2.x() + c;
r.x() = q1.x() * q2.x() - q1yzw.dot(q2yzw); //dot(q1yzw, q2yzw);
//r.yzw = t.xyz;
r.y() = t.x(); r.z() = t.y(); r.w() = t.z();
return r;
}
float4 qsqr(const float4& q)
{
float4 r;
float3 t;
float3 qyzw = float3(q.y(), q.z(), q.w());
t = qyzw * q.x() * 2.0f;
r.x() = q.x() * q.x() - qyzw.squaredNorm(); // dot(qyzw, qyzw);
//r.yzw = t.xyz;
r.y() = t.x(); r.z() = t.y(); r.w() = t.z();
return r;
}
/*float length4(const float4& f)
{
return sqrt(f.x()*f.x() + f.y()*f.y() + f.z()*f.z() + f.w()*f.w());
}*/
STVector3 EstimateNormalQJulia(const STPoint3& p, const float4& c, int iterations)
{
float4 qp = float4( p.x(), p.y(), p.z(), 0.0f );
float4 gx1 = qp - float4( DELTA, 0.0f, 0.0f, 0.0f );
float4 gx2 = qp + float4( DELTA, 0.0f, 0.0f, 0.0f );
float4 gy1 = qp - float4( 0.0f, DELTA, 0.0f, 0.0f );
float4 gy2 = qp + float4( 0.0f, DELTA, 0.0f, 0.0f );
float4 gz1 = qp - float4( 0.0f, 0.0f, DELTA, 0.0f );
float4 gz2 = qp + float4( 0.0f, 0.0f, DELTA, 0.0f );
for ( int i = 0; i < iterations; i++ )
{
gx1 = qsqr( gx1 ) + c;
gx2 = qsqr( gx2 ) + c;
gy1 = qsqr( gy1 ) + c;
gy2 = qsqr( gy2 ) + c;
gz1 = qsqr( gz1 ) + c;
gz2 = qsqr( gz2 ) + c;
}
float nx = gx2.norm() - gx1.norm(); // length4(gx2) - length4(gx1);
float ny = gy2.norm() - gy1.norm(); // length4(gy2) - length4(gy1);
float nz = gz2.norm() - gz1.norm(); // length4(gz2) - length4(gz1);
STVector3 normal = STVector3( nx, ny, nz );
normal.normalize();
return normal;
}
/*float IntersectSphere(STVector3 rO, STVector3 rD, float radius)
{
float fB = 2.0f * STVector3::Dot( rO, rD );
float fB2 = fB * fB;
float fC = STVector3::Dot( rO, rO ) - radius;
float fT = (fB2 - 4.0f * fC);
if (fT <= 0.0f)
return 0.0f;
float fD = sqrt( fT ); //half_sqrt is fast sqrt algorithm
float fT0 = ( -fB + fD ) * 0.5f;
float fT1 = ( -fB - fD ) * 0.5f;
fT = fmin(fT0, fT1);
return fT;
}*/
float4 IntersectQJulia(const STVector3& _rO, const STVector3& rD, const float4& c, float epsilon, float escape)
{
STVector3 rO = _rO;
float rd = 0.0f;
float dist = epsilon;
while ( dist >= epsilon && rd < escape)
{
float4 z = float4( rO.x(), rO.y(), rO.z(), 0.0f );
float4 zp = float4( 1.0f, 0.0f, 0.0f, 0.0f );
float zd = 0.0f;
unsigned int count = 0;
while(zd < escape && count < ITERATIONS)
{
zp = qmult(z, zp) * 2.0f;
z = qsqr(z) + c;
zd = z.squaredNorm(); // dot(z, z);
count++;
}
float normZ = z.norm();
dist = 0.5f * normZ * log( normZ ) / zp.norm(); //was half_log which I think is a faster version of log
rO = rO + rD * dist;
rd = rO.squaredNorm(); // STVector3::Dot(rO, rO);
}
float4 hit; hit.x() = rO.x(); hit.y() = rO.y(); hit.z() = rO.z(); hit.w() = dist;
return hit;
}
// end of code from "OpenCL RayTraced Quaternion Julia-Set Example" in Mac Developer Library
bool intersectBoundingSphere(const STPoint3& e, const STVector3& d_normalized, float* t1, float* t2) {
STVector3 c_to_e = STVector3(e.x(), e.y(), e.z());
// float a = 1.f;
float b = 2.f * c_to_e.dot(d_normalized); //STVector3::Dot(c_to_e, d_normalized);
float c = c_to_e.squaredNorm() - RADIUS * RADIUS;
float disc = b * b - 4.f * c; // a = 1
if (disc <= 0.f) return false; // ray misses bounding sphere (<= instead of < ensures z!=0)
if (b > 0.f) {
float z = 0.5f * (-b - sqrtf(disc));
*t1 = z; // z / a
*t2 = c / z;
} else {
float z = 0.5f * (-b + sqrtf(disc));
*t1 = c / z;
*t2 = z; // z / a
}
return true;
}
bool quaternionJuliaSet::getIntersect(const Ray& ray, Intersection* intersection) const {
// check if this ray starts on the surface of this julia set
bool rayLeavingSurface = false;
bool rayEnteringSurface = false;
//const float same_point_threshold = 0.0001f;
if (ray.e_obj && ray.e_obj->getShape() == this) {
// compare ray direction to the normal of the last intersection point to see if this ray
// is entering or leaving the surface
rayLeavingSurface = (ray.d_dot_e_normal >= 0.f);
rayEnteringSurface = !rayLeavingSurface;
}
Ray ray_adj(ray);
ray_adj.d.normalize();
if (rayEnteringSurface) {
// intersect this ray with the bounding sphere, and then reverse its direction
// so it marches back into the bounding sphere to intersect with the julia set.
// (for julia sets that are hollow, the intersection this returns probably won't be
// where this refracted ray actually leaves the julia set, but oh well)
float t1, t2;
intersectBoundingSphere(ray_adj.e, ray_adj.d, &t1, &t2);
ray_adj.e += t2 * ray_adj.d;
ray_adj.d = -ray_adj.d;
} else if (rayLeavingSurface) {
// move the ray start forward by some epsilons to prevent intersecting the same spot
ray_adj.e += 2.5f * epsilon * ray_adj.d;
} else {
// check if the ray starts outside the bounding sphere. If so, move its start
// position to where it first intersects the bounding sphere
if (STVector3(ray_adj.e.x(), ray_adj.e.y(), ray_adj.e.z()).squaredNorm() > RADIUS * RADIUS) {
float t1, t2;
if (!intersectBoundingSphere(ray_adj.e, ray_adj.d, &t1, &t2)) {
return false; // ray does not intersect bounding sphere
}
ray_adj.e += t1 * ray_adj.d;
}
}
// intersect the ray with the julia set
float escape_threshold = ESCAPE_COEFFICIENT*RADIUS;
float4 hit = IntersectQJulia(STVector3(ray_adj.e.x(), ray_adj.e.y(), ray_adj.e.z()),
ray_adj.d, mu, epsilon, escape_threshold);
float dist = hit.w();
if (dist >= epsilon) {
// ray-marched past the escape threshold instead of unbounding sphere radius
// falling below epsilon; this ray does not intersect the julia set
return false;
}
STPoint3 point = STPoint3(hit.x(), hit.y(), hit.z());
// calculate t from the perspective of the original ray given to us
float t = ray.d.dot(point - ray.e) / ray.d.squaredNorm(); // STVector3::Dot(point - ray.e, ray.d) / ray.d.LengthSq();
if (!ray.inRange(t)) {
return false;
}
// estimate the normal at the intersection with the julia set
STVector3 normal = EstimateNormalQJulia(point, mu, ITERATIONS);
intersection->t = t;
intersection->point = point;
intersection->normal = normal;
return true;
}
bool quaternionJuliaSet::doesIntersect(const Ray& ray) const {
Ray ray_adj(ray);
float ray_d_length = ray.d.norm();
ray_adj.d /= ray_d_length; // ray_adj.d.Normalize()
// check if the ray starts outside the bounding sphere. If so, move its start
// position to where it first intersects the bounding sphere
if (STVector3(ray_adj.e.x(), ray_adj.e.y(), ray_adj.e.z()).squaredNorm() > RADIUS * RADIUS) {
float t1, t2;
if (!intersectBoundingSphere(ray_adj.e, ray_adj.d, &t1, &t2)) {
return false; // ray does not intersect bounding sphere
}
ray_adj.e += t1 * ray_adj.d;
} else {
// ray starts inside the bounding sphere.
// intersect this ray with the bounding sphere, and then reverse its direction
// so it marches back into the bounding sphere to intersect with the julia set.
// Why not just let the ray start marching from where it is? If the ray starts on the surface
// of this julia set, then starting the march there causes weird things to happen sometimes (it may be
// hard to distinguish between a close-by re-intersection or being marched back into the same intersection)
// By doing a backwards march from the bounding sphere, we should avoid some of these problems.
float t1, t2;
intersectBoundingSphere(ray_adj.e, ray_adj.d, &t1, &t2);
ray_adj.e += t2 * ray_adj.d;
ray_adj.d = -ray_adj.d;
}
// intersect the ray with the julia set
float escape_threshold = ESCAPE_COEFFICIENT*RADIUS;
float4 hit = IntersectQJulia(STVector3(ray_adj.e.x(), ray_adj.e.y(), ray_adj.e.z()),
ray_adj.d, mu, epsilon, escape_threshold);
float dist = hit.w();
if (dist >= epsilon) {
// ray-marched past the escape threshold instead of unbounding sphere radius
// falling below epsilon; this ray does not intersect the julia set
return false;
}
STPoint3 point = STPoint3(hit.x(), hit.y(), hit.z());
// calculate t from the perspective of the original ray given to us. Pad the t_min with
// some epsilons to prevent a ray starting on the julia set surface going outwards
// intersecting at the same spot due to the backwards ray-march
float ray_t_epsilon_pad = 2.5f * epsilon / ray_d_length;
float t = ray.d.dot(point - ray.e) / (ray_d_length * ray_d_length); // STVector3::Dot(point - ray.e, ray.d) / (ray_d_length * ray_d_length);
return (t >= (ray.t_min + ray_t_epsilon_pad) && t <= ray.t_max);
}
void quaternionJuliaSet::getAABB(const STTransform4& transform, AABB* aabb) const {
#if USE_EIGEN
float scale = transform.block(0, 0, 3, 1).norm(); // assuming transform does not warp shape
#else
float scale = transform.columnnMagnitude(0); // assuming transform does not warp shape
#endif
float r = scale * RADIUS;
STPoint3 c = transform * STPoint3(0.f, 0.f, 0.f);
*aabb = AABB(c.x() - r, c.x() + r, c.y() - r, c.y() + r, c.z() - r, c.z() + r);
}
#if 0
Intersection* quaternionJuliaSet::getIntersect(const Ray &ray){
float ray_d_length = ray.d.Length();
STVector3 rD = ray.d;
rD /= ray_d_length; //.Normalize();
STVector3 rO (ray.e.x(), ray.e.y(), ray.e.z());
float t = IntersectSphere2(rO, rD, ray);
if (t<= 0) return NULL;
/*STPoint3 point1 = ray.at(t);
STVector3 normal1 = point1 - center;
normal1.Normalize();
return new Intersection(t, point1, normal1);*/
rO = rO + rD*t;
// this code reverses the direction of the ray if it is moving out of the bouding sphere
STVector3 sphere_point;// = ray.at(t);
sphere_point.x() = rO.x(); sphere_point.y() = rO.y(); sphere_point.z() = rO.z();
if (STVector3::Dot(rD, sphere_point) > 0)
{
rD = -rD;
}
float escape_threshold = ESCAPE_COEFFICIENT*RADIUS;
float4 hit = IntersectQJulia( rO, rD, mu, epsilon, escape_threshold);
float dist = hit.w();
if (dist >= epsilon){
// ray-marched past the escape threshold instead of unbounding sphere radius
// falling below epsilon; this ray does not intersect the julia set
return NULL;
}
STPoint3 point;
point.x() = hit.x(); point.y() = hit.y(); point.z() = hit.z();
STVector3 normal = EstimateNormalQJulia( point, mu, ITERATIONS);
//t = (ray.e - point).Length()/ray.d.Length(); //Hopefully this is the right t
// if ray intersected the bounding sphere from the inside, then the ray-march
// back from that intersection may produce a hit point less than shadowBias
// from the ray start or even slightly behind the ray start.
// This comes up when checking for intersection with a ray that originates
// on the surface of the julia set and heads outwards (i.e. reflected rays
// off the surface of the julia set)
// Since the hit point returned by IntersectQJulia() has an error proportional
// to epsilon, we will only count this as an intersection if the hit point
// is more than 2 epsilons + shadowbias away from the ray start (assuming
// ray.d is already normalized
t = STVector3::Dot(point - ray.e, ray.d) / (ray_d_length*ray_d_length);//ray.d.LengthSq();
if (t < ray.t_min + 2.f * epsilon / ray_d_length || t > ray.t_max) {//!ray.inRange(t)) {
return NULL;
}
return new Intersection(t, point, normal);
}
bool quaternionJuliaSet::doesIntersect(const Ray& ray)
{
STVector3 rD = ray.d;
rD.Normalize();
STVector3 rO(ray.e.x(), ray.e.y(), ray.e.z());
float t = IntersectSphere2(rO, rD,ray);
if (t<= 0) return NULL;
rO = rO + rD*t;
float escape_threshold = ESCAPE_COEFFICIENT*RADIUS;
float4 hit = IntersectQJulia( rO, rD, mu, epsilon, escape_threshold);
float dist = hit.w();
if (dist >= epsilon) return false;
else return true;
}
#endif
| [
"wangyix@gmail.com"
] | wangyix@gmail.com |
dfb5e6e7adc3f787be4e92cbc3d12f9ec00db082 | 6ebfc881db45bddc811e56f8f2861a5c3cd44f0b | /Chapter1-Structure/Component_B.cpp | 00cd614016c12cd56de64e181cbf45ad69c68c80 | [] | no_license | JimFawcett/CppModels | 3e373ad0031679f15f7af22289a6e206ae2634fe | ba81488f7c7108f8d6632d2cc2a71e5eacf414e0 | refs/heads/master | 2021-05-26T21:59:28.710470 | 2020-04-08T18:14:14 | 2020-04-08T18:14:14 | 254,164,094 | 2 | 1 | null | 2020-10-17T14:06:14 | 2020-04-08T18:06:21 | C++ | UTF-8 | C++ | false | false | 1,071 | cpp | ///////////////////////////////////////////////////////////////
// Component_B.cpp - implements Component_B operations //
// //
// Jim Fawcett, https://JimFawcett.github.io, Feb 2020 //
///////////////////////////////////////////////////////////////
#include "Component_B.h"
#include <iostream>
#include <string>
class Helper {
public:
static void context();
};
void Helper::context() {
#ifdef TEST_COMPONENT_B
std::cout << "\n Testing Component_B";
#else
std::cout << "\n Component_B used by other classes";
#endif
}
Component_B::Component_B() {
std::cout << "\n\n default construction of Component_B instance";
Helper::context();
pA_ = createComponent_A("B's Component_A");
}
Component_B::~Component_B() {
std::cout << "\n destruction of Component_B instance";
}
void Component_B::say() {
std::cout << "\n Component_B instance here, holding pointer to my Component_A";
pA_->say();
}
#ifdef TEST_COMPONENT_B
int main() {
Cosmetic c;
Component_B b;
b.say();
}
#endif
| [
"jfawcett@twcny.rr.com"
] | jfawcett@twcny.rr.com |
3b800c6cbaab14ba9ba8cbf31386e3a3af263b81 | 8354bc619a651e58f4e468e22d7bfad6f04d5d37 | /bt3/BT6/BT6/cGiaSuc.cpp | e64e8b8441225d257ee7a74d41b2b4a3fac6bc3f | [] | no_license | truong8864/BTOOP | b5e65c15b28baea19b5f67c5b6ba71c27eb20a6d | 490508be3e3bfc3e8119d2dd2871adfe09cd997a | refs/heads/master | 2020-03-28T19:30:19.155217 | 2018-09-16T09:51:27 | 2018-09-16T09:51:27 | 148,982,876 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | cpp | #include "cGiaSuc.h"
cGiaSuc::cGiaSuc()
{
iSoLuong = 0;
iSua = 0;
strTiengKeu = "\0";
}
cGiaSuc::cGiaSuc(int soluong)
{
iSoLuong = soluong;
iSua = 0;
strTiengKeu = "\0";
}
cGiaSuc::~cGiaSuc()
{
}
| [
"43312736+truong8864@users.noreply.github.com"
] | 43312736+truong8864@users.noreply.github.com |
9ecc70f6f45f91bb129ed2831cf68498e0f3a877 | f26ef5f176c2e9d9fe3fbbc9a04e4e17a2189a48 | /C++/LIBRAS.CyberGlove/include/Unsupported/vclip/mv.h | b72947e2e3fecef72f9baaa77d228920acde5d76 | [] | no_license | haroldogtf/LIBRAS.CyberGlove | 9df17fee91a3d318d0eb4161d9702eeea23fa4c8 | a1f7fc92efce0a9221bfc2037c37b9b926bc9f0e | refs/heads/master | 2021-01-15T10:06:51.297507 | 2016-05-09T02:19:32 | 2016-05-09T02:19:32 | 53,633,766 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 37,258 | h | ////////////////////////////////////////////////////////////////////////////////
//
// Copyright 1997 Mitsubishi Electric Information Technology Center
// America (MEITCA). All Rights Reserved.
//
// Permission to use, copy, modify and distribute this software and
// its documentation for educational, research and non-profit
// purposes, without fee, and without a written agreement is hereby
// granted, provided that the above copyright notice and the
// following three paragraphs appear in all copies.
//
// Permission to incorporate this software into commercial products
// may be obtained from MERL - A Mitsubishi Electric Research Lab, 201
// Broadway, Cambridge, MA 02139.
//
// IN NO EVENT SHALL MEITCA BE LIABLE TO ANY PARTY FOR DIRECT,
// INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
// LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF MEITCA HAS BEEN ADVISED OF THE POSSIBILITY
// OF SUCH DAMAGES.
//
// MEITCA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON
// AN "AS IS" BASIS, AND MEITCA HAS NO OBLIGATIONS TO PROVIDE
// MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
//
// Author:
// Brian Mirtich
// mirtich@merl.com
// 617.621.7573
// www.merl.com/people/mirtich
//
////////////////////////////////////////////////////////////////////////////////
#ifndef MV_H
#define MV_H
#if defined(_WIN32)
#include <cmath>
#if defined(min)
#undef min
#endif
#if defined(max)
#undef max
#endif
#if !defined(_USING_STD_NAMESPACE_)
#define _USING_STD_NAMESPACE_
#include <strstream>
using std::istream;
using std::ostream;
using std::ios;
using std::endl;
using std::ws;
using std::istrstream;
#endif
#else
#include <iostream.h>
#include <math.h>
#endif
#if INVENTOR
#include <Inventor/SbLinear.h>
#include <Inventor/nodes/SoTransform.h>
#endif
#if OPCOUNTS
#include <OpCounter.h>
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Matrix-Vector library
//
///////////////////////////////////////////////////////////////////////////////
/*
SGI Inventor Interface
----------------------
The compiler option -DINVENTOR causes compilation of functions
for translating to and from the Inventor Library's vector and matrix
types.
Counting Operations
-------------------
To count floating point operations using the OpCounter package, use
the compiler flag -DOPCOUNTS. This will cause type Real to be
compiled as type Double, which is like type double, but also has
mechanisms for counting operations. See OpCounter.h for details.
Note: This functionality is not included with the V-Clip
distribution.
Implied Operands
----------------
For most operations, the result is returned in 'this'. For example:
Vect3 a,b,c;
...
a.add(b,c); // a <- vector sum of b & c
In the case of vector add, it does not matter if one of the operands
is also the destination: a.add(a,b) simply adds b to a, as
expected. However, for other operations, the destination can not be
passed as an operand, as this will invalidate the computation:
Mat3 M, N;
...
M.mult(M, N); // WRONG! M will not be matrix product M N upon return!
To fix this problem, such functions have versions that assume the
destination as an implied operand, and take care to compute the
result correctly in this situation. The above incorrect call coan
be replaced with
M.postmult(N); // M <- matrix product M N
For consistency, and because it reduces parameter passing, implied
operand versions of most operations exist, even when the destination
could be passed as an operand without a problem. For example:
Vect3 a,b,c;
...
a.add(b); // a <- vector sum of a & b
All problems associated with using destinations as operands can be
avoided by following one simple rule:
*** NEVER EXPLICITLY PASS THE DESTINATION AS AN OPERAND. ***
If you are trying to do this, chances are there is a different
version of the function which does not require the destination to be
explicitly passed. For example,
MatX M, N;
...
M.mult(N, M); // No good! Desination M passed as explicit operand
M.premult(N); // Ok. M <- N M (M is an implicit operand)
...
M.invert(M); // No good! Desination M passed as explicit operand
M.invert(); // Ok. M <- M^-1 (M is an implicit operand)
Violating the rule is sometimes ok, but adhere to it, and never go
wrong. There are a few cases which still pose problems. For
instance, one can't square a matrix M in place. M.mult(M,M)
violates the rule, but so does M.premult(M). Here, one must compute
the square into a new matrix: S.mult(M,M).
Transforming Vectors and Points
-------------------------------
The transformation operations differ slightly from the other
operations in that the result is not returned via 'this'. Instead,
'this' is the transformation description (e.g. a rotation matrix),
and the source and destination vectors/points are passed as
operands, in that order. There are also implied operand versions
that only take a single vector/point argument, transforming it and
storing the result in the same place. For example:
Se3 T;
Vect3 v, xv;
...
T.xformVect(v, xv); // xv <- transformed version of v
T.xformVect(v); // v <- transformed version of v
For some transformation objects, calls like xformVect(v, v) are ok,
but for others, they are not - xformVect(v) must be used.
To ensure correct usage:
*** NEVER PASS THE SAME SOURCE AND DESTINATION TO A TRANSFORM FUNCTION ***
*/
#if OPCOUNTS
typedef Double Real;
#else
typedef double Real;
#endif
class Vect3;
class Mat3;
class MatX;
class Quat;
class Se3;
///////////////////////////////////////////////////////////////////////////////
//
// class Vect3
//
///////////////////////////////////////////////////////////////////////////////
class Vect3 {
friend class Mat3;
friend class MatX;
friend class Quat;
friend class Se3;
public:
Real x, y, z;
// constructors //////////////////////////////////////////////////////////////
Vect3() {}
Vect3(Real x_, Real y_, Real z_) {set(x_, y_, z_);}
// setters / accessors / translators /////////////////////////////////////////
void set(Real x_, Real y_, Real z_) {x = x_; y = y_; z = z_;}
//Real &coord(int i) {return *(&x + i);} // index-based access: 0=x, 1=y, 2=z.
// index-based access: 0=x, 1=y, 2=z.
const Real &operator[](int i) const {return *(&x + i);}
Real &operator[](int i) {return *(&x + i);}
#if INVENTOR
inline void set(const SbVec3f &v);
inline void toSbVec3f(SbVec3f &v) const;
#endif
// input / output ////////////////////////////////////////////////////////////
ostream &print(ostream &os) const;
// Read vector from stream If the next string read is the single
// character i, j, or k, the appropriate unit vector is returned.
// Plus and minus signs may be optionally placed in front of these
// codes, e.g. +i or -k
istream &read(istream &is);
// operations not returning a Vect3 //////////////////////////////////////////
//inline int operator==(const Vect3 &u, const Vect3 &v);
inline int operator==(const Vect3 &other) const;
inline Real dot(const Vect3 &other) const;
inline Real norm() const;
inline Real norm2() const; // norm^2
inline Real distance (const Vect3 &other) const;
inline Real distance2(const Vect3 &other) const; // distance^2
inline Real min() const;
inline Real max() const;
inline Real minAbs() const;
inline Real maxAbs() const;
inline void swap(Vect3 &other);
// for symmetric invocations:
static Real dot (const Vect3 &u, const Vect3 &v) {return u.dot (v);}
static Real distance (const Vect3 &u, const Vect3 &v) {return u.distance (v);}
static Real distance2(const Vect3 &u, const Vect3 &v) {return u.distance2(v);}
static void swap ( Vect3 &u, Vect3 &v) { u.swap (v);}
// operations returning result via this //////////////////////////////////////
// The operation result indicated by the comments is always returned
// in this. The symbol [!] indicates that this must be distinct
// from all of the operands. The three-argument crossAdd() is
// slightly different: this must be distinct from u and v, but not
// necessarily from w.
inline void normalize(const Vect3 &v); // v/|v|
inline void normalize(); // this/|this|
inline void negate(const Vect3 &v); // -v
inline void negate(); // -this
inline void add(const Vect3 &u, const Vect3 &v); // u + v
inline void add(const Vect3 &v); // this + v
inline void sub(const Vect3 &u, const Vect3 &v); // u - v
inline void sub(const Vect3 &v); // this - v
inline void mult(const Vect3 &u, const Vect3 &v); // u * v (component-wise)
inline void mult(const Vect3 &v); // this * v (component-wise)
inline void scale(const Vect3 &v, Real s); // s * v
inline void scale(Real s); // s * this
inline void cross(const Vect3 &u, const Vect3 &v);// u x v [!]
inline void precross(const Vect3 &v); // v x this [!]
inline void postcross(const Vect3 &v); // this x v [!]
inline void crossAdd(const Vect3 &u, const Vect3 &v, const Vect3 &w);
// u x v + w [!]
inline void crossAdd(const Vect3 &u, const Vect3 &v);
// u x v + this [!]
inline void displace(const Vect3 &v, const Vect3 &u, Real lambda);
// v + lambda * u
inline void displace(const Vect3 &u, Real lambda);// this + lambda * u
inline void interpolate(const Vect3 &u, const Vect3 &v, Real lambda);
// (1-lambda)*u + lambda*v
// Vect3 constants ///////////////////////////////////////////////////////////
static const Vect3 ZERO;
static const Vect3 I; // unit vector along +x axis
static const Vect3 J; // unit vector along +y axis
static const Vect3 K; // unit vector along +z axis
static const Vect3 I_; // unit vector along -x axis
static const Vect3 J_; // unit vector along -y axis
static const Vect3 K_; // unit vector along -z axis
};
///////////////////////////////////////////////////////////////////////////////
//
// class Mat3
//
///////////////////////////////////////////////////////////////////////////////
class Mat3 {
friend class Quat;
friend class MatX;
private:
// (stored in row-major order)
Real xx, xy, xz,
yx, yy, yz,
zx, zy, zz;
public:
// constructors //////////////////////////////////////////////////////////////
Mat3() {}
Mat3(const Vect3 &diag, const Vect3 &sym) {set(diag, sym);}
Mat3(const Vect3 &axis, Real angle, int normalizeAxis = 1)
{set(axis, angle, normalizeAxis);}
Mat3(const Quat &q) {set(q);}
// setters / accessors ///////////////////////////////////////////////////////
// make a symmetric matrix, given the diagonal and symmetric
// (off-diagonal) elements in canonical order
inline void set(const Vect3 &diag, const Vect3 &sym);
// set Mat3 as a rotation of 'angle' radians about 'axis'
// axis is automatically normalized unless normalizeAxis = 0
inline void set(const Vect3 &axis, Real angle, int normalizeAxis = 1);
void set(const Quat &q);
// index-based access: 0=xrow, 1=yrow, 2=zrow.
const Vect3 &operator[](int i) const {return *(((Vect3 *) &xx) + i);}
Vect3 &operator[](int i) {return *(((Vect3 *) &xx) + i);}
// set matrix to the skew symmetric matrix corresponding to 'v X'
inline void setSkew(const Vect3 &v);
// for reading rows
const Vect3 &xrow() const {return *((Vect3 *) &xx);}
const Vect3 &yrow() const {return *((Vect3 *) &yx);}
const Vect3 &zrow() const {return *((Vect3 *) &zx);}
// for writing to rows
Vect3 &xrow() {return *((Vect3 *) &xx);}
Vect3 &yrow() {return *((Vect3 *) &yx);}
Vect3 &zrow() {return *((Vect3 *) &zx);}
// for reading columns
Vect3 xcol() const {return Vect3(xx, yx, zx);}
Vect3 ycol() const {return Vect3(xy, yy, zy);}
Vect3 zcol() const {return Vect3(xz, yz, zz);}
// for writing to columns
inline void setXcol(const Vect3 &v);
inline void setYcol(const Vect3 &v);
inline void setZcol(const Vect3 &v);
// for reading a symmetric matrix
Vect3 diag() const {return Vect3(xx, yy, zz);}
Vect3 sym() const {return Vect3(yz, zx, xy);}
// input / output ////////////////////////////////////////////////////////////
ostream& print(ostream &os) const;
// operations not returning a Mat3 ///////////////////////////////////////////
inline Real det() const;
// operations returning result via this //////////////////////////////////////
// The operation result indicated by the comments is always returned
// in this. The symbol [!] indicates that this must be distinct
// from all of the operands. The invert() methods are based on the
// explicit inversion formula from determinants; there are faster
// and more accurate ways. The invert() methods return one if the
// matrix was not invertible, otherwise zero.
inline void xpose(const Mat3 &M); // M^T [!]
inline void xpose(); // this^T
inline void symmetrize(const Mat3 &M); // M + M^T
inline void symmetrize(); // this + this^T
int invert(const Mat3 &M); // M^-1 [!]
int invert(); // this^-1
inline void negate(const Mat3 &M); // -M
inline void negate(); // -this
inline void add(const Mat3 &M, const Mat3 &N); // M + N
inline void add(const Mat3 &M); // this + M
inline void sub(const Mat3 &M, const Mat3 &N); // M - N
inline void sub(const Mat3 &M); // this - M
inline void scale(const Mat3 &M, Real s); // s * M
inline void scale(Real s); // s * this
void mult(const Mat3 &M, const Mat3 &N); // M * N [!]
void premult(const Mat3 &M); // M * this [!]
void postmult(const Mat3 &M); // this * M [!]
// Transforming Vect3s ///////////////////////////////////////////////////////
inline void xform(const Vect3 &v, Vect3 &xv) const; // (this)(v) => xv;
// v & xv must be distinct
inline void xform(Vect3 &v) const; // (this)(v) => v
// These are exactly like the above methods, except the inverse
// transform this^-1 (= this^T) is used. This can be thought of as
// a row vector transformation, e.g.: (v^T)(this) => xv^T
inline void invXform(const Vect3 &v, Vect3 &xv) const;
inline void invXform(Vect3 &v) const;
// Mat3 constants ////////////////////////////////////////////////////////////
static const Mat3 ZERO; // zero matrix
static const Mat3 ID; // identity matrix
};
///////////////////////////////////////////////////////////////////////////////
//
// class MatX
//
///////////////////////////////////////////////////////////////////////////////
class MatX {
friend class Se3;
private:
Mat3 R;
Vect3 d;
public:
// constructors //////////////////////////////////////////////////////////////
MatX() {}
MatX(const Mat3 &R_, const Vect3 &d_) {set(R_, d_);}
MatX(const Se3 &T) {set(T);}
// setters / accessors / translators /////////////////////////////////////////
inline void set(const Mat3 &R_, const Vect3 &d_) {R = R_; d = d_;}
inline void set(const Se3 &T);
const Mat3 &rot() const {return R;}
const Vect3 &trans() const {return d;}
Mat3 &rot() {return R;}
Vect3 &trans() {return d;}
// input / output ////////////////////////////////////////////////////////////
inline ostream& print(ostream &os) const;
inline istream& read(istream &is);
// operations returning result via this //////////////////////////////////////
// The operation result indicated by the comments is always returned
// in this. The symbol [!] indicates that this must be distinct
// from all of the operands.
void mult(const MatX &M, const MatX &N); // M * N [!]
void premult(const MatX &M); // M * this [!]
void postmult(const MatX &M); // this * M [!]
void invert(const MatX &M); // M^-1 [!]
void invert(); // this^-1
// Transforming Vect3s ///////////////////////////////////////////////////////
// MatXs can transform elements of R^3 either as vectors or as
// points. The [!] indicates that the operands must be distinct.
inline void xformVect(const Vect3 &v, Vect3 &xv) const; // this*(v 0)=>xv [!]
inline void xformVect(Vect3 &v) const; // this*(v 0)=>v
inline void xformPoint(const Vect3 &p, Vect3 &xp) const;// this*(p 1)=>xp [!]
inline void xformPoint(Vect3 &p) const; // this*(p 1)=>p
// These are exactly like the above methods, except the inverse
// transform this^-1 is used.
inline void invXformVect(const Vect3 &v, Vect3 &xv) const;
inline void invXformVect(Vect3 &v) const;
inline void invXformPoint(const Vect3 &p, Vect3 &xp) const;
inline void invXformPoint(Vect3 &p) const;
// MatX constants ////////////////////////////////////////////////////////////
static const MatX ID; // identity matrix
};
///////////////////////////////////////////////////////////////////////////////
//
// class Quat
//
///////////////////////////////////////////////////////////////////////////////
class Quat {
friend class Mat3;
friend class Se3;
private:
Real s_, x_, y_, z_;
public:
// constructors //////////////////////////////////////////////////////////////
Quat() {}
Quat(Real s, Real x, Real y, Real z) {set(s, x, y, z);}
Quat(Real angle, const Vect3 &axis, int normalizeAxis = 1)
{set(angle, axis, normalizeAxis);}
Quat(const Mat3 &R) {set(R);}
// setters / accessors / translators /////////////////////////////////////////
void set(Real s, Real x, Real y, Real z) {s_=s; x_=x; y_=y; z_=z;}
// set a quaternion to a rotation of 'angle' radians about 'axis'
// the axis passed is automatically normalized unless normalizeAxis = 0
void set(Real angle, const Vect3 &axis, int normalizeAxis = 1);
void set(const Mat3 &R);
#if INVENTOR
inline void set(const SbRotation &R);
inline void toSbRotation(SbRotation &R) const;
#endif
Real s() const {return s_;}
Real x() const {return x_;}
Real y() const {return y_;}
Real z() const {return z_;}
inline Vect3 axis() const; // normalized axis of rotation
inline Real angle() const; // angle of rotation in radians, in range [0, 2pi)
// input / output ////////////////////////////////////////////////////////////
ostream& print(ostream &os) const;
// operations not returning a Quat ///////////////////////////////////////////
int operator==(const Quat &other)
{return s_ == other.s_ && x_ == other.x_
&& y_ == other.y_ && z_ == other.z_;}
// operations returning result via this //////////////////////////////////////
// The operation result indicated by the comments is always returned
// in this. The symbol [!] indicates that this must be distinct
// from all of the operands.
inline void normalize(const Quat &q); // q/|q|
inline void normalize(); // this/|this|
inline void invert(const Quat &q); // q^-1
inline void invert(); // this^-1
void mult(const Quat &p, const Quat &q); // p * q [!]
void premult(const Quat &q); // q * this [!]
void postmult(const Quat &q); // this * q [!]
// Transforming Vect3s ///////////////////////////////////////////////////////
void xform(const Vect3 &u, Vect3 &v) const; // this (v 0) this^-1 => xv
void xform(Vect3 &v) const; // this (v 0) this^-1 => v
// These are exactly like the above methods, except the inverse
// transform is used (i.e. the factors this and this^-1 are swapped).
void invXform(const Vect3 &v, Vect3 &xv) const;
void invXform(Vect3 &v) const;
// miscellaneous /////////////////////////////////////////////////////////////
// Return the quaternion derivatives in 'this', given a current
// orientation q and body angular velocity w. Note that what is
// returned in 'this' is not a unit quaternion, but the derivative
// of one!
inline void deriv(const Quat &q, const Vect3 &w);
// Quat constants ////////////////////////////////////////////////////////////
static const Quat ID; // identity quaternion
};
///////////////////////////////////////////////////////////////////////////////
//
// class Se3
//
///////////////////////////////////////////////////////////////////////////////
class Se3 {
friend class MatX;
private:
Quat q; // rotation component
Vect3 d; // translation component
public:
// constructors //////////////////////////////////////////////////////////////
Se3() {}
Se3(const Quat &q_, const Vect3 &d_) {set(q_, d_);}
Se3(const MatX &X) {set(X);}
// setters / accessors / translators /////////////////////////////////////////
void set(const Quat &q_, const Vect3 &d_) {q = q_; d = d_;}
void set(const MatX &X) {q.set(X.R); d = X.d;}
#if INVENTOR
inline void set(const SoTransform *T);
inline void toSoTransform(SoTransform *T) const;
#endif
const Quat &rot() const {return q;}
const Vect3 &trans() const {return d;}
Quat &rot() {return q;}
Vect3 &trans() {return d;}
// input / output ////////////////////////////////////////////////////////////
inline ostream& print(ostream &os) const;
// Read Se3 from input stream. The Se3 specification must be
// enclosed in curly brackets { }. Se3's are built up from a
// sequence of translation and rotation operations. A translation
// opereration is specified by "trans v", where v is the translation
// vector. A rotation operation is specified by: "rot a v", where a
// is the scalar rotation in *degrees*, and v is the axis of
// rotation (a vector).
istream& read(istream &is);
// operations returning result via this //////////////////////////////////////
// The operation result indicated by the comments is always returned
// in this. The symbol [!] indicates that this must be distinct
// from all of the operands.
inline void mult(const Se3 &T, const Se3 &U); // T * U [!]
inline void premult(const Se3 &T); // T * this [!]
inline void postmult(const Se3 &T); // this * T [!]
inline void invert(const Se3 &T); // T^-1
inline void invert(); // this^-1
// Transforming Vect3s ///////////////////////////////////////////////////////
// Se3s can transform elements of R^3 either as vectors or as
// points. Multiple operands need not be distinct.
inline void xformVect(const Vect3 &v, Vect3 &xv) const; // this * (v 0) => xv
inline void xformVect(Vect3 &v) const; // this * (v 0) => v
inline void xformPoint(const Vect3 &p, Vect3 &xp) const; // this * (p 1) => xp
inline void xformPoint(Vect3 &p) const; // this * (p 1) => p
// These are exactly like the above methods, except the inverse
// transform this^-1 is used.
inline void invXformVect(const Vect3 &v, Vect3 &xv) const;
inline void invXformVect(Vect3 &v) const;
inline void invXformPoint(const Vect3 &p, Vect3 &xp) const;
inline void invXformPoint(Vect3 &p) const;
// Se3 constants /////////////////////////////////////////////////////////////
static const Se3 ID; // identity Se3
};
///////////////////////////////////////////////////////////////////////////////
//
// stream operators
//
///////////////////////////////////////////////////////////////////////////////
inline ostream &operator<<(ostream &os, const Vect3 &v) {return v.print(os);}
inline ostream &operator<<(ostream &os, const Mat3 &M) {return M.print(os);}
inline ostream &operator<<(ostream &os, const MatX &X) {return X.print(os);}
inline ostream &operator<<(ostream &os, const Quat &q) {return q.print(os);}
#if defined(_WIN32)
inline ostream &operator<<(ostream &os, const Se3 &T) {return T.print(os);}
#else
inline ostream &operator<<(ostream &os, const Se3 &T) {return T.print(os);}
#endif
inline istream &operator>>(istream &os, Vect3 &v) {return v.read(os);}
inline istream &operator>>(istream &is, MatX &X) {return X.read(is);}
inline istream &operator>>(istream &is, Se3 & T) {return T.read(is);}
///////////////////////////////////////////////////////////////////////////////
//
// inline function definitions
//
///////////////////////////////////////////////////////////////////////////////
#if INVENTOR
void Vect3::set(const SbVec3f &vec)
{
const float *v = vec.getValue();
x = v[0]; y = v[1]; z = v[2];
}
#endif
#if INVENTOR
void Vect3::toSbVec3f(SbVec3f &vec) const
{
#if OPCOUNTS
vec.setValue(x.toDouble(), y.toDouble(), z.toDouble());
#else
vec.setValue(x, y, z);
#endif
}
#endif
int Vect3::operator==(const Vect3 &other) const
{
return x == other.x && y == other.y && z == other.z;
}
Real Vect3::dot(const Vect3 &other) const
{
return x * other.x + y * other.y + z * other.z;
}
Real Vect3::norm() const
{
return sqrt(x * x + y * y + z * z);
}
Real Vect3::norm2() const
{
return (x * x + y * y + z * z);
}
Real Vect3::distance(const Vect3 &other) const
{
Vect3 w;
w.sub(other, *this);
return w.norm();
}
Real Vect3::distance2(const Vect3 &other) const
{
Vect3 w;
w.sub(other, *this);
return w.norm2();
}
Real Vect3::min() const
{
return (x <= y) ? ((x <= z) ? x : z) : ((y <= z) ? y : z);
}
Real Vect3::max() const
{
return (x >= y) ? ((x >= z) ? x : z) : ((y >= z) ? y : z);
}
Real Vect3::minAbs() const
{
Real ax, ay, az;
ax = fabs(x);
ay = fabs(y);
az = fabs(z);
return (ax <= ay) ? ((ax <= az) ? ax : az) : ((ay <= az) ? ay : az);
}
Real Vect3::maxAbs() const
{
Real ax, ay, az;
ax = fabs(x);
ay = fabs(y);
az = fabs(z);
return (ax >= ay) ? ((ax >= az) ? ax : az) : ((ay >= az) ? ay : az);
}
void Vect3::swap(Vect3 &other)
{
Vect3 tmp;
tmp = *this;
*this = other;
other = tmp;
}
void Vect3::normalize(const Vect3 &v)
{
Real s;
s = 1.0 / sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
x = s * v.x;
y = s * v.y;
z = s * v.z;
}
void Vect3::normalize()
{
Real s;
s = 1.0 / sqrt(x * x + y * y + z * z);
x *= s;
y *= s;
z *= s;
}
void Vect3::negate(const Vect3 &v)
{
x = - v.x;
y = - v.y;
z = - v.z;
}
void Vect3::negate()
{
x = - x;
y = - y;
z = - z;
}
void Vect3::add(const Vect3 &u, const Vect3 &v)
{
x = u.x + v.x;
y = u.y + v.y;
z = u.z + v.z;
}
void Vect3::add(const Vect3 &v)
{
x += v.x;
y += v.y;
z += v.z;
}
void Vect3::sub(const Vect3 &u, const Vect3 &v)
{
x = u.x - v.x;
y = u.y - v.y;
z = u.z - v.z;
}
void Vect3::sub(const Vect3 &v)
{
x -= v.x;
y -= v.y;
z -= v.z;
}
void Vect3::mult(const Vect3 &u, const Vect3 &v)
{
x = u.x * v.x;
y = u.y * v.y;
z = u.z * v.z;
}
void Vect3::mult(const Vect3 &v)
{
x *= v.x;
y *= v.y;
z *= v.z;
}
void Vect3::scale(const Vect3 &v, Real s)
{
x = s * v.x;
y = s * v.y;
z = s * v.z;
}
void Vect3::scale(Real s)
{
x *= s;
y *= s;
z *= s;
}
void Vect3::cross(const Vect3 &u, const Vect3 &v)
{
x = u.y * v.z - u.z * v.y;
y = u.z * v.x - u.x * v.z;
z = u.x * v.y - u.y * v.x;
}
void Vect3::precross(const Vect3 &v)
{
Real ox, oy;
ox = x;
oy = y;
x = v.y * z - v.z * oy;
y = v.z * ox - v.x * z;
z = v.x * oy - v.y * ox;
}
void Vect3::postcross(const Vect3 &v)
{
Real ox, oy;
ox = x;
oy = y;
x = oy * v.z - z * v.y;
y = z * v.x - ox * v.z;
z = ox * v.y - oy * v.x;
}
void Vect3::crossAdd(const Vect3 &u, const Vect3 &v, const Vect3 &w)
{
x = u.y * v.z - u.z * v.y + w.x;
y = u.z * v.x - u.x * v.z + w.y;
z = u.x * v.y - u.y * v.x + w.z;
}
void Vect3::crossAdd(const Vect3 &u, const Vect3 &v)
{
x += u.y * v.z - u.z * v.y;
y += u.z * v.x - u.x * v.z;
z += u.x * v.y - u.y * v.x;
}
void Vect3::displace(const Vect3 &v, const Vect3 &u, Real lambda)
{
x = v.x + lambda * u.x;
y = v.y + lambda * u.y;
z = v.z + lambda * u.z;
}
void Vect3::displace(const Vect3 &u, Real lambda)
{
x += lambda * u.x;
y += lambda * u.y;
z += lambda * u.z;
}
void Vect3::interpolate(const Vect3 &u, const Vect3 &v, Real lambda)
{
Real lambda2 = 1.0 - lambda;
x = lambda2 * u.x + lambda * v.x;
y = lambda2 * u.y + lambda * v.y;
z = lambda2 * u.z + lambda * v.z;
}
void Mat3::set(const Vect3 &diag, const Vect3 &sym)
{
xx = diag.x;
yy = diag.y;
zz = diag.z;
yz = zy = sym.x;
zx = xz = sym.y;
xy = yx = sym.z;
}
void Mat3::set(const Vect3 &axis, Real angle, int normalizeAxis)
{
Quat q;
q.set(angle, axis, normalizeAxis);
set(q);
}
void Mat3::setXcol(const Vect3 &v)
{
xx = v.x;
yx = v.y;
zx = v.z;
}
void Mat3::setYcol(const Vect3 &v)
{
xy = v.x;
yy = v.y;
zy = v.z;
}
void Mat3::setZcol(const Vect3 &v)
{
xz = v.x;
yz = v.y;
zz = v.z;
}
void Mat3::setSkew(const Vect3 &v)
{
xx = yy = zz = 0.0;
zy = v.x;
yz = -v.x;
xz = v.y;
zx = -v.y;
yx = v.z;
xy = -v.z;
}
Real Mat3::det() const
{
return xx * (yy * zz - yz * zy)
+ xy * (yz * zx - yx * zz)
+ xz * (yx * zy - yy * zx);
}
void Mat3::xpose(const Mat3 &M)
{
xx = M.xx;
xy = M.yx;
xz = M.zx;
yx = M.xy;
yy = M.yy;
yz = M.zy;
zx = M.xz;
zy = M.yz;
zz = M.zz;
}
void Mat3::xpose()
{
Real tmp;
tmp = xy;
xy = yx;
yx = tmp;;
tmp = yz;
yz = zy;
zy = tmp;
tmp = zx;
zx = xz;
xz = tmp;
}
void Mat3::symmetrize(const Mat3 &M)
{
xx = 2 * M.xx;
yy = 2 * M.yy;
zz = 2 * M.zz;
xy = yx = M.xy + M.yx;
yz = zy = M.yz + M.zy;
zx = xz = M.zx + M.xz;
}
void Mat3::symmetrize()
{
xx = 2 * xx;
yy = 2 * yy;
zz = 2 * zz;
xy = yx = xy + yx;
yz = zy = yz + zy;
zx = xz = zx + xz;
}
void Mat3::negate(const Mat3 &M)
{
xx = - M.xx;
xy = - M.xy;
xz = - M.xz;
yx = - M.yx;
yy = - M.yy;
yz = - M.yz;
zx = - M.zx;
zy = - M.zy;
zz = - M.zz;
}
void Mat3::negate()
{
xx = - xx;
xy = - xy;
xz = - xz;
yx = - yx;
yy = - yy;
yz = - yz;
zx = - zx;
zy = - zy;
zz = - zz;
}
void Mat3::add(const Mat3 &M, const Mat3 &N)
{
xx = M.xx + N.xx;
xy = M.xy + N.xy;
xz = M.xz + N.xz;
yx = M.yx + N.yx;
yy = M.yy + N.yy;
yz = M.yz + N.yz;
zx = M.zx + N.zx;
zy = M.zy + N.zy;
zz = M.zz + N.zz;
}
void Mat3::add(const Mat3 &M)
{
xx += M.xx;
xy += M.xy;
xz += M.xz;
yx += M.yx;
yy += M.yy;
yz += M.yz;
zx += M.zx;
zy += M.zy;
zz += M.zz;
}
void Mat3::sub(const Mat3 &M, const Mat3 &N)
{
xx = M.xx - N.xx;
xy = M.xy - N.xy;
xz = M.xz - N.xz;
yx = M.yx - N.yx;
yy = M.yy - N.yy;
yz = M.yz - N.yz;
zx = M.zx - N.zx;
zy = M.zy - N.zy;
zz = M.zz - N.zz;
}
void Mat3::sub(const Mat3 &M)
{
xx -= M.xx;
xy -= M.xy;
xz -= M.xz;
yx -= M.yx;
yy -= M.yy;
yz -= M.yz;
zx -= M.zx;
zy -= M.zy;
zz -= M.zz;
}
void Mat3::scale(const Mat3 &M, Real s)
{
xx = s * M.xx;
xy = s * M.xy;
xz = s * M.xz;
yx = s * M.yx;
yy = s * M.yy;
yz = s * M.yz;
zx = s * M.zx;
zy = s * M.zy;
zz = s * M.zz;
}
void Mat3::scale(Real s)
{
xx *= s;
xy *= s;
xz *= s;
yx *= s;
yy *= s;
yz *= s;
zx *= s;
zy *= s;
zz *= s;
}
void Mat3::xform(const Vect3 &v, Vect3 &xv) const
{
xv.x = xx * v.x + xy * v.y + xz * v.z;
xv.y = yx * v.x + yy * v.y + yz * v.z;
xv.z = zx * v.x + zy * v.y + zz * v.z;
}
void Mat3::xform(Vect3 &v) const
{
Real ox, oy;
ox = v.x; oy= v.y;
v.x = xx * ox + xy * oy + xz * v.z;
v.y = yx * ox + yy * oy + yz * v.z;
v.z = zx * ox + zy * oy + zz * v.z;
}
void Mat3::invXform(const Vect3 &v, Vect3 &xv) const
{
xv.x = xx * v.x + yx * v.y + zx * v.z;
xv.y = xy * v.x + yy * v.y + zy * v.z;
xv.z = xz * v.x + yz * v.y + zz * v.z;
}
void Mat3::invXform(Vect3 &v) const
{
Real ox, oy;
ox = v.x; oy= v.y;
v.x = xx * ox + yx * oy + zx * v.z;
v.y = xy * ox + yy * oy + zy * v.z;
v.z = xz * ox + yz * oy + zz * v.z;
}
void MatX::set(const Se3 &T)
{
R.set(T.q);
d = T.d;
}
ostream& MatX::print(ostream &os) const
{
return os << R << d << "\n";
}
istream& MatX::read(istream &is)
{
Se3 T;
is >> T;
set(T);
return is;
}
void MatX::xformVect(const Vect3 &v, Vect3 &xv) const
{
R.xform(v, xv);
}
void MatX::xformVect(Vect3 &v) const
{
R.xform(v);
}
void MatX::xformPoint(const Vect3 &p, Vect3 &xp) const
{
R.xform(p, xp);
xp.add(d);
}
void MatX::xformPoint(Vect3 &p) const
{
R.xform(p);
p.add(d);
}
void MatX::invXformVect(const Vect3 &v, Vect3 &xv) const
{
R.invXform(v, xv);
}
void MatX::invXformVect(Vect3 &v) const
{
R.invXform(v);
}
void MatX::invXformPoint(const Vect3 &p, Vect3 &xp) const
{
xp.sub(p, d);
R.invXform(xp);
}
void MatX::invXformPoint(Vect3 &p) const
{
p.sub(d);
R.invXform(p);
}
#if INVENTOR
void Quat::set(const SbRotation &rot)
{
const float *q = rot.getValue();
s_ = q[3]; x_ = q[0]; y_ = q[1]; z_ = q[2];
}
#endif
#if INVENTOR
void Quat::toSbRotation(SbRotation &rot) const
{
#if OPCOUNTS
rot.setValue(x_.toDouble(), y_.toDouble(), z_.toDouble(), s_.toDouble());
#else
rot.setValue(x_, y_, z_, s_);
#endif
}
#endif
Vect3 Quat::axis() const
{
Vect3 v(x_, y_, z_);
if (v.norm() == 0.0) v = Vect3::I; // axis is arbitrary here
else v.normalize();
return v;
}
Real Quat::angle() const
{
#if OPCOUNTS
return 2 * acos(s_.toDouble());
#else
return 2 * acos(s_);
#endif
}
void Quat::normalize(const Quat &q)
{
Real scale;
scale = 1.0 / sqrt(q.s_*q.s_ + q.x_*q.x_ + q.y_*q.y_ + q.z_*q.z_);
s_ = scale * q.s_;
x_ = scale * q.x_;
y_ = scale * q.y_;
z_ = scale * q.z_;
}
void Quat::normalize()
{
Real scale;
scale = 1.0 / sqrt(s_*s_ + x_*x_ + y_*y_ + z_*z_);
s_ *= scale;
x_ *= scale;
y_ *= scale;
z_ *= scale;
}
void Quat::invert(const Quat &q)
{
s_ = -q.s_;
x_ = q.x_;
y_ = q.y_;
z_ = q.z_;
}
void Quat::invert()
{
s_ = -s_;
}
void Quat::deriv(const Quat &q, const Vect3 &w)
{
s_ = 0.5 * (-q.x_ * w.x - q.y_ * w.y - q.z_ * w.z);
x_ = 0.5 * ( q.s_ * w.x - q.z_ * w.y + q.y_ * w.z);
y_ = 0.5 * ( q.z_ * w.x + q.s_ * w.y - q.x_ * w.z);
z_ = 0.5 * (-q.y_ * w.x + q.x_ * w.y + q.s_ * w.z);
}
#if INVENTOR
void Se3::set(const SoTransform *xform)
{
const float *quat;
const float *trans;
quat = xform->rotation.getValue().getValue();
q.x_ = quat[0]; q.y_ = quat[1]; q.z_ = quat[2]; q.s_ = quat[3];
trans = xform->translation.getValue().getValue();
d.x = trans[0];
d.y = trans[1];
d.z = trans[2];
}
#endif
#if INVENTOR
void Se3::toSoTransform(SoTransform *xform) const
{
#if OPCOUNTS
xform->rotation.setValue
(q.x_.toDouble(), q.y_.toDouble(), q.z_.toDouble(), q.s_.toDouble());
xform->translation.setValue(d.x.toDouble(), d.y.toDouble(), d.z.toDouble());
#else
xform->rotation.setValue(q.x_, q.y_, q.z_, q.s_);
xform->translation.setValue(d.x, d.y, d.z);
#endif
}
#endif
ostream& Se3::print(ostream &os) const
{
return os << q << d;
}
void Se3::mult(const Se3 &T, const Se3 &U)
{
q.mult(T.q, U.q);
T.q.xform(U.d, d);
d.add(d, T.d);
}
void Se3::premult(const Se3 &T)
{
q.premult(T.q);
T.q.xform(d);
d.add(T.d);
}
void Se3::postmult(const Se3 &T)
{
Vect3 v;
q.xform(T.d, v);
d.add(v);
q.postmult(T.q);
}
void Se3::invert(const Se3 &T)
{
q.s_ = -T.q.s_;
q.x_ = T.q.x_;
q.y_ = T.q.y_;
q.z_ = T.q.z_;
q.xform(T.d, d);
d.negate(d);
}
void Se3::invert()
{
q.s_ = -q.s_;
q.xform(d);
d.negate();
}
void Se3::xformVect(const Vect3 &v, Vect3 &xv) const
{
q.xform(v, xv);
}
void Se3::xformVect(Vect3 &v) const
{
q.xform(v);
}
void Se3::xformPoint(const Vect3 &p, Vect3 &xp) const
{
q.xform(p, xp);
xp.add(d);
}
void Se3::xformPoint(Vect3 &p) const
{
q.xform(p);
p.add(d);
}
void Se3::invXformVect(const Vect3 &v, Vect3 &xv) const
{
q.invXform(v, xv);
}
void Se3::invXformVect(Vect3 &v) const
{
q.invXform(v);
}
void Se3::invXformPoint(const Vect3 &p, Vect3 &xp) const
{
xp.sub(p, d);
q.invXform(xp);
}
void Se3::invXformPoint(Vect3 &p) const
{
p.sub(d);
q.invXform(p);
}
#endif // #ifndef MV_H
| [
"hgtf@cin.ufpe.br"
] | hgtf@cin.ufpe.br |
cf4a28f1942f147f352cae7d14a5cc459bdc3c33 | a3793ffa7a5d5f7a39da43e40e8dc48170198fab | /src/matrix_info.cpp | 94fdd27bd75bbf78762ce8843009309171e94a3d | [] | no_license | MarioniLab/archive-cydar | 84b9222ed036233d1459ba3d71ef2bdc95228187 | d3edfc75293758552d14564ef8c8fc3dc018d9be | refs/heads/master | 2021-06-18T10:46:00.489736 | 2017-05-25T09:26:37 | 2017-05-25T09:26:37 | 65,463,471 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 759 | cpp | #include "cydar.h"
#include "utils.h"
matrix_info::matrix_info (int nr, int nc, const double* ptr) : nrow(nr), ncol(nc), dptr(ptr) {}
matrix_info check_matrix(SEXP matrix) {
if (!isReal(matrix)) {
throw std::runtime_error("matrix must be double-precision");
}
SEXP dims=getAttrib(matrix, R_DimSymbol);
if (!isInteger(dims) || LENGTH(dims)!=2) {
throw std::runtime_error("dimensions of the matrix should be an integer vector of length 2");
}
int nrow=INTEGER(dims)[0], ncol=INTEGER(dims)[1];
if (LENGTH(matrix)!=nrow*ncol) {
throw std::runtime_error("recorded dimensions of the matrix are not consistent with its length");
}
matrix_info output(nrow, ncol, REAL(matrix));
return output;
}
| [
"alun@wehi.edu.au"
] | alun@wehi.edu.au |
7c50b60ac2a634d2c15a8e229494f41e19cadef7 | a75d0418b2143d6f59635a8833bff49bc903df5e | /DofusMessages/GameRolePlayArenaUnregisterMessage.cpp | 413bef3dff54cc4629a6896b4b164e1b2e590602 | [] | no_license | Arkwell9112/dofus_bot | 30b80850ba41b6a2b562705ec8aa1a6c87cfb8f8 | fc1b805b70c0ed43cbc585322806ece89d057585 | refs/heads/master | 2023-01-16T01:08:06.710649 | 2020-11-23T20:53:00 | 2020-11-23T20:53:00 | 314,084,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 167 | cpp | #include "GameRolePlayArenaUnregisterMessage.h"
#include "../BotCoreAPI/BotCoreAPI.h"
void GameRolePlayArenaUnregisterMessage::deserialize(CustomDataInput *input) {
} | [
"arkwell9112@github.com"
] | arkwell9112@github.com |
746b27dd57f3b89377dd91d6847027487284b3cb | 3715937dda2f795275535ded560d4dcf07ca0294 | /Flashing_LED/Flashing_LED.ino | 825384e4300758703b19b2cb6869657195a17212 | [] | no_license | JoelBarlow-Sikorsky-Challenge/2019-2020Module2 | 2873f8a2c44e2fe3f95e6deae234fcad6ff86ef2 | 635506c1e32395823f7b96e60f9fcc40c527dcb1 | refs/heads/master | 2020-08-15T16:45:10.682222 | 2019-10-16T20:47:01 | 2019-10-16T20:47:01 | 215,373,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 191 | ino | #define LED_PIN 6
int wait = 1000;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
digitalWrite(LED_PIN, HIGH);
delay(wait);
digitalWrite(LED_PIN, HIGH);
delay(wait);
}
| [
"kolcrooks10@gmail.com"
] | kolcrooks10@gmail.com |
6435c957bffa27176331a6104c167a8ce68e03ff | be5d9a7f6d2630703fcccb0fb51a82b249341a30 | /SimulGenet/src/qt+/qdslider.cpp | 09c2d12335b2097fe6e3e88fa429ad5bf3cab161 | [] | no_license | Shellloman/SimulGenet | dac6756f9f8f998294d4d2a4e3dd48051be0c1ab | 8fc66fef75fbd4d9d4966d2a5b1c12e3dbd9a163 | refs/heads/master | 2020-11-26T11:24:19.738166 | 2020-11-01T12:40:48 | 2020-11-01T12:40:48 | 229,048,601 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 381 | cpp | #include "qdslider.h"
QDSlider::QDSlider(QWidget *parent,double pourcentage) : QSlider(Qt::Horizontal,parent) {
pourcent = pourcentage;
QObject::connect(this, SIGNAL(valueChanged(int)),
this, SLOT(notifyValueChanged(int)));
}
void QDSlider::notifyValueChanged(int value) {
double doubleValue = value / pourcent;
emit doubleValueChanged(doubleValue);
}
| [
"lineozinc@gmail.com"
] | lineozinc@gmail.com |
fe859eb765ed43fdc66d7370086bbdabcd43cff7 | 340cdfbbf38fe450268119dff003f8729d99777b | /plugins/pong-plugin.cpp | bf4780e8516501bbbd6050b99c0b12b20f200856 | [] | no_license | bluechill/ircd | 262cc426b1ad0eec35e07c94cac8d9065790d8a7 | 500d792a5c694ad8b2be8e6f9c5d1181d74d0c34 | refs/heads/master | 2020-12-24T13:43:52.580473 | 2013-01-30T20:48:14 | 2013-01-30T20:48:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,752 | cpp | #include "IRC_Server.h"
#include "IRC_Plugin.h"
#include <string.h>
#include <vector>
#include <string>
#include <errno.h>
static pthread_t ping_thread;
void* ping_thread_function(void* data)
{
using namespace std;
IRC_Server *link = reinterpret_cast<IRC_Server*>(data);
vector<IRC_Server::User*>* users = link->get_users();
struct timespec current_time;
double double_current_time = 0.0;
link->lock_message_mutex();
for (vector<IRC_Server::User*>::iterator it = users->begin();it != users->end();it++)
(*it)->ping_timer = -1;
link->unlock_message_mutex();
while (true)
{
sleep(1);
current_time = link->get_current_time();
double_current_time = (double(current_time.tv_sec) + double(current_time.tv_nsec)/double(1E9));
link->lock_message_mutex();
for (vector<IRC_Server::User*>::iterator it = users->begin();it != users->end();it++)
{
IRC_Server::User* user = *it;
double user_time = user->ping_timer;
if ((user_time - double_current_time) > double(30) &&
(user_time - double_current_time) < double(35) &&
!(user->nick.size() == 0 || user->username.size() == 0) &&
user->ping_contents == "")
{
string ping_message = "PING :" + link->get_hostname() + IRC_Server::irc_ending;
user->ping_timer = double_current_time + 30;
user->ping_contents = link->get_hostname();
link->send_message(ping_message, user);
}
else if ((user_time - double_current_time) < 0)
{
string quit_message = "ERROR :Closing Link: " + user->nick + "[" + user->hostname + "] (Ping Timeout)" + IRC_Server::irc_ending;
link->send_message(quit_message, user);
IRC_Server::User* temp_user = new IRC_Server::User;
temp_user->channels = user->channels;
temp_user->nick = user->nick;
temp_user->username = user->username;
temp_user->hostname = user->hostname;
link->unlock_message_mutex();
link->disconnect_client(user->client, "PING");
link->lock_message_mutex();
it--;
string output = ":" + temp_user->nick + "!" + temp_user->username + "@" + temp_user->hostname + " QUIT :Ping Timeout" + IRC_Server::irc_ending;
link->broadcast_message(output, temp_user->channels, false);
}
}
link->unlock_message_mutex();
};
}
extern "C" void init(IRC_Server* link)
{
using namespace std;
int status = pthread_create(&ping_thread, NULL, ping_thread_function, link);
if (status)
{
cerr << "Failed to create ping thread with error: " << status << " (\"" << strerror(errno) << "\")" << endl;
throw Server::Thread_Initialization_Failure;
}
}
extern "C" std::vector<IRC_Plugin::Call_Type> get_supported_calls()
{
std::vector<IRC_Plugin::Call_Type> types;
types.push_back(IRC_Plugin::ON_RECIEVE_MESSAGE);
return types;
}
extern "C" std::string name_of_plugin()
{
return "PONG";
}
extern "C" IRC_Plugin::Result_Of_Call plugin_call(IRC_Plugin::Call_Type type, IRC_Server::User* user, std::vector<std::string> &parts, IRC_Server* link)
{
using namespace std;
if (type != IRC_Plugin::ON_RECIEVE_MESSAGE)
return IRC_Plugin::NOT_HANDLED;
if (strncasecmp(parts[0].c_str(), "PONG", 4) != 0)
return IRC_Plugin::NOT_HANDLED;
if (parts.size() != 2)
{
if (parts.size() == 1)
link->send_error_message(user, IRC_Server::ERR_NEEDMOREPARAMS, "PONG");
return IRC_Plugin::HANDLED;
}
link->lock_message_mutex();
std::string contents = parts[1];
if (user->ping_contents == contents)
{
struct timespec current_time;
current_time = link->get_current_time();
user->ping_timer = (double(current_time.tv_sec) + double(current_time.tv_nsec)/double(1E9)) + 60;
user->ping_contents = "";
}
link->unlock_message_mutex();
return IRC_Plugin::HANDLED;
}
| [
"bluechill@me.com"
] | bluechill@me.com |
cf94635a05fbecdd327ebb722f77acaea7a2573e | 35f9797267668378aa0e13adb440feb6f70d79d6 | /Task.h | 0941e74dca8ab4cf87a002b7d1d8064ef0c148b9 | [] | no_license | wbs0829/sudoku | ae0175dc53eb7a812e6b0140a41a2921f429b611 | 714a7aeec469a1f077d85ce06efdce5f1ec0edf9 | refs/heads/master | 2021-01-02T23:12:55.514292 | 2012-07-24T08:29:40 | 2012-07-24T08:29:40 | 4,746,306 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | h | #ifndef SUDOKU_TASK_H
#define SUDOKU_TASK_H
#include "Cell.h"
/*
* The members, row and col, in Cell have more meaning when in Task.
*/
class Task : public Cell
{
public:
enum Information{ ImpoCell, ImpoHorGroup, ImpoVerGroup, KnownHorGroup, KnownVerGroup};
Information info;
Task(const Cell &r, Information i) : info(i) {row = r.row; col = r.col; num = r.num; }
};
#endif
| [
"wbs.y829@gmail.com"
] | wbs.y829@gmail.com |
bb90149c755af6cc64e147df0298dfff7d52ac74 | acaabf966ede742a1f5325ce5ebc83e31fe90c0a | /Week2/Student_Docent/Student_Docent/Teacher.cpp | 66f9bd819609b2c135015326d7434a596aa6b2da | [] | no_license | DanielBergshoeff/OOPBasic | d95f87eb62992bb3583c6795b9b278e62792d286 | 87bdd97700454e32fcb82983ee1201a09db91f96 | refs/heads/master | 2020-03-28T19:41:23.313815 | 2018-10-24T19:11:26 | 2018-10-24T19:11:26 | 149,000,267 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 208 | cpp | #include "stdafx.h"
#include "Teacher.h"
Teacher::Teacher(int agep, string namep, int contractHoursPerWeekp)
:Person(agep, namep), contractHoursPerWeek(contractHoursPerWeekp)
{
}
Teacher::~Teacher()
{
}
| [
"dabergshoeff@gmail.com"
] | dabergshoeff@gmail.com |
0af5eca3c120a67acfe3919b6be1ba5fe0c4b015 | 8f3581a6f6126737e65f7c5a0171693311cc585b | /Source/TBD/SpecialActors/SlimePuddleParent.h | 634212de83cd152915b8ad3dbb623a47f3e48d14 | [] | no_license | Snollygoester/TBD | 18ef42803d108943ab71f49ae62d4d9c7f5c59f2 | 91116e129a49ebe5ce089d9ec5cf765ccf8d1e6c | refs/heads/master | 2020-04-06T16:00:00.225886 | 2019-01-09T15:41:22 | 2019-01-09T15:41:22 | 157,601,347 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,764 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "PuddleParent.h"
#include "SlimePuddleParent.generated.h"
UCLASS()
class TBD_API ASlimePuddleParent : public APuddleParent
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ASlimePuddleParent();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
private:
UPROPERTY()
TArray<class UStaticMeshComponent *> Slowers;
UPROPERTY(VisibleAnywhere)
class UStaticMeshComponent * Slower;
UPROPERTY(VisibleAnywhere)
class UStaticMeshComponent * Slower1;
UPROPERTY(VisibleAnywhere)
class UStaticMeshComponent * Slower2;
UPROPERTY(VisibleAnywhere)
class UStaticMeshComponent * Slower3;
UPROPERTY(VisibleAnywhere)
class UStaticMeshComponent * Slower4;
UPROPERTY(VisibleAnywhere)
class UStaticMeshComponent * Slower5;
UPROPERTY(VisibleAnywhere)
class UStaticMeshComponent * Slower6;
UPROPERTY(VisibleAnywhere)
class UStaticMeshComponent * Slower7;
UPROPERTY(VisibleAnywhere)
class UStaticMeshComponent * Slower8;
UPROPERTY(VisibleAnywhere)
class UStaticMeshComponent * Slower9;
UFUNCTION()
void OnOverlapBegin(class UPrimitiveComponent* OverlappedComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
UFUNCTION()
void OnOverlapEnd(class UPrimitiveComponent* OverlappedComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);
};
| [
"snollygoester1133@gmail.com"
] | snollygoester1133@gmail.com |
dcf6305c43a0e39e7e39831f22989f5f1bbc3b3f | 2af943fbfff74744b29e4a899a6e62e19dc63256 | /IGTLoadableModules/ProstateRegistration/SliceToVolumeRegistration/ConvertToRigidAffine.h | f7c4e41db500a5cdca1d71754c22d6ef084792d5 | [] | no_license | lheckemann/namic-sandbox | c308ec3ebb80021020f98cf06ee4c3e62f125ad9 | 0c7307061f58c9d915ae678b7a453876466d8bf8 | refs/heads/master | 2021-08-24T12:40:01.331229 | 2014-02-07T21:59:29 | 2014-02-07T21:59:29 | 113,701,721 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 13,889 | h | #ifndef __ConvertToRigidAffine_h
#define __ConvertToRigidAffine_h
#include <itkMatrix.h>
#include <itkVector.h>
#include <itkAffineTransform.h>
#include <itkVersorRigid3DTransform.h>
#include "itkScaleVersor3DTransform.h"
#include "itkScaleSkewVersor3DTransform.h"
#include "itkMacro.h"
#include <vnl/vnl_matrix.h>
#include <vnl/vnl_inverse.h>
#include <vnl/vnl_matrix_fixed.h>
#include <vnl/vnl_vector.h>
#include <vnl/algo/vnl_svd.h>
#include <vcl_cmath.h>
// TODO: Need to make return types an input template type.
namespace AssignRigid
{
typedef itk::AffineTransform< double, 3 > AffineTransformType;
typedef AffineTransformType::Pointer AffineTransformPointer;
typedef vnl_matrix_fixed< double, 4, 4 > VnlTransformMatrixType44;
typedef itk::Matrix< double, 3, 3 > Matrix3D;
typedef itk::Versor< double > VersorType;
typedef AffineTransformType::MatrixType MatrixType;
typedef AffineTransformType::InputPointType PointType;
typedef AffineTransformType::OutputVectorType VectorType;
typedef itk::VersorRigid3DTransform< double >
VersorRigid3DTransformType;
typedef VersorRigid3DTransformType::Pointer
VersorRigid3DTransformPointer;
typedef VersorRigid3DTransformType::ParametersType
VersorRigid3DParametersType;
typedef itk::ScaleVersor3DTransform< double >
ScaleVersor3DTransformType;
typedef ScaleVersor3DTransformType::Pointer ScaleVersor3DTransformPointer;
typedef ScaleVersor3DTransformType::ParametersType
ScaleVersor3DParametersType;
typedef itk::ScaleSkewVersor3DTransform< double >
ScaleSkewVersor3DTransformType;
typedef ScaleSkewVersor3DTransformType::Pointer
ScaleSkewVersor3DTransformPointer;
typedef ScaleSkewVersor3DTransformType::ParametersType
ScaleSkewVersor3DParametersType;
/**
* AffineTransformPointer := AffineTransformPointer
*/
inline void
AssignConvertedTransform(AffineTransformPointer & result,
const AffineTransformType::ConstPointer affine)
{
if ( result.IsNotNull() )
{
result->SetParameters( affine->GetParameters() );
result->SetFixedParameters( affine->GetFixedParameters() );
}
else
{
std::cout
<<
"Error missing Pointer data, while assigning AffineTransformPointer := AffineTransformPointer."
<< std::endl;
throw;
}
}
/**
* AffineTransformPointer := VnlTransformMatrixType44
*/
inline void
AssignConvertedTransform(AffineTransformPointer & result,
const VnlTransformMatrixType44 & matrix)
{
if ( result.IsNotNull() )
{
MatrixType rotator; // can't do = conversion.
rotator.operator=( matrix.extract(3, 3, 0, 0) );
VectorType offset;
for ( unsigned int i = 0; i < 3; i++ )
{
offset[i] = matrix.get(i, 3);
}
itk::Point< double, 3 > ZeroCenter;
ZeroCenter.Fill(0.0);
result->SetIdentity();
result->SetCenter(ZeroCenter); // Assume that rotation is about 0.0
result->SetMatrix(rotator);
result->SetOffset(offset); // It is offset in this case, and not
// Translation.
}
else
{
std::cout
<<
"Error missing Pointer data, while assigning AffineTransformPointer := VnlTransformMatrixType44."
<< std::endl;
throw;
}
}
/**
* VnlTransformMatrixType44 := AffineTransformPointer
*/
inline void
AssignConvertedTransform(VnlTransformMatrixType44 & result,
const AffineTransformType::ConstPointer affine)
{
if ( affine.IsNotNull() )
{
MatrixType rotator = affine->GetMatrix();
VectorType offset = affine->GetOffset(); // This needs to be offst
// in
// this case, and not
// Translation.
result.update(rotator.GetVnlMatrix(), 0, 0);
for ( unsigned int i = 0; i < 3; i++ )
{
result.put(i, 3, offset[i]);
result.put(3, i, 0.0);
}
result.put(3, 3, 1.0);
}
else
{
std::cout
<<
"Error missing Pointer data, while assigning VnlTransformMatrixType44 := AffineTransformPointer."
<< std::endl;
throw;
}
}
/**
* AffineTransformPointer := ScaleSkewVersor3DTransformPointer
*/
inline void
AssignConvertedTransform(AffineTransformPointer & result,
const ScaleSkewVersor3DTransformType::ConstPointer scale)
{
if ( result.IsNotNull() && scale.IsNotNull() )
{
result->SetIdentity();
result->SetCenter( scale->GetCenter() );
result->SetMatrix( scale->GetMatrix() );
result->SetTranslation( scale->GetTranslation() );
}
else
{
std::cout
<<
"Error missing Pointer data, assigning AffineTransformPointer := ScaleSkewVersor3DTransformPointer."
<< std::endl;
throw;
}
}
/**
* ScaleSkewVersor3DTransformPointer := ScaleSkewVersor3DTransformPointer
*/
inline void
AssignConvertedTransform(ScaleSkewVersor3DTransformPointer & result,
const ScaleSkewVersor3DTransformType::ConstPointer scale)
{
if ( result.IsNotNull() && scale.IsNotNull() )
{
result->SetParameters( scale->GetParameters() );
result->SetFixedParameters( scale->GetFixedParameters() );
}
else
{
std::cout
<<
"Error missing Pointer data, assigning AffineTransformPointer := ScaleSkewVersor3DTransformPointer."
<< std::endl;
throw;
}
}
/**
* AffineTransformPointer := ScaleVersor3DTransformPointer
*/
inline void
AssignConvertedTransform(AffineTransformPointer & result,
const ScaleVersor3DTransformType::ConstPointer scale)
{
if ( result.IsNotNull() && scale.IsNotNull() )
{
result->SetIdentity();
result->SetCenter( scale->GetCenter() );
result->SetMatrix( scale->GetMatrix() ); // NOTE: This matrix has
// both
// rotation ans scale components.
result->SetTranslation( scale->GetTranslation() );
}
else
{
std::cout
<<
"Error missing Pointer data, assigning AffineTransformPointer := ScaleVersor3DTransformPointer."
<< std::endl;
throw;
}
}
/**
* ScaleVersor3DTransformPointer := ScaleVersor3DTransformPointer
*/
inline void
AssignConvertedTransform(ScaleVersor3DTransformPointer & result,
const ScaleVersor3DTransformType::ConstPointer scale)
{
if ( result.IsNotNull() && scale.IsNotNull() )
{
result->SetParameters( scale->GetParameters() );
result->SetFixedParameters( scale->GetFixedParameters() );
}
else
{
std::cout
<<
"Error missing Pointer data, assigning ScaleVersor3DTransform := ScaleVersor3DTransformPointer."
<< std::endl;
throw;
}
}
/**
* AffineTransformPointer := VersorRigid3DTransformPointer
*/
inline void
AssignConvertedTransform(AffineTransformPointer & result,
const VersorRigid3DTransformType::ConstPointer versorTransform)
{
if ( result.IsNotNull() && versorTransform.IsNotNull() )
{
result->SetIdentity();
result->SetCenter( versorTransform->GetCenter() );
result->SetMatrix( versorTransform->GetMatrix() ); // We MUST
// SetMatrix
// before the
// SetOffset -- not
// after!
result->SetTranslation( versorTransform->GetTranslation() );
}
else
{
std::cout
<<
"Error missing Pointer data, assigning AffineTransformPointer := VersorRigid3DTransformPointer."
<< std::endl;
throw;
}
}
/**
* *VersorRigid3DTransformPointer := VersorRigid3DTransformPointer
*/
inline void AssignConvertedTransform(
VersorRigid3DTransformPointer & result,
const VersorRigid3DTransformType::ConstPointer versorRigid)
{
if ( result.IsNotNull() && versorRigid.IsNotNull() )
{
result->SetParameters( versorRigid->GetParameters() );
result->SetFixedParameters( versorRigid->GetFixedParameters() );
}
else
{
std::cout
<<
"Error missing Pointer data, assigning VersorRigid3DTransformPointer := VersorRigid3DTTransformPointer."
<< std::endl;
throw;
}
}
/**
* ScaleSkewVersor3DTransformPointer := ScaleVersor3DTransformPointer
*/
inline void AssignConvertedTransform(
ScaleSkewVersor3DTransformPointer & result,
const ScaleVersor3DTransformType::ConstPointer scale)
{
if ( result.IsNotNull() && scale.IsNotNull() )
{
result->SetIdentity();
result->SetCenter( scale->GetCenter() );
result->SetRotation( scale->GetVersor() );
result->SetScale( scale->GetScale() );
result->SetTranslation( scale->GetTranslation() );
}
else
{
std::cout
<<
"Error missing Pointer data, assigning ScaleSkewVersor3DTransformPointer := ScaleVersor3DTransformPointer."
<< std::endl;
throw;
}
}
/**
* ScaleSkewVersor3DTransformPointer := VersorRigid3DTransformPointer
*/
inline void AssignConvertedTransform(
ScaleSkewVersor3DTransformPointer & result,
const VersorRigid3DTransformType::ConstPointer versorRigid)
{
if ( result.IsNotNull() && versorRigid.IsNotNull() )
{
result->SetIdentity();
result->SetCenter( versorRigid->GetCenter() );
result->SetRotation( versorRigid->GetVersor() );
result->SetTranslation( versorRigid->GetTranslation() );
}
else
{
std::cout
<<
"Error missing Pointer data, assigning ScaleSkewVersor3DTransformPointer := VersorRigid3DTransformPointer."
<< std::endl;
throw;
}
}
/**
* ScaleVersor3DTransformPointer := VersorRigid3DTransformPointer
*/
inline void AssignConvertedTransform(
ScaleVersor3DTransformPointer & result,
const VersorRigid3DTransformType::ConstPointer versorRigid)
{
if ( result.IsNotNull() && versorRigid.IsNotNull() )
{
result->SetIdentity();
result->SetCenter( versorRigid->GetCenter() );
result->SetRotation( versorRigid->GetVersor() );
result->SetTranslation( versorRigid->GetTranslation() );
}
else
{
std::cout
<<
"Error missing Pointer data, assigning ScaleVersor3DTransformPointer := VersorRigid3DTransformPointer."
<< std::endl;
throw;
}
}
inline void ExtractVersorRigid3DTransform(
VersorRigid3DTransformPointer & result,
const ScaleVersor3DTransformType::ConstPointer scaleVersorRigid)
{
if ( result.IsNotNull() && scaleVersorRigid.IsNotNull() )
{
result->SetIdentity();
result->SetCenter( scaleVersorRigid->GetCenter() );
result->SetRotation( scaleVersorRigid->GetVersor() );
result->SetTranslation( scaleVersorRigid->GetTranslation() );
}
else
{
std::cout
<<
"Error missing Pointer data, assigning VersorRigid3DTransformPointer := ScaleVersor3DTransformPointer."
<< std::endl;
throw;
}
}
inline void ExtractVersorRigid3DTransform(
VersorRigid3DTransformPointer & result,
const ScaleSkewVersor3DTransformType::ConstPointer scaleSkewVersorRigid)
{
if ( result.IsNotNull() && scaleSkewVersorRigid.IsNotNull() )
{
result->SetIdentity();
result->SetCenter( scaleSkewVersorRigid->GetCenter() );
result->SetRotation( scaleSkewVersorRigid->GetVersor() );
result->SetTranslation( scaleSkewVersorRigid->GetTranslation() );
}
else
{
std::cout
<<
"Error missing Pointer data, assigning VersorRigid3DTransformPointer := ScaleSkewVersor3DTransformPointer."
<< std::endl;
throw;
}
}
inline void ExtractVersorRigid3DTransform(
VersorRigid3DTransformPointer & result,
const VersorRigid3DTransformType::ConstPointer versorRigid)
{
if ( result.IsNotNull() && versorRigid.IsNotNull() )
{
result->SetParameters( versorRigid->GetParameters() );
result->SetFixedParameters( versorRigid->GetFixedParameters() );
}
else
{
std::cout
<<
"Error missing Pointer data, assigning VersorRigid3DTransformPointer := ScaleVersor3DTransformPointer."
<< std::endl;
throw;
}
}
/**
* VersorRigid3DTransformPointer := AffineTransformPointer
*/
/**
* Utility function in which we claim the singular-value decomposition (svd)
* gives the orthogonalization of a matrix in its U component. However we
* must clip out the null subspace, if any.
*/
inline Matrix3D
orthogonalize(const Matrix3D rotator)
{
vnl_svd< double > decomposition(
rotator.GetVnlMatrix(),
-1E-6);
vnl_diag_matrix< vnl_svd< double >::singval_t > Winverse( decomposition.Winverse() );
vnl_matrix< double > W(3, 3);
W.fill( double(0) );
for ( unsigned int i = 0; i < 3; ++i )
{
if ( decomposition.Winverse() (i, i) != 0.0 )
{
W(i, i) = 1.0;
}
}
vnl_matrix< double > result(
decomposition.U() *W *decomposition.V().conjugate_transpose() );
// std::cout << " svd Orthonormalized Rotation: " << std::endl
// << result << std::endl;
Matrix3D Orthog;
Orthog.operator=(result);
return Orthog;
}
inline void
ExtractVersorRigid3DTransform(VersorRigid3DTransformPointer & result,
const AffineTransformType::ConstPointer affine)
{
if ( result.IsNotNull() && affine.IsNotNull() )
{
Matrix3D NonOrthog = affine->GetMatrix();
Matrix3D Orthog( orthogonalize(NonOrthog) );
MatrixType rotator;
rotator.operator=(Orthog);
VersorType versor;
versor.Set(rotator); // --> controversial! Is rotator
// orthogonal as
// required?
// versor.Normalize();
result->SetIdentity();
result->SetCenter( affine->GetCenter() );
std::cout << "Affine transform center: " << affine->GetCenter() << std::endl;
result->SetRotation(versor);
result->SetTranslation( affine->GetTranslation() );
}
else
{
std::cout << "Error missing Pointer data, assigning "
<< "VersorRigid3DTransformPointer := AffineTransformPointer."
<< std::endl;
throw;
}
}
}
#endif // __RigidAffine_h
| [
"lassoan@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8"
] | lassoan@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8 |
64188a98763aae7c9ef68398a7b11b33b3669c52 | 4fee08e558e77d16ab915f629df74a0574709e8b | /cpsc585/Havok/Physics/Collide/Shape/hkpShapeType.h | d26024a51c3e51c4774949961cceb436db9b7035 | [] | no_license | NinjaMeTimbers/CPSC-585-Game-Project | c6fe97818ffa69b26e6e4dce622079068f5831cc | 27a0ce3ef6daabb79e7bdfbe7dcd5635bafce390 | refs/heads/master | 2021-01-21T00:55:51.915184 | 2012-04-16T20:06:05 | 2012-04-16T20:06:05 | 3,392,986 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,709 | h | /*
* 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.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2011 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*/
#ifndef HK_COLLIDE2_SHAPE_TYPES_H
#define HK_COLLIDE2_SHAPE_TYPES_H
/// All shape types. The dispatcher has only to implement at least the types that can be used as secondary types
enum hkpShapeType
{
//
// Shape types from HK_SHAPE_INVALID to HK_SHAPE_MAX_ID_SPU are supported on the SPU.
//
HK_SHAPE_INVALID = 0,
//
// Simple convex shapes
//
/// hkpSphereShape type.
HK_SHAPE_SPHERE,
/// The first real shape.
HK_FIRST_SHAPE_TYPE = HK_SHAPE_SPHERE,
/// hkpCylinderShape type.
HK_SHAPE_CYLINDER,
/// hkpTriangleShape type.
HK_SHAPE_TRIANGLE,
/// hkpBoxShape type.
HK_SHAPE_BOX,
/// hkpCapsuleShape type.
HK_SHAPE_CAPSULE,
/// hkpConvexVerticesShape type.
HK_SHAPE_CONVEX_VERTICES,
//
// Shape collection interfaces
//
/// All shapes which inherit from hkpShapeCollection have this as an alternate type.
HK_SHAPE_COLLECTION,
/// All shapes which inherit from hkpBvTreeShape have this as an alternate type.
HK_SHAPE_BV_TREE,
//
// SPU-compatible shape collections
//
/// hkpListShape type.
HK_SHAPE_LIST,
/// hkpMoppBvTreeShape type.
HK_SHAPE_MOPP,
/// hkpConvexTranslateShape type.
HK_SHAPE_CONVEX_TRANSLATE,
/// hkpConvexTransformShape type.
HK_SHAPE_CONVEX_TRANSFORM,
/// hkpSampledHeightFieldShape type.
HK_SHAPE_SAMPLED_HEIGHT_FIELD,
/// hkpExtendedMeshShape type.
HK_SHAPE_EXTENDED_MESH,
/// hkpTransformShape type.
HK_SHAPE_TRANSFORM,
/// hkpCompressedMeshShape type.
HK_SHAPE_COMPRESSED_MESH,
/// hkpStaticCompoundShape
HK_SHAPE_STATIC_COMPOUND,
/// hkpBvCompressedMeshShape type.
HK_SHAPE_BV_COMPRESSED_MESH,
//
// Shape types from HK_SHAPE_MAX_ID_SPU to HK_SHAPE_MAX_ID are NOT supported on the SPU.
//
// Last SPU support shape type
HK_SHAPE_MAX_ID_SPU = HK_SHAPE_BV_COMPRESSED_MESH + 1,
/// All shapes which inherit from hkpConvexShape have this as an alternate type.
HK_SHAPE_CONVEX,
/// DEPRECATED - hkpConvexPieceShape type.
HK_SHAPE_CONVEX_PIECE,
//
// hkpShapeCollection implementations
//
/// DEPRECATED - hkpMultiSphereShape type.
HK_SHAPE_MULTI_SPHERE,
/// DEPRECATED - hkpConvexListShape.
HK_SHAPE_CONVEX_LIST,
/// A shape collection which only returns triangles as child shapes, e.g., hkpMeshShape.
HK_SHAPE_TRIANGLE_COLLECTION,
//
// Special shapes
//
/// hkpHeightFieldShape type.
HK_SHAPE_HEIGHT_FIELD,
/// hkpSphereRepShape type.
HK_SHAPE_SPHERE_REP,
/// hkpBvShape type.
HK_SHAPE_BV,
/// hkpPlaneShape type.
HK_SHAPE_PLANE,
//
// Single shapes which are processed by unary agents.
//
/// hkpPhantomCallbackShape type.
HK_SHAPE_PHANTOM_CALLBACK,
/// hkpMultiRayShape type.
HK_SHAPE_MULTI_RAY,
//
// user shapes
//
HK_SHAPE_USER0,
HK_SHAPE_USER1,
HK_SHAPE_USER2,
/// The end of the shape type list.
HK_SHAPE_MAX_ID,
/// All shapes flag, used by the hkpCollisionDispatcher.
HK_SHAPE_ALL = -1
};
/// A utility function to return a useful name for a given shape type
const char* HK_CALL hkGetShapeTypeName( hkpShapeType type );
class hkpCollisionDispatcher;
/// Register all Havok specific shape types.
/// This needs to be called at setup time to tell the dispatcher which
/// shapes inherit from other shapes.
void HK_CALL hkpRegisterAlternateShapeTypes( hkpCollisionDispatcher* dis );
#endif // HK_COLLIDE2_SHAPE_TYPES_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20110913)
*
* Confidential Information of Havok. (C) Copyright 1999-2011
* 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 at www.havok.com/tryhavok.
*
*/
| [
"cdebavel@ucalgary.ca"
] | cdebavel@ucalgary.ca |
c2ac97a06eb8e71b81f4871f949877b12e709212 | 4a9b40fd4535082a7cd25e0949920a5668997310 | /src/codegen/llvm/intrin_rule_nvptx.cc | 60957198d5f3a47ad861796a28541e2288276374 | [
"Apache-2.0"
] | permissive | siju-samuel/tvmdbg | 19cfb6ab6a17d376ab98625757c2da32de6279fb | b60e8b1174644e564f1e2e13d29b1ff38656e83d | refs/heads/master | 2020-03-18T02:57:59.975935 | 2018-07-11T14:20:26 | 2018-07-11T14:20:26 | 134,216,022 | 0 | 3 | Apache-2.0 | 2018-07-03T10:44:45 | 2018-05-21T04:01:10 | C++ | UTF-8 | C++ | false | false | 1,726 | cc | /*!
* Copyright (c) 2017 by Contributors
* \file intrin_rule_nvptx.cc
*/
#ifdef TVM_LLVM_VERSION
#include <tvm/ir.h>
#include <tvm/expr.h>
#include <tvm/api_registry.h>
#include <sstream>
namespace tvm {
namespace codegen {
inline void DispatchExternLibDevice(const TVMArgs& args, TVMRetValue* rv) {
Expr e = args[0];
using namespace ir;
const Call* call = e.as<Call>();
CHECK(call != nullptr);
CHECK(call->type.bits() == 32 || call->type.bits() == 64) << "Only support float32 or float64.";
std::ostringstream intrinsic_name;
intrinsic_name << "__nv_" << call->name;
if (call->type.bits() == 32) intrinsic_name << "f";
*rv = Call::make(call->type, intrinsic_name.str(), call->args,
Call::PureExtern);
}
namespace llvm {
TVM_REGISTER_GLOBAL("tvm.intrin.rule.nvptx.floor")
.set_body(DispatchExternLibDevice);
TVM_REGISTER_GLOBAL("tvm.intrin.rule.nvptx.ceil")
.set_body(DispatchExternLibDevice);
TVM_REGISTER_GLOBAL("tvm.intrin.rule.nvptx.round")
.set_body(DispatchExternLibDevice);
TVM_REGISTER_GLOBAL("tvm.intrin.rule.nvptx.trunc")
.set_body(DispatchExternLibDevice);
TVM_REGISTER_GLOBAL("tvm.intrin.rule.nvptx.exp")
.set_body(DispatchExternLibDevice);
TVM_REGISTER_GLOBAL("tvm.intrin.rule.nvptx.fma")
.set_body(DispatchExternLibDevice);
TVM_REGISTER_GLOBAL("tvm.intrin.rule.nvptx.log")
.set_body(DispatchExternLibDevice);
TVM_REGISTER_GLOBAL("tvm.intrin.rule.nvptx.sqrt")
.set_body(DispatchExternLibDevice);
TVM_REGISTER_GLOBAL("tvm.intrin.rule.nvptx.pow")
.set_body(DispatchExternLibDevice);
TVM_REGISTER_GLOBAL("tvm.intrin.rule.nvptx.tanh")
.set_body(DispatchExternLibDevice);
} // namespace llvm
} // namespace codegen
} // namespace tvm
#endif // LLVM_VERSION
| [
"siju.samuel@huawei.com"
] | siju.samuel@huawei.com |
b19d4d7723f739b3fdcc029990ee384e0bbd6a56 | c127df65f94a30122ce715bb0567085c8828c30d | /src/common/SystemInformation.cpp | 7f4a958791d510d42aee4c3c9ad7ea5bc0948d04 | [
"MIT"
] | permissive | djp952/vm-linux | 966af41dac53db855dc55dc0780ec29ec885dd06 | bea00665424bdf0a1def86034ec85606b4d8217f | refs/heads/master | 2020-05-21T16:25:27.814517 | 2016-12-04T03:47:27 | 2016-12-04T03:47:27 | 64,184,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,727 | cpp | //-----------------------------------------------------------------------------
// Copyright (c) 2016 Michael G. Brehm
//
// 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 "stdafx.h"
#include "SystemInformation.h"
#pragma warning(push, 4)
// g_memstatus
//
// Global copy of the MEMORYSTATUSEX structure
static MEMORYSTATUSEX g_memstatus;
// g_sysinfo (local)
//
// Global copy of the SYSTEM_INFO structure
static SYSTEM_INFO g_sysinfo;
// g_initonce (local)
//
// Global one-time initialization context
static INIT_ONCE g_initonce = INIT_ONCE_STATIC_INIT;
// InitOnceSystemInformation (local)
//
// One-time initialization handler to retrieve system information
static BOOL CALLBACK InitOnceSystemInformation(PINIT_ONCE, PVOID, PVOID*)
{
g_memstatus.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&g_memstatus);
GetNativeSystemInfo(&g_sysinfo);
return TRUE;
}
// SystemInformation::ActiveProcessorMask
//
unsigned __int3264 const SystemInformation::ActiveProcessorMask = []() -> unsigned __int3264 {
InitOnceExecuteOnce(&g_initonce, InitOnceSystemInformation, nullptr, nullptr);
return g_sysinfo.dwActiveProcessorMask;
}();
// SystemInformation::AllocationGranularity
//
size_t const SystemInformation::AllocationGranularity = []() -> size_t {
InitOnceExecuteOnce(&g_initonce, InitOnceSystemInformation, nullptr, nullptr);
return g_sysinfo.dwAllocationGranularity;
}();
// SystemInformation::MaximumApplicationAddress
//
void* const SystemInformation::MaximumApplicationAddress = []() -> void* {
InitOnceExecuteOnce(&g_initonce, InitOnceSystemInformation, nullptr, nullptr);
return g_sysinfo.lpMaximumApplicationAddress;
}();
// SystemInformation::MinimumApplicationAddress
//
void* const SystemInformation::MinimumApplicationAddress = []() -> void* {
InitOnceExecuteOnce(&g_initonce, InitOnceSystemInformation, nullptr, nullptr);
return g_sysinfo.lpMinimumApplicationAddress;
}();
// SystemInformation::NumberOfProcessors
//
size_t const SystemInformation::NumberOfProcessors = []() -> size_t {
InitOnceExecuteOnce(&g_initonce, InitOnceSystemInformation, nullptr, nullptr);
return g_sysinfo.dwNumberOfProcessors;
}();
// SystemInformation::PageSize
//
size_t const SystemInformation::PageSize = []() -> size_t {
InitOnceExecuteOnce(&g_initonce, InitOnceSystemInformation, nullptr, nullptr);
return g_sysinfo.dwPageSize;
}();
// SystemInformation::ProcessorArchitecture
//
SystemInformation::Architecture const SystemInformation::ProcessorArchitecture = []() -> SystemInformation::Architecture {
InitOnceExecuteOnce(&g_initonce, InitOnceSystemInformation, nullptr, nullptr);
return static_cast<SystemInformation::Architecture>(g_sysinfo.wProcessorArchitecture);
}();
// SystemInformation::ProcessorFeatureMask
//
uint32_t const SystemInformation::ProcessorFeatureMask = []() -> uint32_t {
int cpuinfo[4]; // Gets EAX, EBX, ECX, EDX
__cpuid(&cpuinfo[0], 1); // Use the compiler intrinsic __cpuid
return cpuinfo[3]; // EDX has the bitmask we're looking for
}();
// SystemInformation::TotalPhysicalMemory
//
uint64_t const SystemInformation::TotalPhysicalMemory = []() -> uint64_t {
InitOnceExecuteOnce(&g_initonce, InitOnceSystemInformation, nullptr, nullptr);
return g_memstatus.ullTotalPhys;
}();
// SystemInformation::TotalVirtualMemory
//
uint64_t const SystemInformation::TotalVirtualMemory = []() -> uint64_t {
InitOnceExecuteOnce(&g_initonce, InitOnceSystemInformation, nullptr, nullptr);
return g_memstatus.ullTotalVirtual;
}();
//-----------------------------------------------------------------------------
#pragma warning(pop)
| [
"djp952@gmail.com"
] | djp952@gmail.com |
3bdf60951c2351095a7eeaafc78610771e51215b | 051b26722589a40de1fe310c5f9ac36d3d3a4390 | /src/asm2wasm.h | 6cbb4e084d419ae569cd946a046e45cedf3e426e | [
"MIT"
] | permissive | mcanthony/binaryen | 0dbbd845296fdefae4217d4cd584ff9f23f3963c | 7d0250a6e0f6a656637abce0a29cb4618eeedd68 | refs/heads/master | 2021-01-17T23:30:46.375435 | 2015-11-23T05:54:03 | 2015-11-23T05:54:03 | 46,705,274 | 1 | 0 | null | 2015-11-23T08:00:11 | 2015-11-23T08:00:10 | null | UTF-8 | C++ | false | false | 56,247 | h |
//
// asm.js-to-WebAssembly translator. Uses the Emscripten optimizer
// infrastructure.
//
#include "wasm.h"
#include "emscripten-optimizer/optimizer.h"
#include "mixed_arena.h"
namespace wasm {
using namespace cashew;
int debug = 0; // wasm::debug is set in main(), typically from an env var
// Utilities
IString GLOBAL("global"), NAN_("NaN"), INFINITY_("Infinity"),
TOPMOST("topmost"),
INT8ARRAY("Int8Array"),
INT16ARRAY("Int16Array"),
INT32ARRAY("Int32Array"),
UINT8ARRAY("Uint8Array"),
UINT16ARRAY("Uint16Array"),
UINT32ARRAY("Uint32Array"),
FLOAT32ARRAY("Float32Array"),
FLOAT64ARRAY("Float64Array"),
IMPOSSIBLE_CONTINUE("impossible-continue"),
MATH("Math"),
IMUL("imul"),
CLZ32("clz32"),
FROUND("fround"),
ASM2WASM("asm2wasm"),
F64_REM("f64-rem"),
F64_TO_INT("f64-to-int"),
GLOBAL_MATH("global.Math"),
ABS("abs"),
FLOOR("floor"),
SQRT("sqrt"),
I32_TEMP("asm2wasm_i32_temp"),
DEBUGGER("debugger"),
GROW_WASM_MEMORY("__growWasmMemory"),
NEW_SIZE("newSize");
static void abort_on(std::string why) {
std::cerr << why << '\n';
abort();
}
static void abort_on(std::string why, int x) {
std::cerr << why << ' ' << x << '\n';
abort();
}
static void abort_on(std::string why, Ref element) {
std::cerr << why << ' ';
element->stringify(std::cerr);
std::cerr << '\n';
abort();
}
static void abort_on(std::string why, IString element) {
std::cerr << why << ' ' << element.str << '\n';
abort();
}
// useful when we need to see our parent, in an asm.js expression stack
struct AstStackHelper {
static std::vector<Ref> astStack;
AstStackHelper(Ref curr) {
astStack.push_back(curr);
}
~AstStackHelper() {
astStack.pop_back();
}
Ref getParent() {
if (astStack.size() >= 2) {
return astStack[astStack.size()-2];
} else {
return Ref();
}
}
};
std::vector<Ref> AstStackHelper::astStack;
//
// Asm2WasmPreProcessor - does some initial parsing/processing
// of asm.js code.
//
struct Asm2WasmPreProcessor {
bool memoryGrowth = false;
char* process(char* input) {
// emcc --separate-asm modules can look like
//
// Module["asm"] = (function(global, env, buffer) {
// ..
// });
//
// we need to clean that up.
if (*input == 'M') {
size_t num = strlen(input);
while (*input != 'f') {
input++;
num--;
}
char *end = input + num - 1;
while (*end != '}') {
*end = 0;
end--;
}
}
// asm.js memory growth uses a quite elaborate pattern. Instead of parsing and
// matching it, we do a simpler detection on emscripten's asm.js output format
const char* START_FUNCS = "// EMSCRIPTEN_START_FUNCS";
char *marker = strstr(input, START_FUNCS);
if (marker) {
*marker = 0; // look for memory growth code just up to here
char *growthSign = strstr(input, "return true;"); // this can only show up in growth code, as normal asm.js lacks "true"
if (growthSign) {
memoryGrowth = true;
// clean out this function, we don't need it
char *growthFuncStart = strstr(input, "function ");
assert(strstr(growthFuncStart + 1, "function ") == 0); // should be only this one function in this area, so no confusion for us
char *growthFuncEnd = strchr(growthSign, '}');
assert(growthFuncEnd > growthFuncStart + 5);
growthFuncStart[0] = '/';
growthFuncStart[1] = '*';
growthFuncEnd--;
growthFuncEnd[0] = '*';
growthFuncEnd[1] = '/';
}
*marker = START_FUNCS[0];
}
return input;
}
};
//
// Asm2WasmBuilder - converts an asm.js module into WebAssembly
//
class Asm2WasmBuilder {
Module& wasm;
MixedArena allocator;
// globals
unsigned nextGlobal; // next place to put a global
unsigned maxGlobal; // highest address we can put a global
struct MappedGlobal {
unsigned address;
WasmType type;
bool import; // if true, this is an import - we should read the value, not just set a zero
IString module, base;
MappedGlobal() : address(0), type(none), import(false) {}
MappedGlobal(unsigned address, WasmType type, bool import, IString module, IString base) : address(address), type(type), import(import), module(module), base(base) {}
};
// function table
std::map<IString, int> functionTableStarts; // each asm function table gets a range in the one wasm table, starting at a location
std::map<CallIndirect*, IString> callIndirects; // track these, as we need to fix them after we know the functionTableStarts. this maps call => its function table
bool memoryGrowth;
public:
std::map<IString, MappedGlobal> mappedGlobals;
private:
void allocateGlobal(IString name, WasmType type, bool import, IString module = IString(), IString base = IString()) {
assert(mappedGlobals.find(name) == mappedGlobals.end());
mappedGlobals.emplace(name, MappedGlobal(nextGlobal, type, import, module, base));
nextGlobal += 8;
assert(nextGlobal < maxGlobal);
}
struct View {
unsigned bytes;
bool integer, signed_;
AsmType type;
View() : bytes(0) {}
View(unsigned bytes, bool integer, bool signed_, AsmType type) : bytes(bytes), integer(integer), signed_(signed_), type(type) {}
};
std::map<IString, View> views; // name (e.g. HEAP8) => view info
// Imported names of Math.*
IString Math_imul;
IString Math_clz32;
IString Math_fround;
IString Math_abs;
IString Math_floor;
IString Math_sqrt;
// function types. we fill in this information as we see
// uses, in the first pass
std::map<IString, FunctionType> importedFunctionTypes;
void noteImportedFunctionCall(Ref ast, WasmType resultType, AsmData *asmData) {
assert(ast[0] == CALL && ast[1][0] == NAME);
IString importName = ast[1][1]->getIString();
FunctionType type;
type.name = IString((std::string("type$") + importName.str).c_str(), false); // TODO: make a list of such types
type.result = resultType;
Ref args = ast[2];
for (unsigned i = 0; i < args->size(); i++) {
type.params.push_back(detectWasmType(args[i], asmData));
}
// if we already saw this signature, verify it's the same (or else handle that)
if (importedFunctionTypes.find(importName) != importedFunctionTypes.end()) {
FunctionType& previous = importedFunctionTypes[importName];
#if 0
std::cout << "compare " << importName.str << "\nfirst: ";
type.print(std::cout, 0);
std::cout << "\nsecond: ";
previous.print(std::cout, 0) << ".\n";
#endif
if (type != previous) {
// merge it in. we'll add on extra 0 parameters for ones not actually used, etc.
for (size_t i = 0; i < type.params.size(); i++) {
if (previous.params.size() > i) {
if (previous.params[i] == none) {
previous.params[i] = type.params[i]; // use a more concrete type
}
} else {
previous.params.push_back(type.params[i]); // add a new param
}
}
if (previous.result == none) {
previous.result = type.result; // use a more concrete type
}
}
} else {
importedFunctionTypes[importName] = type;
}
}
char getSigFromType(WasmType type) {
switch (type) {
case i32: return 'i';
case f32: return 'f';
case f64: return 'd';
case none: return 'v';
default: abort();
}
}
FunctionType *getFunctionType(Ref parent, ExpressionList& operands) {
// generate signature
WasmType result = detectWasmType(parent, nullptr);
std::string str = "FUNCSIG$";
str += getSigFromType(result);
for (auto operand : operands) {
str += getSigFromType(operand->type);
}
IString sig(str.c_str(), false);
if (wasm.functionTypesMap.find(sig) == wasm.functionTypesMap.end()) {
// add new type
auto type = allocator.alloc<FunctionType>();
type->name = sig;
type->result = result;
for (auto operand : operands) {
type->params.push_back(operand->type);
}
wasm.addFunctionType(type);
}
return wasm.functionTypesMap[sig];
}
public:
Asm2WasmBuilder(Module& wasm, bool memoryGrowth) : wasm(wasm), nextGlobal(8), maxGlobal(1000), memoryGrowth(memoryGrowth) {}
void processAsm(Ref ast);
void optimize();
private:
WasmType asmToWasmType(AsmType asmType) {
switch (asmType) {
case ASM_INT: return WasmType::i32;
case ASM_DOUBLE: return WasmType::f64;
case ASM_FLOAT: return WasmType::f32;
case ASM_NONE: return WasmType::none;
default: {}
}
abort_on("confused asmType", asmType);
return (WasmType)-1; // avoid warning
}
AsmType wasmToAsmType(WasmType type) {
switch (type) {
case WasmType::i32: return ASM_INT;
case WasmType::f32: return ASM_FLOAT;
case WasmType::f64: return ASM_DOUBLE;
case WasmType::none: return ASM_NONE;
default: {}
}
abort_on("confused wasmType", type);
return (AsmType)-1; // avoid warning
}
AsmType detectAsmType(Ref ast, AsmData *data) {
if (ast[0] == NAME) {
IString name = ast[1]->getIString();
if (!data->isLocal(name)) {
// must be global
assert(mappedGlobals.find(name) != mappedGlobals.end());
return wasmToAsmType(mappedGlobals[name].type);
}
} else if (ast[0] == SUB && ast[1][0] == NAME) {
// could be a heap access, use view info
auto view = views.find(ast[1][1]->getIString());
if (view != views.end()) {
return view->second.type;
}
}
return detectType(ast, data, false, Math_fround);
}
WasmType detectWasmType(Ref ast, AsmData *data) {
return asmToWasmType(detectAsmType(ast, data));
}
bool isUnsignedCoercion(Ref ast) {
return detectSign(ast, Math_fround) == ASM_UNSIGNED;
}
// an asm.js binary op can either be a binary or a relational in wasm
bool parseAsmBinaryOp(IString op, Ref left, Ref right, BinaryOp &binary, RelationalOp &relational, AsmData *asmData) {
if (op == PLUS) { binary = BinaryOp::Add; return true; }
if (op == MINUS) { binary = BinaryOp::Sub; return true; }
if (op == MUL) { binary = BinaryOp::Mul; return true; }
if (op == AND) { binary = BinaryOp::And; return true; }
if (op == OR) { binary = BinaryOp::Or; return true; }
if (op == XOR) { binary = BinaryOp::Xor; return true; }
if (op == LSHIFT) { binary = BinaryOp::Shl; return true; }
if (op == RSHIFT) { binary = BinaryOp::ShrS; return true; }
if (op == TRSHIFT) { binary = BinaryOp::ShrU; return true; }
if (op == EQ) { relational = RelationalOp::Eq; return false; }
if (op == NE) { relational = RelationalOp::Ne; return false; }
WasmType leftType = detectWasmType(left, asmData);
#if 0
std::cout << "CHECK\n";
left->stringify(std::cout);
std::cout << " => " << printWasmType(leftType);
std::cout << '\n';
right->stringify(std::cout);
std::cout << " => " << printWasmType(detectWasmType(right, asmData)) << "\n";
#endif
bool isInteger = leftType == WasmType::i32;
bool isUnsigned = isUnsignedCoercion(left) || isUnsignedCoercion(right);
if (op == DIV) {
if (isInteger) {
{ binary = isUnsigned ? BinaryOp::DivU : BinaryOp::DivS; return true; }
}
{ binary = BinaryOp::Div; return true; }
}
if (op == MOD) {
if (isInteger) {
{ binary = isUnsigned ? BinaryOp::RemU : BinaryOp::RemS; return true; }
}
{ binary = BinaryOp::RemS; return true; } // XXX no floating-point remainder op, this must be handled by the caller
}
if (op == GE) {
if (isInteger) {
{ relational = isUnsigned ? RelationalOp::GeU : RelationalOp::GeS; return false; }
}
{ relational = RelationalOp::Ge; return false; }
}
if (op == GT) {
if (isInteger) {
{ relational = isUnsigned ? RelationalOp::GtU : RelationalOp::GtS; return false; }
}
{ relational = RelationalOp::Gt; return false; }
}
if (op == LE) {
if (isInteger) {
{ relational = isUnsigned ? RelationalOp::LeU : RelationalOp::LeS; return false; }
}
{ relational = RelationalOp::Le; return false; }
}
if (op == LT) {
if (isInteger) {
{ relational = isUnsigned ? RelationalOp::LtU : RelationalOp::LtS; return false; }
}
{ relational = RelationalOp::Lt; return false; }
}
abort_on("bad wasm binary op", op);
return false; // avoid warning
}
unsigned bytesToShift(unsigned bytes) {
switch (bytes) {
case 1: return 0;
case 2: return 1;
case 4: return 2;
case 8: return 3;
default: {}
}
abort();
return -1; // avoid warning
}
std::map<unsigned, Ref> tempNums;
Literal checkLiteral(Ref ast) {
if (ast[0] == NUM) {
return Literal((int32_t)ast[1]->getInteger());
} else if (ast[0] == UNARY_PREFIX) {
if (ast[1] == PLUS && ast[2][0] == NUM) {
return Literal((double)ast[2][1]->getNumber());
}
if (ast[1] == MINUS && ast[2][0] == NUM) {
double num = -ast[2][1]->getNumber();
assert(isInteger32(num));
return Literal((int32_t)num);
}
if (ast[1] == PLUS && ast[2][0] == UNARY_PREFIX && ast[2][1] == MINUS && ast[2][2][0] == NUM) {
return Literal((double)-ast[2][2][1]->getNumber());
}
if (ast[1] == MINUS && ast[2][0] == UNARY_PREFIX && ast[2][1] == PLUS && ast[2][2][0] == NUM) {
return Literal((double)-ast[2][2][1]->getNumber());
}
}
return Literal();
}
Literal getLiteral(Ref ast) {
Literal ret = checkLiteral(ast);
if (ret.type == none) abort();
return ret;
}
void fixCallType(Expression* call, WasmType type) {
if (call->is<Call>()) call->type = type;
if (call->is<CallImport>()) call->type = type;
else if (call->is<CallIndirect>()) call->type = type;
}
FunctionType* getBuiltinFunctionType(Name module, Name base, ExpressionList* operands = nullptr) {
if (module == GLOBAL_MATH) {
if (base == ABS) {
assert(operands && operands->size() == 1);
WasmType type = (*operands)[0]->type;
if (type == i32) {
static FunctionType* builtin = nullptr;
if (!builtin) {
builtin = new FunctionType();
builtin->params.push_back(i32);
builtin->result = i32;
}
return builtin;
}
if (type == f32) {
static FunctionType* builtin = nullptr;
if (!builtin) {
builtin = new FunctionType();
builtin->params.push_back(f32);
builtin->result = f32;
}
return builtin;
}
if (type == f64) {
static FunctionType* builtin = nullptr;
if (!builtin) {
builtin = new FunctionType();
builtin->params.push_back(f64);
builtin->result = f64;
}
return builtin;
}
}
}
return nullptr;
}
Block* blockify(Expression* expression) {
if (expression->is<Block>()) return expression->dyn_cast<Block>();
auto ret = allocator.alloc<Block>();
ret->list.push_back(expression);
return ret;
}
Function* processFunction(Ref ast);
};
void Asm2WasmBuilder::processAsm(Ref ast) {
assert(ast[0] == TOPLEVEL);
Ref asmFunction = ast[1][0];
assert(asmFunction[0] == DEFUN);
Ref body = asmFunction[3];
assert(body[0][0] == STAT && body[0][1][0] == STRING && (body[0][1][1]->getIString() == IString("use asm") || body[0][1][1]->getIString() == IString("almost asm")));
auto addImport = [&](IString name, Ref imported, WasmType type) {
assert(imported[0] == DOT);
Ref module = imported[1];
IString moduleName;
if (module[0] == DOT) {
// we can have (global.Math).floor; skip the 'Math'
assert(module[1][0] == NAME);
if (module[2] == MATH) {
if (imported[2] == IMUL) {
assert(Math_imul.isNull());
Math_imul = name;
return;
} else if (imported[2] == CLZ32) {
assert(Math_clz32.isNull());
Math_clz32 = name;
return;
} else if (imported[2] == FROUND) {
assert(Math_fround.isNull());
Math_fround = name;
return;
} else if (imported[2] == ABS) {
assert(Math_abs.isNull());
Math_abs = name;
return;
} else if (imported[2] == FLOOR) {
assert(Math_floor.isNull());
Math_floor = name;
return;
} else if (imported[2] == SQRT) {
assert(Math_sqrt.isNull());
Math_sqrt = name;
return;
}
}
std::string fullName = module[1][1]->getCString();
fullName += '.';
fullName += + module[2]->getCString();
moduleName = IString(fullName.c_str(), false);
} else {
assert(module[0] == NAME);
moduleName = module[1]->getIString();
}
auto import = allocator.alloc<Import>();
import->name = name;
import->module = moduleName;
import->base = imported[2]->getIString();
// special-case some asm builtins
if (import->module == GLOBAL && (import->base == NAN_ || import->base == INFINITY_)) {
type = WasmType::f64;
}
if (type != WasmType::none) {
// wasm has no imported constants, so allocate a global, and we need to write the value into that
allocateGlobal(name, type, true, import->module, import->base);
} else {
wasm.addImport(import);
}
};
IString Int8Array, Int16Array, Int32Array, UInt8Array, UInt16Array, UInt32Array, Float32Array, Float64Array;
// first pass - do almost everything, but function imports and indirect calls
for (unsigned i = 1; i < body->size(); i++) {
Ref curr = body[i];
if (curr[0] == VAR) {
// import, global, or table
for (unsigned j = 0; j < curr[1]->size(); j++) {
Ref pair = curr[1][j];
IString name = pair[0]->getIString();
Ref value = pair[1];
if (value[0] == NUM) {
// global int
assert(value[1]->getNumber() == 0);
allocateGlobal(name, WasmType::i32, false);
} else if (value[0] == BINARY) {
// int import
assert(value[1] == OR && value[3][0] == NUM && value[3][1]->getNumber() == 0);
Ref import = value[2]; // env.what
addImport(name, import, WasmType::i32);
} else if (value[0] == UNARY_PREFIX) {
// double import or global
assert(value[1] == PLUS);
Ref import = value[2];
if (import[0] == NUM) {
// global
assert(import[1]->getNumber() == 0);
allocateGlobal(name, WasmType::f64, false);
} else {
// import
addImport(name, import, WasmType::f64);
}
} else if (value[0] == CALL) {
assert(value[1][0] == NAME && value[1][1] == Math_fround && value[2][0][0] == NUM && value[2][0][1]->getNumber() == 0);
allocateGlobal(name, WasmType::f32, false);
} else if (value[0] == DOT) {
// simple module.base import. can be a view, or a function.
if (value[1][0] == NAME) {
IString module = value[1][1]->getIString();
IString base = value[2]->getIString();
if (module == GLOBAL) {
if (base == INT8ARRAY) {
Int8Array = name;
} else if (base == INT16ARRAY) {
Int16Array = name;
} else if (base == INT32ARRAY) {
Int32Array = name;
} else if (base == UINT8ARRAY) {
UInt8Array = name;
} else if (base == UINT16ARRAY) {
UInt16Array = name;
} else if (base == UINT32ARRAY) {
UInt32Array = name;
} else if (base == FLOAT32ARRAY) {
Float32Array = name;
} else if (base == FLOAT64ARRAY) {
Float64Array = name;
}
}
}
// function import
addImport(name, value, WasmType::none);
} else if (value[0] == NEW) {
// ignore imports of typed arrays, but note the names of the arrays
value = value[1];
assert(value[0] == CALL);
unsigned bytes;
bool integer, signed_;
AsmType asmType;
Ref constructor = value[1];
if (constructor[0] == DOT) { // global.*Array
IString heap = constructor[2]->getIString();
if (heap == INT8ARRAY) {
bytes = 1; integer = true; signed_ = true; asmType = ASM_INT;
} else if (heap == INT16ARRAY) {
bytes = 2; integer = true; signed_ = true; asmType = ASM_INT;
} else if (heap == INT32ARRAY) {
bytes = 4; integer = true; signed_ = true; asmType = ASM_INT;
} else if (heap == UINT8ARRAY) {
bytes = 1; integer = true; signed_ = false; asmType = ASM_INT;
} else if (heap == UINT16ARRAY) {
bytes = 2; integer = true; signed_ = false; asmType = ASM_INT;
} else if (heap == UINT32ARRAY) {
bytes = 4; integer = true; signed_ = false; asmType = ASM_INT;
} else if (heap == FLOAT32ARRAY) {
bytes = 4; integer = false; signed_ = true; asmType = ASM_FLOAT;
} else if (heap == FLOAT64ARRAY) {
bytes = 8; integer = false; signed_ = true; asmType = ASM_DOUBLE;
} else {
abort_on("invalid view import", heap);
}
} else { // *ArrayView that was previously imported
assert(constructor[0] == NAME);
IString viewName = constructor[1]->getIString();
if (viewName == Int8Array) {
bytes = 1; integer = true; signed_ = true; asmType = ASM_INT;
} else if (viewName == Int16Array) {
bytes = 2; integer = true; signed_ = true; asmType = ASM_INT;
} else if (viewName == Int32Array) {
bytes = 4; integer = true; signed_ = true; asmType = ASM_INT;
} else if (viewName == UInt8Array) {
bytes = 1; integer = true; signed_ = false; asmType = ASM_INT;
} else if (viewName == UInt16Array) {
bytes = 2; integer = true; signed_ = false; asmType = ASM_INT;
} else if (viewName == UInt32Array) {
bytes = 4; integer = true; signed_ = false; asmType = ASM_INT;
} else if (viewName == Float32Array) {
bytes = 4; integer = false; signed_ = true; asmType = ASM_FLOAT;
} else if (viewName == Float64Array) {
bytes = 8; integer = false; signed_ = true; asmType = ASM_DOUBLE;
} else {
abort_on("invalid short view import", viewName);
}
}
assert(views.find(name) == views.end());
views.emplace(name, View(bytes, integer, signed_, asmType));
} else if (value[0] == ARRAY) {
// function table. we merge them into one big table, so e.g. [foo, b1] , [b2, bar] => [foo, b1, b2, bar]
// TODO: when not using aliasing function pointers, we could merge them by noticing that
// index 0 in each table is the null func, and each other index should only have one
// non-null func. However, that breaks down when function pointer casts are emulated.
functionTableStarts[name] = wasm.table.names.size(); // this table starts here
Ref contents = value[1];
for (unsigned k = 0; k < contents->size(); k++) {
IString curr = contents[k][1]->getIString();
wasm.table.names.push_back(curr);
}
} else {
abort_on("invalid var element", pair);
}
}
} else if (curr[0] == DEFUN) {
// function
wasm.addFunction(processFunction(curr));
} else if (curr[0] == RETURN) {
// exports
Ref object = curr[1];
Ref contents = curr[1][1];
for (unsigned k = 0; k < contents->size(); k++) {
Ref pair = contents[k];
IString key = pair[0]->getIString();
Ref value = pair[1];
assert(value[0] == NAME);
auto export_ = allocator.alloc<Export>();
export_->name = key;
export_->value = value[1]->getIString();
wasm.addExport(export_);
}
}
}
// second pass. first, function imports
std::vector<IString> toErase;
for (auto& pair : wasm.importsMap) {
IString name = pair.first;
Import& import = *pair.second;
if (importedFunctionTypes.find(name) != importedFunctionTypes.end()) {
// special math builtins
FunctionType* builtin = getBuiltinFunctionType(import.module, import.base);
if (builtin) {
import.type = *builtin;
continue;
}
import.type = importedFunctionTypes[name];
} else if (import.module != ASM2WASM) { // special-case the special module
// never actually used
toErase.push_back(name);
}
}
for (auto curr : toErase) {
wasm.removeImport(curr);
}
// finalize indirect calls
for (auto& pair : callIndirects) {
CallIndirect* call = pair.first;
IString tableName = pair.second;
assert(functionTableStarts.find(tableName) != functionTableStarts.end());
auto sub = allocator.alloc<Binary>();
// note that the target is already masked, so we just offset it, we don't need to guard against overflow (which would be an error anyhow)
sub->op = Add;
sub->left = call->target;
sub->right = allocator.alloc<Const>()->set(Literal((int32_t)functionTableStarts[tableName]));
sub->type = WasmType::i32;
call->target = sub;
}
// apply memory growth, if relevant
if (memoryGrowth) {
// create and export a function that just calls memory growth
auto growWasmMemory = allocator.alloc<Function>();
growWasmMemory->name = GROW_WASM_MEMORY;
growWasmMemory->params.emplace_back(NEW_SIZE, i32); // the new size
auto get = allocator.alloc<GetLocal>();
get->name = NEW_SIZE;
auto grow = allocator.alloc<Host>();
grow->op = GrowMemory;
grow->operands.push_back(get);
growWasmMemory->body = grow;
wasm.addFunction(growWasmMemory);
auto export_ = allocator.alloc<Export>();
export_->name = export_->value = GROW_WASM_MEMORY;
wasm.addExport(export_);
}
}
Function* Asm2WasmBuilder::processFunction(Ref ast) {
//if (ast[1] != IString("qta")) return nullptr;
if (debug) {
std::cout << "\nfunc: " << ast[1]->getIString().str << '\n';
if (debug >= 2) {
ast->stringify(std::cout);
std::cout << '\n';
}
}
auto function = allocator.alloc<Function>();
function->name = ast[1]->getIString();
Ref params = ast[2];
Ref body = ast[3];
unsigned nextId = 0;
auto getNextId = [&nextId](std::string prefix) {
return IString((prefix + '$' + std::to_string(nextId++)).c_str(), false);
};
// given an asm.js label, returns the wasm label for breaks or continues
auto getBreakLabelName = [](IString label) {
return IString((std::string("label$break$") + label.str).c_str(), false);
};
auto getContinueLabelName = [](IString label) {
return IString((std::string("label$continue$") + label.str).c_str(), false);
};
IStringSet functionVariables; // params or locals
IString parentLabel; // set in LABEL, then read in WHILE/DO/SWITCH
std::vector<IString> breakStack; // where a break will go
std::vector<IString> continueStack; // where a continue will go
AsmData asmData; // need to know var and param types, for asm type detection
for (unsigned i = 0; i < params->size(); i++) {
Ref curr = body[i];
assert(curr[0] == STAT);
curr = curr[1];
assert(curr[0] == ASSIGN && curr[2][0] == NAME);
IString name = curr[2][1]->getIString();
AsmType asmType = detectType(curr[3], nullptr, false, Math_fround);
function->params.emplace_back(name, asmToWasmType(asmType));
functionVariables.insert(name);
asmData.addParam(name, asmType);
}
unsigned start = params->size();
while (start < body->size() && body[start][0] == VAR) {
Ref curr = body[start];
for (unsigned j = 0; j < curr[1]->size(); j++) {
Ref pair = curr[1][j];
IString name = pair[0]->getIString();
AsmType asmType = detectType(pair[1], nullptr, true, Math_fround);
function->locals.emplace_back(name, asmToWasmType(asmType));
functionVariables.insert(name);
asmData.addVar(name, asmType);
}
start++;
}
bool addedI32Temp = false;
auto ensureI32Temp = [&]() {
if (addedI32Temp) return;
addedI32Temp = true;
function->locals.emplace_back(I32_TEMP, i32);
functionVariables.insert(I32_TEMP);
asmData.addVar(I32_TEMP, ASM_INT);
};
bool seenReturn = false; // function->result is updated if we see a return
bool needTopmost = false; // we label the topmost b lock if we need one for a return
// processors
std::function<Expression* (Ref, unsigned)> processStatements;
std::function<Expression* (Ref, unsigned)> processUnshifted;
std::function<Expression* (Ref)> process = [&](Ref ast) -> Expression* {
AstStackHelper astStackHelper(ast); // TODO: only create one when we need it?
if (debug >= 2) {
std::cout << "at: ";
ast->stringify(std::cout);
std::cout << '\n';
}
IString what = ast[0]->getIString();
if (what == STAT) {
return process(ast[1]); // and drop return value, if any
} else if (what == ASSIGN) {
if (ast[2][0] == NAME) {
IString name = ast[2][1]->getIString();
if (functionVariables.has(name)) {
auto ret = allocator.alloc<SetLocal>();
ret->name = ast[2][1]->getIString();
ret->value = process(ast[3]);
ret->type = ret->value->type;
return ret;
}
// global var, do a store to memory
assert(mappedGlobals.find(name) != mappedGlobals.end());
MappedGlobal global = mappedGlobals[name];
auto ret = allocator.alloc<Store>();
ret->bytes = getWasmTypeSize(global.type);
ret->offset = 0;
ret->align = ret->bytes;
auto ptr = allocator.alloc<Const>();
ptr->value.type = WasmType::i32; // XXX for wasm64, need 64
ptr->value.i32 = global.address;
ret->ptr = ptr;
ret->value = process(ast[3]);
ret->type = global.type;
return ret;
} else if (ast[2][0] == SUB) {
Ref target = ast[2];
assert(target[1][0] == NAME);
IString heap = target[1][1]->getIString();
assert(views.find(heap) != views.end());
View& view = views[heap];
auto ret = allocator.alloc<Store>();
ret->bytes = view.bytes;
ret->offset = 0;
ret->align = view.bytes;
ret->ptr = processUnshifted(target[2], view.bytes);
ret->value = process(ast[3]);
ret->type = asmToWasmType(view.type);
if (ret->type != ret->value->type) {
// in asm.js we have some implicit coercions that we must do explicitly here
if (ret->type == f32 && ret->value->type == f64) {
auto conv = allocator.alloc<Convert>();
conv->op = DemoteFloat64;
conv->value = ret->value;
conv->type = WasmType::f32;
ret->value = conv;
} else {
abort();
}
}
return ret;
}
abort_on("confusing assign", ast);
} else if (what == BINARY) {
if (ast[1] == OR && ast[3][0] == NUM && ast[3][1]->getNumber() == 0) {
auto ret = process(ast[2]); // just look through the ()|0 coercion
fixCallType(ret, i32);
return ret;
}
BinaryOp binary;
RelationalOp relational;
bool isBinary = parseAsmBinaryOp(ast[1]->getIString(), ast[2], ast[3], binary, relational, &asmData);
if (isBinary) {
auto ret = allocator.alloc<Binary>();
ret->op = binary;
ret->left = process(ast[2]);
ret->right = process(ast[3]);
ret->type = ret->left->type;
if (binary == BinaryOp::RemS && isWasmTypeFloat(ret->type)) {
// WebAssembly does not have floating-point remainder, we have to emit a call to a special import of ours
CallImport *call = allocator.alloc<CallImport>();
call->target = F64_REM;
call->operands.push_back(ret->left);
call->operands.push_back(ret->right);
call->type = f64;
static bool addedImport = false;
if (!addedImport) {
addedImport = true;
auto import = allocator.alloc<Import>(); // f64-rem = asm2wasm.f64-rem;
import->name = F64_REM;
import->module = ASM2WASM;
import->base = F64_REM;
import->type.name = F64_REM;
import->type.result = f64;
import->type.params.push_back(f64);
import->type.params.push_back(f64);
wasm.addImport(import);
}
return call;
}
return ret;
} else {
auto ret = allocator.alloc<Compare>();
ret->op = relational;
ret->left = process(ast[2]);
ret->right = process(ast[3]);
assert(ret->left->type == ret->right->type);
ret->inputType = ret->left->type;
return ret;
}
} else if (what == NUM) {
auto ret = allocator.alloc<Const>();
double num = ast[1]->getNumber();
if (isInteger32(num)) {
ret->value.type = WasmType::i32;
ret->value.i32 = num;
} else {
ret->value.type = WasmType::f64;
ret->value.f64 = num;
}
ret->type = ret->value.type;
return ret;
} else if (what == NAME) {
IString name = ast[1]->getIString();
if (functionVariables.has(name)) {
// var in scope
auto ret = allocator.alloc<GetLocal>();
ret->name = name;
ret->type = asmToWasmType(asmData.getType(name));
return ret;
}
if (name == DEBUGGER) {
CallImport *call = allocator.alloc<CallImport>();
call->target = DEBUGGER;
call->type = none;
static bool addedImport = false;
if (!addedImport) {
addedImport = true;
auto import = allocator.alloc<Import>(); // debugger = asm2wasm.debugger;
import->name = DEBUGGER;
import->module = ASM2WASM;
import->base = DEBUGGER;
import->type.name = DEBUGGER;
import->type.result = none;
wasm.addImport(import);
}
return call;
}
// global var, do a load from memory
assert(mappedGlobals.find(name) != mappedGlobals.end());
MappedGlobal global = mappedGlobals[name];
auto ret = allocator.alloc<Load>();
ret->bytes = getWasmTypeSize(global.type);
ret->signed_ = true; // but doesn't matter
ret->offset = 0;
ret->align = ret->bytes;
auto ptr = allocator.alloc<Const>();
ptr->value.type = WasmType::i32; // XXX for wasm64, need 64
ptr->value.i32 = global.address;
ret->ptr = ptr;
ret->type = global.type;
return ret;
} else if (what == SUB) {
Ref target = ast[1];
assert(target[0] == NAME);
IString heap = target[1]->getIString();
assert(views.find(heap) != views.end());
View& view = views[heap];
auto ret = allocator.alloc<Load>();
ret->bytes = view.bytes;
ret->signed_ = view.signed_;
ret->offset = 0;
ret->align = view.bytes;
ret->ptr = processUnshifted(ast[2], view.bytes);
ret->type = getWasmType(view.bytes, !view.integer);
return ret;
} else if (what == UNARY_PREFIX) {
if (ast[1] == PLUS) {
Literal literal = checkLiteral(ast);
if (literal.type != none) {
return allocator.alloc<Const>()->set(literal);
}
auto ret = process(ast[2]); // we are a +() coercion
if (ret->type == i32) {
auto conv = allocator.alloc<Convert>();
conv->op = isUnsignedCoercion(ast[2]) ? ConvertUInt32 : ConvertSInt32;
conv->value = ret;
conv->type = WasmType::f64;
return conv;
}
if (ret->type == f32) {
auto conv = allocator.alloc<Convert>();
conv->op = PromoteFloat32;
conv->value = ret;
conv->type = WasmType::f64;
return conv;
}
fixCallType(ret, f64);
return ret;
} else if (ast[1] == MINUS) {
if (ast[2][0] == NUM || (ast[2][0] == UNARY_PREFIX && ast[2][1] == PLUS && ast[2][2][0] == NUM)) {
auto ret = allocator.alloc<Const>();
ret->value = getLiteral(ast);
ret->type = ret->value.type;
return ret;
}
AsmType asmType = detectAsmType(ast[2], &asmData);
if (asmType == ASM_INT) {
// wasm has no unary negation for int, so do 0-
auto ret = allocator.alloc<Binary>();
ret->op = Sub;
ret->left = allocator.alloc<Const>()->set(Literal((int32_t)0));
ret->right = process(ast[2]);
ret->type = WasmType::i32;
return ret;
}
auto ret = allocator.alloc<Unary>();
ret->op = Neg;
ret->value = process(ast[2]);
if (asmType == ASM_DOUBLE) {
ret->type = WasmType::f64;
} else if (asmType == ASM_FLOAT) {
ret->type = WasmType::f32;
} else {
abort();
}
return ret;
} else if (ast[1] == B_NOT) {
// ~, might be ~~ as a coercion or just a not
if (ast[2][0] == UNARY_PREFIX && ast[2][1] == B_NOT) {
#if 0
auto ret = allocator.alloc<Convert>();
ret->op = TruncSFloat64; // equivalent to U, except for error handling, which asm.js doesn't have anyhow
ret->value = process(ast[2][2]);
ret->type = WasmType::i32;
return ret;
#endif
// WebAssembly traps on float-to-int overflows, but asm.js wouldn't, so we must emulate that
CallImport *ret = allocator.alloc<CallImport>();
ret->target = F64_TO_INT;
ret->operands.push_back(process(ast[2][2]));
ret->type = i32;
static bool addedImport = false;
if (!addedImport) {
addedImport = true;
auto import = allocator.alloc<Import>(); // f64-to-int = asm2wasm.f64-to-int;
import->name = F64_TO_INT;
import->module = ASM2WASM;
import->base = F64_TO_INT;
import->type.name = F64_TO_INT;
import->type.result = i32;
import->type.params.push_back(f64);
wasm.addImport(import);
}
return ret;
}
// no bitwise unary not, so do xor with -1
auto ret = allocator.alloc<Binary>();
ret->op = Xor;
ret->left = process(ast[2]);
ret->right = allocator.alloc<Const>()->set(Literal(int32_t(-1)));
ret->type = WasmType::i32;
return ret;
} else if (ast[1] == L_NOT) {
// no logical unary not, so do == 0
auto ret = allocator.alloc<Compare>();
ret->op = Eq;
ret->left = process(ast[2]);
ret->right = allocator.alloc<Const>()->set(Literal(0));
assert(ret->left->type == ret->right->type);
ret->inputType = ret->left->type;
return ret;
}
abort_on("bad unary", ast);
} else if (what == IF) {
auto ret = allocator.alloc<If>();
ret->condition = process(ast[1]);
ret->ifTrue = process(ast[2]);
ret->ifFalse = !!ast[3] ? process(ast[3]) : nullptr;
return ret;
} else if (what == CALL) {
if (ast[1][0] == NAME) {
IString name = ast[1][1]->getIString();
if (name == Math_imul) {
assert(ast[2]->size() == 2);
auto ret = allocator.alloc<Binary>();
ret->op = Mul;
ret->left = process(ast[2][0]);
ret->right = process(ast[2][1]);
ret->type = WasmType::i32;
return ret;
}
if (name == Math_clz32) {
assert(ast[2]->size() == 1);
auto ret = allocator.alloc<Unary>();
ret->op = Clz;
ret->value = process(ast[2][0]);
ret->type = WasmType::i32;
return ret;
}
if (name == Math_fround) {
assert(ast[2]->size() == 1);
Literal lit = checkLiteral(ast[2][0]);
if (lit.type == i32) {
return allocator.alloc<Const>()->set(Literal((float)lit.geti32()));
} else if (lit.type == f64) {
return allocator.alloc<Const>()->set(Literal((float)lit.getf64()));
}
auto ret = allocator.alloc<Convert>();
ret->value = process(ast[2][0]);
if (ret->value->type == f64) {
ret->op = DemoteFloat64;
} else if (ret->value->type == i32) {
ret->op = ConvertSInt32;
} else if (ret->value->type == f32) {
return ret->value;
} else if (ret->value->type == none) { // call, etc.
ret->value->type = f32;
return ret->value;
} else {
abort_on("confusing fround target", ast[2][0]);
}
ret->type = f32;
return ret;
}
if (name == Math_abs) {
// overloaded on type: i32, f32 or f64
Expression* value = process(ast[2][0]);
if (value->type == i32) {
// No wasm support, so use a temp local
ensureI32Temp();
auto set = allocator.alloc<SetLocal>();
set->name = I32_TEMP;
set->value = value;
set->type = i32;
auto get = [&]() {
auto ret = allocator.alloc<GetLocal>();
ret->name = I32_TEMP;
ret->type = i32;
return ret;
};
auto isNegative = allocator.alloc<Compare>();
isNegative->op = LtS;
isNegative->inputType = i32;
isNegative->left = get();
isNegative->right = allocator.alloc<Const>()->set(0);
auto block = allocator.alloc<Block>();
block->list.push_back(set);
auto flip = allocator.alloc<Binary>();
flip->op = Sub;
flip->left = allocator.alloc<Const>()->set(0);
flip->right = get();
flip->type = i32;
auto select = allocator.alloc<Select>();
select->condition = isNegative;
select->ifTrue = flip;
select->ifFalse = get();
select->type = i32;
block->list.push_back(select);
block->type = i32;
return block;
} else if (value->type == f32 || value->type == f64) {
auto ret = allocator.alloc<Unary>();
ret->op = Abs;
ret->value = value;
ret->type = value->type;
return ret;
} else {
abort();
}
}
if (name == Math_floor || name == Math_sqrt) {
// overloaded on type: f32 or f64
Expression* value = process(ast[2][0]);
if (value->type == f32 || value->type == f64) {
auto ret = allocator.alloc<Unary>();
ret->op = name == Math_floor ? Floor : Sqrt;
ret->value = value;
ret->type = value->type;
return ret;
} else {
abort();
}
}
Call* ret;
if (wasm.importsMap.find(name) != wasm.importsMap.end()) {
Ref parent = astStackHelper.getParent();
WasmType type = !!parent ? detectWasmType(parent, &asmData) : none;
ret = allocator.alloc<CallImport>();
noteImportedFunctionCall(ast, type, &asmData);
} else {
ret = allocator.alloc<Call>();
}
ret->target = name;
Ref args = ast[2];
for (unsigned i = 0; i < args->size(); i++) {
ret->operands.push_back(process(args[i]));
}
return ret;
}
// function pointers
auto ret = allocator.alloc<CallIndirect>();
Ref target = ast[1];
assert(target[0] == SUB && target[1][0] == NAME && target[2][0] == BINARY && target[2][1] == AND && target[2][3][0] == NUM); // FUNCTION_TABLE[(expr) & mask]
ret->target = process(target[2]); // TODO: as an optimization, we could look through the mask
Ref args = ast[2];
for (unsigned i = 0; i < args->size(); i++) {
ret->operands.push_back(process(args[i]));
}
ret->type = getFunctionType(astStackHelper.getParent(), ret->operands);
callIndirects[ret] = target[1][1]->getIString(); // we need to fix this up later, when we know how asm function tables are layed out inside the wasm table.
return ret;
} else if (what == RETURN) {
WasmType type = !!ast[1] ? detectWasmType(ast[1], &asmData) : none;
if (seenReturn) {
assert(function->result == type);
} else {
function->result = type;
}
// wasm has no return, so we just break on the topmost block
needTopmost = true;
auto ret = allocator.alloc<Break>();
ret->name = TOPMOST;
ret->value = !!ast[1] ? process(ast[1]) : nullptr;
return ret;
} else if (what == BLOCK) {
Name name;
if (parentLabel.is()) {
name = getBreakLabelName(parentLabel);
parentLabel = IString();
breakStack.push_back(name);
}
auto ret = processStatements(ast[1], 0);
if (name.is()) {
breakStack.pop_back();
Block* block = ret->dyn_cast<Block>();
if (block && block->name.isNull()) {
block->name = name;
} else {
block = allocator.alloc<Block>();
block->name = name;
block->list.push_back(ret);
ret = block;
}
}
return ret;
} else if (what == BREAK) {
auto ret = allocator.alloc<Break>();
assert(breakStack.size() > 0);
ret->name = !!ast[1] ? getBreakLabelName(ast[1]->getIString()) : breakStack.back();
return ret;
} else if (what == CONTINUE) {
auto ret = allocator.alloc<Break>();
assert(continueStack.size() > 0);
ret->name = !!ast[1] ? getContinueLabelName(ast[1]->getIString()) : continueStack.back();
return ret;
} else if (what == WHILE) {
bool forever = ast[1][0] == NUM && ast[1][1]->getInteger() == 1;
auto ret = allocator.alloc<Loop>();
IString out, in;
if (!parentLabel.isNull()) {
out = getBreakLabelName(parentLabel);
in = getContinueLabelName(parentLabel);
parentLabel = IString();
} else {
out = getNextId("while-out");
in = getNextId("while-in");
}
ret->out = out;
ret->in = in;
breakStack.push_back(out);
continueStack.push_back(in);
if (forever) {
ret->body = process(ast[2]);
} else {
Break *breakOut = allocator.alloc<Break>();
breakOut->name = out;
If *condition = allocator.alloc<If>();
condition->condition = process(ast[1]);
condition->ifTrue = allocator.alloc<Nop>();
condition->ifFalse = breakOut;
auto body = allocator.alloc<Block>();
body->list.push_back(condition);
body->list.push_back(process(ast[2]));
ret->body = body;
}
// loops do not automatically loop, add a branch back
Block* block = blockify(ret->body);
auto continuer = allocator.alloc<Break>();
continuer->name = ret->in;
block->list.push_back(continuer);
ret->body = block;
continueStack.pop_back();
breakStack.pop_back();
return ret;
} else if (what == DO) {
if (ast[1][0] == NUM && ast[1][1]->getNumber() == 0) {
// one-time loop
auto block = allocator.alloc<Block>();
IString stop;
if (!parentLabel.isNull()) {
stop = getBreakLabelName(parentLabel);
parentLabel = IString();
} else {
stop = getNextId("do-once");
}
block->name = stop;
breakStack.push_back(stop);
continueStack.push_back(IMPOSSIBLE_CONTINUE);
block->list.push_back(process(ast[2]));
continueStack.pop_back();
breakStack.pop_back();
return block;
}
// general do-while loop
auto ret = allocator.alloc<Loop>();
IString out, in;
if (!parentLabel.isNull()) {
out = getBreakLabelName(parentLabel);
in = getContinueLabelName(parentLabel);
parentLabel = IString();
} else {
out = getNextId("do-out");
in = getNextId("do-in");
}
ret->out = out;
ret->in = in;
breakStack.push_back(out);
continueStack.push_back(in);
ret->body = process(ast[2]);
continueStack.pop_back();
breakStack.pop_back();
Break *continuer = allocator.alloc<Break>();
continuer->name = in;
If *condition = allocator.alloc<If>();
condition->condition = process(ast[1]);
condition->ifTrue = continuer;
Block *block = blockify(ret->body);
block->list.push_back(condition);
ret->body = block;
return ret;
} else if (what == LABEL) {
assert(parentLabel.isNull());
parentLabel = ast[1]->getIString();
return process(ast[2]);
} else if (what == CONDITIONAL) {
auto ret = allocator.alloc<If>();
ret->condition = process(ast[1]);
ret->ifTrue = process(ast[2]);
ret->ifFalse = process(ast[3]);
ret->type = ret->ifTrue->type;
return ret;
} else if (what == SEQ) {
auto ret = allocator.alloc<Block>();
ret->list.push_back(process(ast[1]));
ret->list.push_back(process(ast[2]));
ret->type = ret->list[1]->type;
return ret;
} else if (what == SWITCH) {
IString name;
if (!parentLabel.isNull()) {
name = getBreakLabelName(parentLabel);
parentLabel = IString();
} else {
name = getNextId("switch");
}
breakStack.push_back(name);
auto ret = allocator.alloc<Switch>();
ret->name = name;
ret->value = process(ast[1]);
assert(ret->value->type == i32);
Ref cases = ast[2];
bool seen = false;
int min = 0; // the lowest index we see; we will offset to it
for (unsigned i = 0; i < cases->size(); i++) {
Ref curr = cases[i];
Ref condition = curr[0];
if (!condition->isNull()) {
assert(condition[0] == NUM || condition[0] == UNARY_PREFIX);
int32_t index = getLiteral(condition).geti32();
if (!seen) {
seen = true;
min = index;
} else {
if (index < min) min = index;
}
}
}
Binary* offsetor = allocator.alloc<Binary>();
offsetor->op = BinaryOp::Sub;
offsetor->left = ret->value;
offsetor->right = allocator.alloc<Const>()->set(Literal(min));
offsetor->type = i32;
ret->value = offsetor;
for (unsigned i = 0; i < cases->size(); i++) {
Ref curr = cases[i];
Ref condition = curr[0];
Ref body = curr[1];
Switch::Case case_;
case_.body = processStatements(body, 0);
if (condition->isNull()) {
case_.name = ret->default_ = getNextId("switch-default");
} else {
assert(condition[0] == NUM || condition[0] == UNARY_PREFIX);
int32_t index = getLiteral(condition).geti32();
assert(index >= min);
index -= min;
assert(index >= 0);
case_.name = getNextId("switch-case");
if (ret->targets.size() <= index) {
ret->targets.resize(index+1);
}
ret->targets[index] = case_.name;
}
ret->cases.push_back(case_);
}
// ensure a default
if (ret->default_.isNull()) {
Switch::Case defaultCase;
defaultCase.name = ret->default_ = getNextId("switch-default");
defaultCase.body = allocator.alloc<Nop>(); // ok if others fall through to this
ret->cases.push_back(defaultCase);
}
for (size_t i = 0; i < ret->targets.size(); i++) {
if (ret->targets[i].isNull()) ret->targets[i] = ret->default_;
}
// finalize
breakStack.pop_back();
return ret;
}
abort_on("confusing expression", ast);
return (Expression*)nullptr; // avoid warning
};
// given HEAP32[addr >> 2], we need an absolute address, and would like to remove that shift.
// if there is a shift, we can just look through it, etc.
processUnshifted = [&](Ref ptr, unsigned bytes) {
unsigned shifts = bytesToShift(bytes);
if (ptr[0] == BINARY && ptr[1] == RSHIFT && ptr[3][0] == NUM && ptr[3][1]->getInteger() == shifts) {
return process(ptr[2]); // look through it
} else if (ptr[0] == NUM) {
// constant, apply a shift (e.g. HEAP32[1] is address 4)
unsigned addr = ptr[1]->getInteger();
unsigned shifted = addr << shifts;
auto ret = allocator.alloc<Const>();
ret->value.type = WasmType::i32;
ret->value.i32 = shifted;
return (Expression*)ret;
}
abort_on("bad processUnshifted", ptr);
return (Expression*)nullptr; // avoid warning
};
processStatements = [&](Ref ast, unsigned from) -> Expression* {
unsigned size = ast->size() - from;
if (size == 0) return allocator.alloc<Nop>();
if (size == 1) return process(ast[from]);
auto block = allocator.alloc<Block>();
for (unsigned i = from; i < ast->size(); i++) {
block->list.push_back(process(ast[i]));
}
return block;
};
// body
function->body = processStatements(body, start);
if (needTopmost) {
Block* topmost = function->body->dyn_cast<Block>();
// if there's no block there, or there is a block but it already has a name, we need a new block.
if (!topmost || topmost->name.is()) {
topmost = allocator.alloc<Block>();
topmost->list.push_back(function->body);
function->body = topmost;
}
topmost->name = TOPMOST;
}
// cleanups/checks
assert(breakStack.size() == 0 && continueStack.size() == 0);
assert(parentLabel.isNull());
return function;
}
void Asm2WasmBuilder::optimize() {
// Optimization passes. Note: no effort is made to free nodes that are no longer held on to.
struct BlockBreakOptimizer : public WasmWalker {
void visitBlock(Block *curr) override {
// if the block ends in a break on this very block, then just put the value there
Break *last = curr->list[curr->list.size()-1]->dyn_cast<Break>();
if (last && last->value && last->name == curr->name) {
curr->list[curr->list.size()-1] = last->value;
}
if (curr->list.size() > 1) return; // no hope to remove the block
// just one element; maybe we can return just the element
if (curr->name.isNull()) {
replaceCurrent(curr->list[0]); // cannot break into it
return;
}
// we might be broken to, but maybe there isn't a break (and we may have removed it, leading to this)
struct BreakSeeker : public WasmWalker {
IString target; // look for this one
size_t found;
BreakSeeker(IString target) : target(target), found(false) {}
void visitBreak(Break *curr) override {
if (curr->name == target) found++;
}
};
// look for any breaks to this block
BreakSeeker breakSeeker(curr->name);
Expression *child = curr->list[0];
breakSeeker.walk(child);
if (breakSeeker.found == 0) {
replaceCurrent(child); // no breaks to here, so eliminate the block
}
}
};
BlockBreakOptimizer blockBreakOptimizer;
for (auto pair : wasm.functionsMap) {
blockBreakOptimizer.startWalk(pair.second);
}
}
} // namespace wasm
| [
"alonzakai@gmail.com"
] | alonzakai@gmail.com |
893fbd7837194e5f0793f3794fe7e569b7ba2e18 | ecca4afeab636dcc4c2197b51cbb7e42b14361a3 | /opencv_data/opencv_pca/MainWindow.cpp | 8655bf6c80c1d6923c3c5564e0227efdc32ff1c7 | [] | no_license | ngzHappy/oct2 | f1140c2d930c7bd202b4494f1d4eab8e0d3fc4b2 | 5d4b17774e92ec149da68ec06c4543151e8885e1 | refs/heads/master | 2020-05-21T13:35:32.311475 | 2016-12-08T10:25:25 | 2016-12-08T10:25:25 | 55,474,235 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 773 | cpp | /*MainWindow.cpp*/
#include "MainWindow.hpp"
#include "OpenCVWindowDetail.hpp"
#include <QtWidgets/qboxlayout.h>
/*中央窗口*/
namespace {
namespace __private {
class CentralWidget :public QWidget {
QVBoxLayout * layout_;
public:
CentralWidget(OpenCVWindow * window) {
layout_=new QVBoxLayout;
this->setLayout(layout_);
layout_->setSpacing(0);
layout_->setMargin(0);
layout_->addWidget(window);
}
~CentralWidget() {}
};
}
}
/*初始化主窗口*/
MainWindow::MainWindow(QWidget *parent):
P(parent) {
openCVWindow_=new OpenCVWindowDetail;
this->setCentralWidget(new __private::CentralWidget(openCVWindow_));
this->setMinimumSize(512,512);
}
/*析构主窗口*/
MainWindow::~MainWindow() {
}
| [
"819869472@qq.com"
] | 819869472@qq.com |
d5abb77d924db3af18b9d35975572c67f8afb48d | 5a380cbb0e6d5d57c80ae710d8bf5e39b06bfb5e | /Game/boost/boost/random/uniform_real.hpp | e221f6a9f18ddba4096593bd8637b428c5f64ee7 | [
"MIT"
] | permissive | jxianglonggg/SourceCodeGameTLBB | afcf222603c20651db02716f8c7dac80f9aa14e8 | e3cea615b06761c2098a05427a5f41c236b71bf7 | refs/heads/master | 2023-05-04T02:25:08.807563 | 2021-05-18T06:02:37 | 2021-05-18T06:02:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,403 | hpp | /* boost random/uniform_real.hpp header file
*
* Copyright Jens Maurer 2000-2001
* Distributed under the Boost Software License, Version 1.0. (See
* accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* See http://www.boost.org for most recent version including documentation.
*
* $Id: uniform_real.hpp,v 1.1.1.1 2007/10/29 07:32:44 cvsadmin Exp $
*
* Revision history
* 2001-04-08 added min<max assertion (N. Becker)
* 2001-02-18 moved to individual header files
*/
#ifndef BOOST_RANDOM_UNIFORM_REAL_HPP
#define BOOST_RANDOM_UNIFORM_REAL_HPP
#include <cassert>
#include <iostream>
#include <boost/config.hpp>
#include <boost/limits.hpp>
#include <boost/static_assert.hpp>
namespace boost {
// uniform distribution on a real range
template<class RealType = double>
class uniform_real
{
public:
typedef RealType input_type;
typedef RealType result_type;
explicit uniform_real(RealType min = RealType(0),
RealType max = RealType(1))
: _min(min), _max(max)
{
#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
BOOST_STATIC_ASSERT(!std::numeric_limits<RealType>::is_integer);
#endif
assert(min < max);
}
// compiler-generated copy ctor and assignment operator are fine
result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return _min; }
result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return _max; }
void reset() { }
template<class Engine>
result_type operator()(Engine& eng) {
return static_cast<result_type>(eng() - eng.min BOOST_PREVENT_MACRO_SUBSTITUTION())
/ static_cast<result_type>(eng.max BOOST_PREVENT_MACRO_SUBSTITUTION() - eng.min BOOST_PREVENT_MACRO_SUBSTITUTION())
* (_max - _min) + _min;
}
#if !defined(BOOST_NO_OPERATORS_IN_NAMESPACE) && !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
template<class CharT, class Traits>
friend std::basic_ostream<CharT,Traits>&
operator<<(std::basic_ostream<CharT,Traits>& os, const uniform_real& ud)
{
os << ud._min << " " << ud._max;
return os;
}
template<class CharT, class Traits>
friend std::basic_istream<CharT,Traits>&
operator>>(std::basic_istream<CharT,Traits>& is, uniform_real& ud)
{
is >> std::ws >> ud._min >> std::ws >> ud._max;
return is;
}
#endif
private:
RealType _min, _max;
};
} // namespace boost
#endif // BOOST_RANDOM_UNIFORM_REAL_HPP
| [
"shacojx001@gmail.com"
] | shacojx001@gmail.com |
4b064cc87c641d903f00c03a7cc0aace276b6f0f | c8a29d344b99479c06507d45a3f0887224603b04 | /gamelib/src/Loggable.cpp | fb2e2da0e188b6569ee61e78dd3e54cb86615b66 | [] | no_license | jrahman-zz/CS307 | 0f01e336e0c82d05cf36a18415a103c354af3267 | 5d266c20f2a3a34704b20bdfe8a7caf501e42f52 | refs/heads/master | 2022-08-15T16:20:34.956788 | 2014-12-16T00:58:35 | 2014-12-16T00:58:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 330 | cpp | #include "Loggable.h"
#include "LogObserver.h"
Loggable::Loggable() {
}
void Loggable::registerLogObserver(weak_ptr<LogObserver> obs) {
m_logObserver = obs;
}
void Loggable::log(shared_ptr<LogEntry> entry) {
auto observer = m_logObserver.lock();
if (observer != nullptr) {
observer->onLog(entry);
}
}
| [
"rahmanj@purdue.edu"
] | rahmanj@purdue.edu |
85592f1adfd57eb76ce752de8da5cba236bc1604 | b0842664ede379fc516503d90af3afffe35c6740 | /test/test2.cc | e93a48c939c45b1d5d29534ffa9879f62d0da299 | [
"MIT"
] | permissive | mqnc/cpp-peglib | dfd18945df1a2d15053b93b3041ca7007d055a9c | be759267ea28a5a4b444e7f9fb34ac51e9e25a1b | refs/heads/master | 2021-06-16T05:02:57.844413 | 2021-02-26T18:24:57 | 2021-02-26T18:24:57 | 147,244,178 | 0 | 0 | MIT | 2018-09-10T17:15:13 | 2018-09-03T19:16:06 | C++ | UTF-8 | C++ | false | false | 42,165 | cc | #include "catch.hh"
#include <peglib.h>
#include <sstream>
using namespace peg;
TEST_CASE("Token boundary 1", "[token boundary]")
{
parser pg(R"(
ROOT <- TOP
TOP <- 'a' 'b' 'c'
%whitespace <- [ \t\r\n]*
)");
REQUIRE(pg.parse(" a b c "));
}
TEST_CASE("Token boundary 2", "[token boundary]")
{
parser pg(R"(
ROOT <- TOP
TOP <- < 'a' 'b' 'c' >
%whitespace <- [ \t\r\n]*
)");
REQUIRE(!pg.parse(" a b c "));
}
TEST_CASE("Token boundary 3", "[token boundary]")
{
parser pg(R"(
ROOT <- TOP
TOP <- < 'a' B 'c' >
B <- 'b'
%whitespace <- [ \t\r\n]*
)");
REQUIRE(!pg.parse(" a b c "));
}
TEST_CASE("Token boundary 4", "[token boundary]")
{
parser pg(R"(
ROOT <- TOP
TOP <- < A 'b' 'c' >
A <- 'a'
%whitespace <- [ \t\r\n]*
)");
REQUIRE(!pg.parse(" a b c "));
}
TEST_CASE("Token boundary 5", "[token boundary]")
{
parser pg(R"(
ROOT <- TOP
TOP <- A < 'b' C >
A <- 'a'
C <- 'c'
%whitespace <- [ \t\r\n]*
)");
REQUIRE(!pg.parse(" a b c "));
}
TEST_CASE("Token boundary 6", "[token boundary]")
{
parser pg(R"(
ROOT <- TOP
TOP <- < A > B C
A <- 'a'
B <- 'b'
C <- 'c'
%whitespace <- [ \t\r\n]*
)");
REQUIRE(pg.parse(" a b c "));
}
TEST_CASE("Token boundary 7", "[token boundary]")
{
parser pg(R"(
ROOT <- TOP
TOP <- < A B C >
A <- 'a'
B <- 'b'
C <- 'c'
%whitespace <- [ \t\r\n]*
)");
REQUIRE(!pg.parse(" a b c "));
}
TEST_CASE("Infinite loop 1", "[infinite loop]")
{
parser pg(R"(
ROOT <- WH TOKEN* WH
TOKEN <- [a-z0-9]*
WH <- [ \t]*
)");
REQUIRE(!pg);
}
TEST_CASE("Infinite loop 2", "[infinite loop]") {
parser pg(R"(
ROOT <- WH TOKEN+ WH
TOKEN <- [a-z0-9]*
WH <- [ \t]*
)");
REQUIRE(!pg);
}
TEST_CASE("Infinite loop 3", "[infinite loop]") {
parser pg(R"(
ROOT <- WH TOKEN* WH
TOKEN <- !'word1'
WH <- [ \t]*
)");
REQUIRE(!pg);
}
TEST_CASE("Infinite loop 4", "[infinite loop]") {
parser pg(R"(
ROOT <- WH TOKEN* WH
TOKEN <- &'word1'
WH <- [ \t]*
)");
REQUIRE(!pg);
}
TEST_CASE("Infinite loop 5", "[infinite loop]") {
parser pg(R"(
Numbers <- Number*
Number <- [0-9]+ / Spacing
Spacing <- ' ' / '\t' / '\n' / EOF # EOF is empty
EOF <- !.
)");
REQUIRE(!pg);
}
TEST_CASE("Infinite loop 6", "[infinite loop]") {
parser pg(R"(
S <- ''*
)");
REQUIRE(!pg);
}
TEST_CASE("Infinite loop 7", "[infinite loop]") {
parser pg(R"(
S <- A*
A <- ''
)");
REQUIRE(!pg);
}
TEST_CASE("Infinite loop 8", "[infinite loop]") {
parser pg(R"(
ROOT <- ('A' /)*
)");
REQUIRE(!pg);
}
TEST_CASE("Infinite 9", "[infinite loop]") {
parser pg(R"(
START <- __? SECTION*
SECTION <- HEADER __ ENTRIES __?
HEADER <- '[' _ CATEGORY (':' _ ATTRIBUTES)? ']'^header
CATEGORY <- < [-_a-zA-Z0-9\u0080-\uFFFF ]+ > _
ATTRIBUTES <- ATTRIBUTE (',' _ ATTRIBUTE)*
ATTRIBUTE <- < [-_a-zA-Z0-9\u0080-\uFFFF]+ > _
ENTRIES <- (ENTRY (__ ENTRY)*)?
ENTRY <- ONE_WAY PHRASE ('|' _ PHRASE)* !'='
/ PHRASE ('|' _ PHRASE)+ !'='
/ %recover(entry)
ONE_WAY <- PHRASE '=' _
PHRASE <- WORD (' ' WORD)* _
WORD <- < (![ \t\r\n=|[\]#] .)+ >
~__ <- _ (comment? nl _)+
~_ <- [ \t]*
comment <- ('#' (!nl .)*)
nl <- '\r'? '\n'
header <- (!__ .)* { message "invalid section header, missing ']'." }
# The `(!(__ / HEADER) )+` should be `(!(__ / HEADER) .)+`
entry <- (!(__ / HEADER) )+ { message "invalid token '%t', expecting another phrase." }
)");
REQUIRE(!pg);
}
TEST_CASE("Not infinite 1", "[infinite loop]") {
parser pg(R"(
Numbers <- Number* EOF
Number <- [0-9]+ / Spacing
Spacing <- ' ' / '\t' / '\n'
EOF <- !.
)");
REQUIRE(!!pg); // OK
}
TEST_CASE("Not infinite 2", "[infinite loop]") {
parser pg(R"(
ROOT <- _ ('[' TAG_NAME ']' _)*
# In a sequence operator, if there is at least one non-empty element, we can treat it as non-empty
TAG_NAME <- (!']' .)+
_ <- [ \t]*
)");
REQUIRE(!!pg); // OK
}
TEST_CASE("Not infinite 3", "[infinite loop]") {
parser pg(R"(
EXPRESSION <- _ TERM (TERM_OPERATOR TERM)*
TERM <- FACTOR (FACTOR_OPERATOR FACTOR)*
FACTOR <- NUMBER / '(' _ EXPRESSION ')' _ # Recursive...
TERM_OPERATOR <- < [-+] > _
FACTOR_OPERATOR <- < [/*] > _
NUMBER <- < [0-9]+ > _
_ <- [ \t\r\n]*
)");
REQUIRE(!!pg); // OK
}
TEST_CASE("Precedence climbing", "[precedence]") {
parser parser(R"(
START <- _ EXPRESSION
EXPRESSION <- ATOM (OPERATOR ATOM)* {
precedence
L + -
L * /
}
ATOM <- NUMBER / T('(') EXPRESSION T(')')
OPERATOR <- T([-+/*])
NUMBER <- T('-'? [0-9]+)
~_ <- [ \t]*
T(S) <- < S > _
)");
REQUIRE(!!parser); // OK
parser.enable_packrat_parsing();
// Setup actions
parser["EXPRESSION"] = [](const SemanticValues &vs) -> long {
auto result = std::any_cast<long>(vs[0]);
if (vs.size() > 1) {
auto ope = std::any_cast<char>(vs[1]);
auto num = std::any_cast<long>(vs[2]);
switch (ope) {
case '+': result += num; break;
case '-': result -= num; break;
case '*': result *= num; break;
case '/': result /= num; break;
}
}
return result;
};
parser["OPERATOR"] = [](const SemanticValues &vs) { return *vs.sv().data(); };
parser["NUMBER"] = [](const SemanticValues &vs) { return vs.token_to_number<long>(); };
bool ret = parser;
REQUIRE(ret == true);
{
auto expr = " 1 + 2 * 3 * (4 - 5 + 6) / 7 - 8 ";
long val = 0;
ret = parser.parse(expr, val);
REQUIRE(ret == true);
REQUIRE(val == -3);
}
{
auto expr = "-1+-2--3"; // -1 + -2 - -3 = 0
long val = 0;
ret = parser.parse(expr, val);
REQUIRE(ret == true);
REQUIRE(val == 0);
}
}
TEST_CASE("Precedence climbing with macro", "[precedence]") {
// Create a PEG parser
parser parser(R"(
EXPRESSION <- INFIX_EXPRESSION(ATOM, OPERATOR)
INFIX_EXPRESSION(A, O) <- A (O A)* {
precedence
L + -
L * /
}
ATOM <- NUMBER / '(' EXPRESSION ')'
OPERATOR <- < [-+/*] >
NUMBER <- < '-'? [0-9]+ >
%whitespace <- [ \t]*
)");
parser.enable_packrat_parsing();
bool ret = parser;
REQUIRE(ret == true);
// Setup actions
parser["INFIX_EXPRESSION"] = [](const SemanticValues &vs) -> long {
auto result = std::any_cast<long>(vs[0]);
if (vs.size() > 1) {
auto ope = std::any_cast<char>(vs[1]);
auto num = std::any_cast<long>(vs[2]);
switch (ope) {
case '+': result += num; break;
case '-': result -= num; break;
case '*': result *= num; break;
case '/': result /= num; break;
}
}
return result;
};
parser["OPERATOR"] = [](const SemanticValues &vs) { return *vs.sv().data(); };
parser["NUMBER"] = [](const SemanticValues &vs) { return vs.token_to_number<long>(); };
{
auto expr = " 1 + 2 * 3 * (4 - 5 + 6) / 7 - 8 ";
long val = 0;
ret = parser.parse(expr, val);
REQUIRE(ret == true);
REQUIRE(val == -3);
}
{
auto expr = "-1+-2--3"; // -1 + -2 - -3 = 0
long val = 0;
ret = parser.parse(expr, val);
REQUIRE(ret == true);
REQUIRE(val == 0);
}
}
TEST_CASE("Precedence climbing error1", "[precedence]") {
parser parser(R"(
START <- _ EXPRESSION
EXPRESSION <- ATOM (OPERATOR ATOM1)* {
precedence
L + -
L * /
}
ATOM <- NUMBER / T('(') EXPRESSION T(')')
ATOM1 <- NUMBER / T('(') EXPRESSION T(')')
OPERATOR <- T([-+/*])
NUMBER <- T('-'? [0-9]+)
~_ <- [ \t]*
T(S) <- < S > _
)");
bool ret = parser;
REQUIRE(ret == false);
}
TEST_CASE("Precedence climbing error2", "[precedence]") {
parser parser(R"(
START <- _ EXPRESSION
EXPRESSION <- ATOM OPERATOR ATOM {
precedence
L + -
L * /
}
ATOM <- NUMBER / T('(') EXPRESSION T(')')
OPERATOR <- T([-+/*])
NUMBER <- T('-'? [0-9]+)
~_ <- [ \t]*
T(S) <- < S > _
)");
bool ret = parser;
REQUIRE(ret == false);
}
TEST_CASE("Precedence climbing error3", "[precedence]") {
parser parser(R"(
EXPRESSION <- PRECEDENCE_PARSING(ATOM, OPERATOR)
PRECEDENCE_PARSING(A, O) <- A (O A)+ {
precedence
L + -
L * /
}
ATOM <- NUMBER / '(' EXPRESSION ')'
OPERATOR <- < [-+/*] >
NUMBER <- < '-'? [0-9]+ >
%whitespace <- [ \t]*
)");
bool ret = parser;
REQUIRE(ret == false);
}
TEST_CASE("Packrat parser test with %whitespace%", "[packrat]") {
peg::parser parser(R"(
ROOT <- 'a'
%whitespace <- SPACE*
SPACE <- ' '
)");
parser.enable_packrat_parsing();
auto ret = parser.parse("a");
REQUIRE(ret == true);
}
TEST_CASE("Packrat parser test with macro", "[packrat]") {
parser parser(R"(
EXPRESSION <- _ LIST(TERM, TERM_OPERATOR)
TERM <- LIST(FACTOR, FACTOR_OPERATOR)
FACTOR <- NUMBER / T('(') EXPRESSION T(')')
TERM_OPERATOR <- T([-+])
FACTOR_OPERATOR <- T([/*])
NUMBER <- T([0-9]+)
~_ <- [ \t]*
LIST(I, D) <- I (D I)*
T(S) <- < S > _
)");
parser.enable_packrat_parsing();
auto ret = parser.parse(" 1 + 2 * 3 * (4 - 5 + 6) / 7 - 8 ");
REQUIRE(ret == true);
}
TEST_CASE("Packrat parser test with precedence expression parser",
"[packrat]") {
peg::parser parser(R"(
Expression <- Atom (Operator Atom)* { precedence L + - L * / }
Atom <- _? Number _?
Number <- [0-9]+
Operator <- '+' / '-' / '*' / '/'
_ <- ' '+
)");
bool ret = parser;
REQUIRE(ret == true);
parser.enable_packrat_parsing();
ret = parser.parse(" 1 + 2 * 3 ");
REQUIRE(ret == true);
}
TEST_CASE("Backreference test", "[backreference]") {
parser parser(R"(
START <- _ LQUOTE < (!RQUOTE .)* > RQUOTE _
LQUOTE <- 'R"' $delm< [a-zA-Z]* > '('
RQUOTE <- ')' $delm '"'
~_ <- [ \t\r\n]*
)");
std::string token;
parser["START"] = [&](const SemanticValues &vs) { token = vs.token(); };
{
token.clear();
auto ret = parser.parse(R"delm(
R"("hello world")"
)delm");
REQUIRE(ret == true);
REQUIRE(token == "\"hello world\"");
}
{
token.clear();
auto ret = parser.parse(R"delm(
R"foo("(hello world)")foo"
)delm");
REQUIRE(ret == true);
REQUIRE(token == "\"(hello world)\"");
}
{
token.clear();
auto ret = parser.parse(R"delm(
R"foo("(hello world)foo")foo"
)delm");
REQUIRE(ret == false);
REQUIRE(token == "\"(hello world");
}
{
token.clear();
auto ret = parser.parse(R"delm(
R"foo("(hello world)")bar"
)delm");
REQUIRE(ret == false);
REQUIRE(token.empty());
}
}
TEST_CASE("Invalid backreference test", "[backreference]") {
parser parser(R"(
START <- _ LQUOTE (!RQUOTE .)* RQUOTE _
LQUOTE <- 'R"' $delm< [a-zA-Z]* > '('
RQUOTE <- ')' $delm2 '"'
~_ <- [ \t\r\n]*
)");
REQUIRE_THROWS_AS(parser.parse(R"delm(
R"foo("(hello world)")foo"
)delm"),
std::runtime_error);
}
TEST_CASE("Nested capture test", "[backreference]") {
parser parser(R"(
ROOT <- CONTENT
CONTENT <- (ELEMENT / TEXT)*
ELEMENT <- $(STAG CONTENT ETAG)
STAG <- '<' $tag< TAG_NAME > '>'
ETAG <- '</' $tag '>'
TAG_NAME <- 'b' / 'u'
TEXT <- TEXT_DATA
TEXT_DATA <- ![<] .
)");
REQUIRE(parser.parse("This is <b>a <u>test</u> text</b>."));
REQUIRE(!parser.parse("This is <b>a <u>test</b> text</u>."));
REQUIRE(!parser.parse("This is <b>a <u>test text</b>."));
REQUIRE(!parser.parse("This is a <u>test</u> text</b>."));
}
TEST_CASE("Backreference with Prioritized Choice test", "[backreference]") {
parser parser(R"(
TREE <- WRONG_BRANCH / CORRECT_BRANCH
WRONG_BRANCH <- BRANCH THAT IS_capture WRONG
CORRECT_BRANCH <- BRANCH THAT IS_backref CORRECT
BRANCH <- 'branch'
THAT <- 'that'
IS_capture <- $ref<..>
IS_backref <- $ref
WRONG <- 'wrong'
CORRECT <- 'correct'
)");
REQUIRE_THROWS_AS(parser.parse("branchthatiscorrect"), std::runtime_error);
}
TEST_CASE("Backreference with Zero or More test", "[backreference]") {
parser parser(R"(
TREE <- WRONG_BRANCH* CORRECT_BRANCH
WRONG_BRANCH <- BRANCH THAT IS_capture WRONG
CORRECT_BRANCH <- BRANCH THAT IS_backref CORRECT
BRANCH <- 'branch'
THAT <- 'that'
IS_capture <- $ref<..>
IS_backref <- $ref
WRONG <- 'wrong'
CORRECT <- 'correct'
)");
REQUIRE(parser.parse("branchthatiswrongbranchthatiscorrect"));
REQUIRE(!parser.parse("branchthatiswrongbranchthatIscorrect"));
REQUIRE(
!parser.parse("branchthatiswrongbranchthatIswrongbranchthatiscorrect"));
REQUIRE(
parser.parse("branchthatiswrongbranchthatIswrongbranchthatIscorrect"));
REQUIRE_THROWS_AS(parser.parse("branchthatiscorrect"), std::runtime_error);
REQUIRE_THROWS_AS(parser.parse("branchthatiswron_branchthatiscorrect"),
std::runtime_error);
}
TEST_CASE("Backreference with One or More test", "[backreference]") {
parser parser(R"(
TREE <- WRONG_BRANCH+ CORRECT_BRANCH
WRONG_BRANCH <- BRANCH THAT IS_capture WRONG
CORRECT_BRANCH <- BRANCH THAT IS_backref CORRECT
BRANCH <- 'branch'
THAT <- 'that'
IS_capture <- $ref<..>
IS_backref <- $ref
WRONG <- 'wrong'
CORRECT <- 'correct'
)");
REQUIRE(parser.parse("branchthatiswrongbranchthatiscorrect"));
REQUIRE(!parser.parse("branchthatiswrongbranchthatIscorrect"));
REQUIRE(
!parser.parse("branchthatiswrongbranchthatIswrongbranchthatiscorrect"));
REQUIRE(
parser.parse("branchthatiswrongbranchthatIswrongbranchthatIscorrect"));
REQUIRE(!parser.parse("branchthatiscorrect"));
REQUIRE(!parser.parse("branchthatiswron_branchthatiscorrect"));
}
TEST_CASE("Backreference with Option test", "[backreference]") {
parser parser(R"(
TREE <- WRONG_BRANCH? CORRECT_BRANCH
WRONG_BRANCH <- BRANCH THAT IS_capture WRONG
CORRECT_BRANCH <- BRANCH THAT IS_backref CORRECT
BRANCH <- 'branch'
THAT <- 'that'
IS_capture <- $ref<..>
IS_backref <- $ref
WRONG <- 'wrong'
CORRECT <- 'correct'
)");
REQUIRE(parser.parse("branchthatiswrongbranchthatiscorrect"));
REQUIRE(!parser.parse("branchthatiswrongbranchthatIscorrect"));
REQUIRE(
!parser.parse("branchthatiswrongbranchthatIswrongbranchthatiscorrect"));
REQUIRE(
!parser.parse("branchthatiswrongbranchthatIswrongbranchthatIscorrect"));
REQUIRE_THROWS_AS(parser.parse("branchthatiscorrect"), std::runtime_error);
REQUIRE_THROWS_AS(parser.parse("branchthatiswron_branchthatiscorrect"),
std::runtime_error);
}
TEST_CASE("Repetition {0}", "[repetition]") {
parser parser(R"(
START <- '(' DIGIT{3} ') ' DIGIT{3} '-' DIGIT{4}
DIGIT <- [0-9]
)");
REQUIRE(parser.parse("(123) 456-7890"));
REQUIRE(!parser.parse("(12a) 456-7890"));
REQUIRE(!parser.parse("(123) 45-7890"));
REQUIRE(!parser.parse("(123) 45-7a90"));
}
TEST_CASE("Repetition {2,4}", "[repetition]") {
parser parser(R"(
START <- DIGIT{2,4}
DIGIT <- [0-9]
)");
REQUIRE(!parser.parse("1"));
REQUIRE(parser.parse("12"));
REQUIRE(parser.parse("123"));
REQUIRE(parser.parse("1234"));
REQUIRE(!parser.parse("12345"));
}
TEST_CASE("Repetition {2,1}", "[repetition]") {
parser parser(R"(
START <- DIGIT{2,1} # invalid range
DIGIT <- [0-9]
)");
REQUIRE(!parser.parse("1"));
REQUIRE(parser.parse("12"));
REQUIRE(!parser.parse("123"));
}
TEST_CASE("Repetition {2,}", "[repetition]") {
parser parser(R"(
START <- DIGIT{2,}
DIGIT <- [0-9]
)");
REQUIRE(!parser.parse("1"));
REQUIRE(parser.parse("12"));
REQUIRE(parser.parse("123"));
REQUIRE(parser.parse("1234"));
}
TEST_CASE("Repetition {,2}", "[repetition]") {
parser parser(R"(
START <- DIGIT{,2}
DIGIT <- [0-9]
)");
REQUIRE(parser.parse("1"));
REQUIRE(parser.parse("12"));
REQUIRE(!parser.parse("123"));
REQUIRE(!parser.parse("1234"));
}
TEST_CASE("Left recursive test", "[left recursive]") {
parser parser(R"(
A <- A 'a'
B <- A 'a'
)");
REQUIRE(!parser);
}
TEST_CASE("Left recursive with option test", "[left recursive]") {
parser parser(R"(
A <- 'a' / 'b'? B 'c'
B <- A
)");
REQUIRE(!parser);
}
TEST_CASE("Left recursive with zom test", "[left recursive]") {
parser parser(R"(
A <- 'a'* A*
)");
REQUIRE(!parser);
}
TEST_CASE("Left recursive with a ZOM content rule", "[left recursive]") {
parser parser(R"(
A <- B
B <- _ A
_ <- ' '* # Zero or more
)");
REQUIRE(!parser);
}
TEST_CASE("Left recursive with empty string test", "[left recursive]") {
parser parser(" A <- '' A");
REQUIRE(!parser);
}
TEST_CASE("User defined rule test", "[user rule]") {
auto g = parser(R"(
ROOT <- _ 'Hello' _ NAME '!' _
)",
{{"NAME", usr([](const char *s, size_t n, SemanticValues &,
std::any &) -> size_t {
static std::vector<std::string> names = {"PEG", "BNF"};
for (const auto &name : names) {
if (name.size() <= n &&
!name.compare(0, name.size(), s, name.size())) {
return name.size();
}
}
return static_cast<size_t>(-1);
})},
{"~_", zom(cls(" \t\r\n"))}});
REQUIRE(g.parse(" Hello BNF! ") == true);
}
TEST_CASE("Semantic predicate test", "[predicate]") {
parser parser("NUMBER <- [0-9]+");
parser["NUMBER"] = [](const SemanticValues &vs) {
auto val = vs.token_to_number<long>();
if (val != 100) { throw parse_error("value error!!"); }
return val;
};
long val;
REQUIRE(parser.parse("100", val));
REQUIRE(val == 100);
parser.log = [](size_t line, size_t col, const std::string &msg) {
REQUIRE(line == 1);
REQUIRE(col == 1);
REQUIRE(msg == "value error!!");
};
REQUIRE(!parser.parse("200", val));
}
TEST_CASE("Japanese character", "[unicode]") {
peg::parser parser(u8R"(
文 <- 修飾語? 主語 述語 '。'
主語 <- 名詞 助詞
述語 <- 動詞 助詞
修飾語 <- 形容詞
名詞 <- 'サーバー' / 'クライアント'
形容詞 <- '古い' / '新しい'
動詞 <- '落ち' / '復旧し'
助詞 <- 'が' / 'を' / 'た' / 'ます' / 'に'
)");
bool ret = parser;
REQUIRE(ret == true);
REQUIRE(parser.parse(u8R"(サーバーを復旧します。)"));
}
TEST_CASE("dot with a code", "[unicode]") {
peg::parser parser(" S <- 'a' . 'b' ");
REQUIRE(parser.parse(u8R"(aあb)"));
}
TEST_CASE("dot with a char", "[unicode]") {
peg::parser parser(" S <- 'a' . 'b' ");
REQUIRE(parser.parse(u8R"(aåb)"));
}
TEST_CASE("character class", "[unicode]") {
peg::parser parser(R"(
S <- 'a' [い-おAさC-Eた-とは] 'b'
)");
bool ret = parser;
REQUIRE(ret == true);
REQUIRE(!parser.parse(u8R"(aあb)"));
REQUIRE(parser.parse(u8R"(aいb)"));
REQUIRE(parser.parse(u8R"(aうb)"));
REQUIRE(parser.parse(u8R"(aおb)"));
REQUIRE(!parser.parse(u8R"(aかb)"));
REQUIRE(parser.parse(u8R"(aAb)"));
REQUIRE(!parser.parse(u8R"(aBb)"));
REQUIRE(parser.parse(u8R"(aEb)"));
REQUIRE(!parser.parse(u8R"(aFb)"));
REQUIRE(!parser.parse(u8R"(aそb)"));
REQUIRE(parser.parse(u8R"(aたb)"));
REQUIRE(parser.parse(u8R"(aちb)"));
REQUIRE(parser.parse(u8R"(aとb)"));
REQUIRE(!parser.parse(u8R"(aなb)"));
REQUIRE(parser.parse(u8R"(aはb)"));
REQUIRE(!parser.parse(u8R"(a?b)"));
}
#if 0 // TODO: Unicode Grapheme support
TEST_CASE("dot with a grapheme", "[unicode]")
{
peg::parser parser(" S <- 'a' . 'b' ");
REQUIRE(parser.parse(u8R"(aसिb)"));
}
#endif
TEST_CASE("Macro simple test", "[macro]") {
parser parser(R"(
S <- HELLO WORLD
HELLO <- T('hello')
WORLD <- T('world')
T(a) <- a [ \t]*
)");
REQUIRE(parser.parse("hello \tworld "));
}
TEST_CASE("Macro two parameters", "[macro]") {
parser parser(R"(
S <- HELLO_WORLD
HELLO_WORLD <- T('hello', 'world')
T(a, b) <- a [ \t]* b [ \t]*
)");
REQUIRE(parser.parse("hello \tworld "));
}
TEST_CASE("Macro syntax error", "[macro]") {
parser parser(R"(
S <- T('hello')
T (a) <- a [ \t]*
)");
bool ret = parser;
REQUIRE(ret == false);
}
TEST_CASE("Macro missing argument", "[macro]") {
parser parser(R"(
S <- T ('hello')
T(a, b) <- a [ \t]* b
)");
bool ret = parser;
REQUIRE(ret == false);
}
TEST_CASE("Macro reference syntax error", "[macro]") {
parser parser(R"(
S <- T ('hello')
T(a) <- a [ \t]*
)");
bool ret = parser;
REQUIRE(ret == false);
}
TEST_CASE("Macro invalid macro reference error", "[macro]") {
parser parser(R"(
S <- T('hello')
T <- 'world'
)");
bool ret = parser;
REQUIRE(ret == false);
}
TEST_CASE("Macro calculator", "[macro]") {
// Create a PEG parser
parser parser(R"(
# Grammar for simple calculator...
EXPRESSION <- _ LIST(TERM, TERM_OPERATOR)
TERM <- LIST(FACTOR, FACTOR_OPERATOR)
FACTOR <- NUMBER / T('(') EXPRESSION T(')')
TERM_OPERATOR <- T([-+])
FACTOR_OPERATOR <- T([/*])
NUMBER <- T([0-9]+)
~_ <- [ \t]*
LIST(I, D) <- I (D I)*
T(S) <- < S > _
)");
// Setup actions
auto reduce = [](const SemanticValues &vs) {
auto result = std::any_cast<long>(vs[0]);
for (auto i = 1u; i < vs.size(); i += 2) {
auto num = std::any_cast<long>(vs[i + 1]);
auto ope = std::any_cast<char>(vs[i]);
switch (ope) {
case '+': result += num; break;
case '-': result -= num; break;
case '*': result *= num; break;
case '/': result /= num; break;
}
}
return result;
};
parser["EXPRESSION"] = reduce;
parser["TERM"] = reduce;
parser["TERM_OPERATOR"] = [](const SemanticValues &vs) {
return static_cast<char>(*vs.sv().data());
};
parser["FACTOR_OPERATOR"] = [](const SemanticValues &vs) {
return static_cast<char>(*vs.sv().data());
};
parser["NUMBER"] = [](const SemanticValues &vs) { return vs.token_to_number<long>(); };
bool ret = parser;
REQUIRE(ret == true);
auto expr = " 1 + 2 * 3 * (4 - 5 + 6) / 7 - 8 ";
long val = 0;
ret = parser.parse(expr, val);
REQUIRE(ret == true);
REQUIRE(val == -3);
}
TEST_CASE("Macro expression arguments", "[macro]") {
parser parser(R"(
S <- M('hello' / 'Hello', 'world' / 'World')
M(arg0, arg1) <- arg0 [ \t]+ arg1
)");
REQUIRE(parser.parse("Hello world"));
}
TEST_CASE("Macro recursive", "[macro]") {
parser parser(R"(
S <- M('abc')
M(s) <- !s / s ' ' M(s / '123') / s
)");
REQUIRE(parser.parse(""));
REQUIRE(parser.parse("abc"));
REQUIRE(parser.parse("abc abc"));
REQUIRE(parser.parse("abc 123 abc"));
}
TEST_CASE("Macro recursive2", "[macro]") {
auto syntaxes = std::vector<const char *>{
"S <- M('abc') M(s) <- !s / s ' ' M(s* '-' '123') / s",
"S <- M('abc') M(s) <- !s / s ' ' M(s+ '-' '123') / s",
"S <- M('abc') M(s) <- !s / s ' ' M(s? '-' '123') / s",
"S <- M('abc') M(s) <- !s / s ' ' M(&s s+ '-' '123') / s",
"S <- M('abc') M(s) <- !s / s ' ' M(s '-' !s '123') / s",
"S <- M('abc') M(s) <- !s / s ' ' M(< s > '-' '123') / s",
"S <- M('abc') M(s) <- !s / s ' ' M(~s '-' '123') / s",
};
for (const auto &syntax : syntaxes) {
parser parser(syntax);
REQUIRE(parser.parse("abc abc-123"));
}
}
TEST_CASE("Macro exclusive modifiers", "[macro]") {
parser parser(R"(
S <- Modifiers(!"") _
Modifiers(Appeared) <- (!Appeared) (
Token('public') Modifiers(Appeared / 'public') /
Token('static') Modifiers(Appeared / 'static') /
Token('final') Modifiers(Appeared / 'final') /
"")
Token(t) <- t _
_ <- [ \t\r\n]*
)");
REQUIRE(parser.parse("public"));
REQUIRE(parser.parse("static"));
REQUIRE(parser.parse("final"));
REQUIRE(parser.parse("public static final"));
REQUIRE(!parser.parse("public public"));
REQUIRE(!parser.parse("public static public"));
}
TEST_CASE("Macro token check test", "[macro]") {
parser parser(R"(
# Grammar for simple calculator...
EXPRESSION <- _ LIST(TERM, TERM_OPERATOR)
TERM <- LIST(FACTOR, FACTOR_OPERATOR)
FACTOR <- NUMBER / T('(') EXPRESSION T(')')
TERM_OPERATOR <- T([-+])
FACTOR_OPERATOR <- T([/*])
NUMBER <- T([0-9]+)
~_ <- [ \t]*
LIST(I, D) <- I (D I)*
T(S) <- < S > _
)");
REQUIRE(parser["EXPRESSION"].is_token() == false);
REQUIRE(parser["TERM"].is_token() == false);
REQUIRE(parser["FACTOR"].is_token() == false);
REQUIRE(parser["FACTOR_OPERATOR"].is_token() == true);
REQUIRE(parser["NUMBER"].is_token() == true);
REQUIRE(parser["_"].is_token() == true);
REQUIRE(parser["LIST"].is_token() == false);
REQUIRE(parser["T"].is_token() == true);
}
TEST_CASE("Macro passes an arg to another macro", "[macro]") {
parser parser(R"(
A <- B(C)
B(D) <- D
C <- 'c'
D <- 'd'
)");
REQUIRE(parser.parse("c"));
}
TEST_CASE("Nested macro call", "[macro]") {
parser parser(R"(
A <- B(T)
B(X) <- C(X)
C(Y) <- Y
T <- 'val'
)");
REQUIRE(parser.parse("val"));
}
TEST_CASE("Nested macro call2", "[macro]") {
parser parser(R"(
START <- A('TestVal1', 'TestVal2')+
A(Aarg1, Aarg2) <- B(Aarg1) '#End'
B(Barg1) <- '#' Barg1
)");
REQUIRE(parser.parse("#TestVal1#End"));
}
TEST_CASE("Line information test", "[line information]") {
parser parser(R"(
S <- _ (WORD _)+
WORD <- [A-Za-z]+
~_ <- [ \t\r\n]+
)");
std::vector<std::pair<size_t, size_t>> locations;
parser["WORD"] = [&](const peg::SemanticValues &vs) {
locations.push_back(vs.line_info());
};
bool ret = parser;
REQUIRE(ret == true);
ret = parser.parse(" Mon Tue Wed \nThu Fri Sat\nSun\n");
REQUIRE(ret == true);
REQUIRE(locations[0] == std::make_pair<size_t, size_t>(1, 2));
REQUIRE(locations[1] == std::make_pair<size_t, size_t>(1, 6));
REQUIRE(locations[2] == std::make_pair<size_t, size_t>(1, 10));
REQUIRE(locations[3] == std::make_pair<size_t, size_t>(2, 1));
REQUIRE(locations[4] == std::make_pair<size_t, size_t>(2, 6));
REQUIRE(locations[5] == std::make_pair<size_t, size_t>(2, 11));
REQUIRE(locations[6] == std::make_pair<size_t, size_t>(3, 1));
}
TEST_CASE("Dictionary", "[dic]") {
parser parser(R"(
START <- 'This month is ' MONTH '.'
MONTH <- 'Jan' | 'January' | 'Feb' | 'February'
)");
REQUIRE(parser.parse("This month is Jan."));
REQUIRE(parser.parse("This month is January."));
REQUIRE_FALSE(parser.parse("This month is Jannuary."));
REQUIRE_FALSE(parser.parse("This month is ."));
}
TEST_CASE("Dictionary invalid", "[dic]") {
parser parser(R"(
START <- 'This month is ' MONTH '.'
MONTH <- 'Jan' | 'January' | [a-z]+ | 'Feb' | 'February'
)");
bool ret = parser;
REQUIRE_FALSE(ret);
}
TEST_CASE("Error recovery 1", "[error]") {
parser pg(R"(
START <- __? SECTION*
SECTION <- HEADER __ ENTRIES __?
HEADER <- '[' _ CATEGORY (':' _ ATTRIBUTES)? ']'^header
CATEGORY <- < [-_a-zA-Z0-9\u0080-\uFFFF ]+ > _
ATTRIBUTES <- ATTRIBUTE (',' _ ATTRIBUTE)*
ATTRIBUTE <- < [-_a-zA-Z0-9\u0080-\uFFFF]+ > _
ENTRIES <- (ENTRY (__ ENTRY)*)? { no_ast_opt }
ENTRY <- ONE_WAY PHRASE ('|' _ PHRASE)* !'='
/ PHRASE ('|' _ PHRASE)+ !'='
/ %recover(entry)
ONE_WAY <- PHRASE '=' _
PHRASE <- WORD (' ' WORD)* _
WORD <- < (![ \t\r\n=|[\]#] .)+ >
~__ <- _ (comment? nl _)+
~_ <- [ \t]*
comment <- ('#' (!nl .)*)
nl <- '\r'? '\n'
header <- (!__ .)* { message "invalid section header, missing ']'." }
entry <- (!(__ / HEADER) .)+ { message "invalid entry." }
)");
REQUIRE(!!pg); // OK
std::vector<std::string> errors{
R"(3:1: invalid entry.)",
R"(7:1: invalid entry.)",
R"(10:11: invalid section header, missing ']'.)",
R"(18:1: invalid entry.)",
};
size_t i = 0;
pg.log = [&](size_t ln, size_t col, const std::string &msg) {
std::stringstream ss;
ss << ln << ":" << col << ": " << msg;
REQUIRE(ss.str() == errors[i++]);
};
pg.enable_ast();
std::shared_ptr<Ast> ast;
REQUIRE_FALSE(pg.parse(R"([Section 1]
111 = 222 | 333
aaa || bbb
ccc = ddd
[Section 2]
eee
fff | ggg
[Section 3
hhh | iii
[Section 日本語]
ppp | qqq
[Section 4]
jjj | kkk
lll = mmm | nnn = ooo
[Section 5]
rrr | sss
)", ast));
ast = pg.optimize_ast(ast);
REQUIRE(ast_to_s(ast) ==
R"(+ START
+ SECTION
- HEADER/0[CATEGORY] (Section 1)
+ ENTRIES
+ ENTRY/0
- ONE_WAY/0[WORD] (111)
- PHRASE/0[WORD] (222)
- PHRASE/0[WORD] (333)
+ ENTRY/2
+ ENTRY/0
- ONE_WAY/0[WORD] (ccc)
- PHRASE/0[WORD] (ddd)
+ SECTION
- HEADER/0[CATEGORY] (Section 2)
+ ENTRIES
+ ENTRY/2
+ ENTRY/1
- PHRASE/0[WORD] (fff)
- PHRASE/0[WORD] (ggg)
+ SECTION
- HEADER/0[CATEGORY] (Section 3)
+ ENTRIES
+ ENTRY/1
- PHRASE/0[WORD] (hhh)
- PHRASE/0[WORD] (iii)
+ SECTION
- HEADER/0[CATEGORY] (Section 日本語)
+ ENTRIES
+ ENTRY/1
- PHRASE/0[WORD] (ppp)
- PHRASE/0[WORD] (qqq)
+ SECTION
- HEADER/0[CATEGORY] (Section 4)
+ ENTRIES
+ ENTRY/1
- PHRASE/0[WORD] (jjj)
- PHRASE/0[WORD] (kkk)
+ ENTRY/2
+ SECTION
- HEADER/0[CATEGORY] (Section 5)
+ ENTRIES
+ ENTRY/1
- PHRASE/0[WORD] (rrr)
- PHRASE/0[WORD] (sss)
)");
}
TEST_CASE("Error recovery 2", "[error]") {
parser pg(R"(
START <- ENTRY ((',' ENTRY) / %recover((!(',' / Space) .)+))* (_ / %recover(.*))
ENTRY <- '[' ITEM (',' ITEM)* ']'
ITEM <- WORD / NUM / %recover((!(',' / ']') .)+)
NUM <- [0-9]+ ![a-z]
WORD <- '"' [a-z]+ '"'
~_ <- Space+
Space <- [ \n]
)");
REQUIRE(!!pg); // OK
std::vector<std::string> errors{
R"(1:6: syntax error, unexpected ']'.)",
R"(1:18: syntax error, unexpected 'z', expecting <NUM>.)",
R"(1:24: syntax error, unexpected ',', expecting <WORD>.)",
R"(1:31: syntax error, unexpected 'ccc', expecting <NUM>.)",
R"(1:38: syntax error, unexpected 'ddd', expecting <NUM>.)",
R"(1:55: syntax error, unexpected ']', expecting <WORD>.)",
R"(1:58: syntax error, unexpected '\n', expecting <NUM>.)",
R"(2:3: syntax error.)",
};
size_t i = 0;
pg.log = [&](size_t ln, size_t col, const std::string &msg) {
std::stringstream ss;
ss << ln << ":" << col << ": " << msg;
REQUIRE(ss.str() == errors[i++]);
};
pg.enable_ast();
std::shared_ptr<Ast> ast;
REQUIRE_FALSE(pg.parse(R"([000]],[111],[222z,"aaa,"bbb",ccc"],[ddd",444,555,"eee],[
)", ast));
ast = pg.optimize_ast(ast);
REQUIRE(ast_to_s(ast) ==
R"(+ START
- ENTRY/0[NUM] (000)
- ENTRY/0[NUM] (111)
+ ENTRY
+ ITEM/2
+ ITEM/2
- ITEM/0[WORD] ("bbb")
+ ITEM/2
+ ENTRY
+ ITEM/2
- ITEM/1[NUM] (444)
- ITEM/1[NUM] (555)
+ ITEM/2
)");
}
TEST_CASE("Error recovery 3", "[error]") {
parser pg(R"~(
# Grammar
START <- __? SECTION*
SECTION <- HEADER __ ENTRIES __?
HEADER <- '['^missing_bracket _ CATEGORY (':' _ ATTRIBUTES)? ']'^missing_bracket ___
CATEGORY <- < (&[-_a-zA-Z0-9\u0080-\uFFFF ] (![\u0080-\uFFFF])^vernacular_char .)+ > _
ATTRIBUTES <- ATTRIBUTE (',' _ ATTRIBUTE)*
ATTRIBUTE <- < [-_a-zA-Z0-9]+ > _
ENTRIES <- (ENTRY (__ ENTRY)*)? { no_ast_opt }
ENTRY <- ONE_WAY PHRASE^expect_phrase (or _ PHRASE^expect_phrase)* ___
/ PHRASE (or^missing_or _ PHRASE^expect_phrase) (or _ PHRASE^expect_phrase)* ___ { no_ast_opt }
ONE_WAY <- PHRASE assign _
PHRASE <- WORD (' ' WORD)* _ { no_ast_opt }
WORD <- < (![ \t\r\n=|[\]#] (![*?] / %recover(wildcard)) .)+ >
~assign <- '=' ____
~or <- '|' (!'|')^duplicate_or ____
~_ <- [ \t]*
~__ <- _ (comment? nl _)+
~___ <- (!operators)^invalid_ope
~____ <- (!operators)^invalid_ope_comb
operators <- [|=]+
comment <- ('#' (!nl .)*)
nl <- '\r'? '\n'
# Recovery
duplicate_or <- skip_puncs { message "Duplicate OR operator (|)" }
missing_or <- '' { message "Missing OR operator (|)" }
missing_bracket <- skip_puncs { message "Missing opening/closing square bracket" }
expect_phrase <- skip { message "Expect phrase" }
invalid_ope_comb <- skip_puncs { message "Use of invalid operator combination" }
invalid_ope <- skip { message "Use of invalid operator" }
wildcard <- '' { message "Wildcard characters (%c) should not be used" }
vernacular_char <- '' { message "Section name %c must be in English" }
skip <- (!(__) .)*
skip_puncs <- [|=]* _
)~");
REQUIRE(!!pg); // OK
std::vector<std::string> errors{
R"(3:7: Wildcard characters (*) should not be used)",
R"(4:6: Wildcard characters (?) should not be used)",
R"(5:6: Duplicate OR operator (|))",
R"(9:4: Missing OR operator (|))",
R"(11:16: Expect phrase)",
R"(13:11: Missing opening/closing square bracket)",
R"(16:10: Section name 日 must be in English)",
R"(16:11: Section name 本 must be in English)",
R"(16:12: Section name 語 must be in English)",
R"(16:13: Section name で must be in English)",
R"(16:14: Section name す must be in English)",
R"(21:17: Use of invalid operator)",
R"(24:10: Use of invalid operator combination)",
R"(26:10: Missing OR operator (|))",
};
size_t i = 0;
pg.log = [&](size_t ln, size_t col, const std::string &msg) {
std::stringstream ss;
ss << ln << ":" << col << ": " << msg;
REQUIRE(ss.str() == errors[i++]);
};
pg.enable_ast();
std::shared_ptr<Ast> ast;
REQUIRE_FALSE(pg.parse(R"([Section 1]
111 = 222 | 333
AAA BB* | CCC
AAA B?B | CCC
aaa || bbb
ccc = ddd
[Section 2]
eee
fff | ggg
fff | ggg 111 |
[Section 3
hhh | iii
[Section 日本語です]
ppp | qqq
[Section 4]
jjj | kkk
lll = mmm | nnn = ooo
[Section 5]
ppp qqq |= rrr
Section 6]
sss | ttt
)", ast));
ast = pg.optimize_ast(ast);
REQUIRE(ast_to_s(ast) ==
R"(+ START
+ SECTION
- HEADER/0[CATEGORY] (Section 1)
+ ENTRIES
+ ENTRY/0
+ ONE_WAY/0[PHRASE]
- WORD (111)
+ PHRASE
- WORD (222)
+ PHRASE
- WORD (333)
+ ENTRY/1
+ PHRASE
- WORD (AAA)
- WORD (BB*)
+ PHRASE
- WORD (CCC)
+ ENTRY/1
+ PHRASE
- WORD (AAA)
- WORD (B?B)
+ PHRASE
- WORD (CCC)
+ ENTRY/1
+ PHRASE
- WORD (aaa)
+ PHRASE
- WORD (bbb)
+ ENTRY/0
+ ONE_WAY/0[PHRASE]
- WORD (ccc)
+ PHRASE
- WORD (ddd)
+ SECTION
- HEADER/0[CATEGORY] (Section 2)
+ ENTRIES
+ ENTRY/1
+ PHRASE
- WORD (eee)
+ ENTRY/1
+ PHRASE
- WORD (fff)
+ PHRASE
- WORD (ggg)
+ ENTRY/1
+ PHRASE
- WORD (fff)
+ PHRASE
- WORD (ggg)
- WORD (111)
+ SECTION
- HEADER/0[CATEGORY] (Section 3)
+ ENTRIES
+ ENTRY/1
+ PHRASE
- WORD (hhh)
+ PHRASE
- WORD (iii)
+ SECTION
- HEADER/0[CATEGORY] (Section 日本語です)
+ ENTRIES
+ ENTRY/1
+ PHRASE
- WORD (ppp)
+ PHRASE
- WORD (qqq)
+ SECTION
- HEADER/0[CATEGORY] (Section 4)
+ ENTRIES
+ ENTRY/1
+ PHRASE
- WORD (jjj)
+ PHRASE
- WORD (kkk)
+ ENTRY/0
+ ONE_WAY/0[PHRASE]
- WORD (lll)
+ PHRASE
- WORD (mmm)
+ PHRASE
- WORD (nnn)
+ SECTION
- HEADER/0[CATEGORY] (Section 5)
+ ENTRIES
+ ENTRY/1
+ PHRASE
- WORD (ppp)
- WORD (qqq)
+ PHRASE
- WORD (rrr)
+ ENTRY/1
+ PHRASE
- WORD (Section)
- WORD (6)
+ ENTRY/1
+ PHRASE
- WORD (sss)
+ PHRASE
- WORD (ttt)
)");
}
TEST_CASE("Error recovery Java", "[error]") {
parser pg(R"(
Prog ← PUBLIC CLASS NAME LCUR PUBLIC STATIC VOID MAIN LPAR STRING LBRA RBRA NAME RPAR BlockStmt RCUR
BlockStmt ← LCUR (Stmt)* RCUR^rcblk
Stmt ← IfStmt / WhileStmt / PrintStmt / DecStmt / AssignStmt / BlockStmt
IfStmt ← IF LPAR Exp RPAR Stmt (ELSE Stmt)?
WhileStmt ← WHILE LPAR Exp RPAR Stmt
DecStmt ← INT NAME (ASSIGN Exp)? SEMI
AssignStmt ← NAME ASSIGN Exp SEMI^semia
PrintStmt ← PRINTLN LPAR Exp RPAR SEMI
Exp ← RelExp (EQ RelExp)*
RelExp ← AddExp (LT AddExp)*
AddExp ← MulExp ((PLUS / MINUS) MulExp)*
MulExp ← AtomExp ((TIMES / DIV) AtomExp)*
AtomExp ← LPAR Exp RPAR / NUMBER / NAME
NUMBER ← < [0-9]+ >
NAME ← < [a-zA-Z_][a-zA-Z_0-9]* >
~LPAR ← '('
~RPAR ← ')'
~LCUR ← '{'
~RCUR ← '}'
~LBRA ← '['
~RBRA ← ']'
~SEMI ← ';'
~EQ ← '=='
~LT ← '<'
~ASSIGN ← '='
~IF ← 'if'
~ELSE ← 'else'
~WHILE ← 'while'
PLUS ← '+'
MINUS ← '-'
TIMES ← '*'
DIV ← '/'
CLASS ← 'class'
PUBLIC ← 'public'
STATIC ← 'static'
VOID ← 'void'
INT ← 'int'
MAIN ← 'main'
STRING ← 'String'
PRINTLN ← 'System.out.println'
%whitespace ← [ \t\n]*
%word ← NAME
# Throw operator labels
rcblk ← SkipToRCUR { message "missing end of block." }
semia ← '' { message "missing simicolon in assignment." }
# Recovery expressions
SkipToRCUR ← (!RCUR (LCUR SkipToRCUR / .))* RCUR
)");
REQUIRE(!!pg); // OK
std::vector<std::string> errors{
R"(8:5: missing simicolon in assignment.)",
R"(8:6: missing end of block.)",
};
size_t i = 0;
pg.log = [&](size_t ln, size_t col, const std::string &msg) {
std::stringstream ss;
ss << ln << ":" << col << ": " << msg;
REQUIRE(ss.str() == errors[i++]);
};
pg.enable_ast();
std::shared_ptr<Ast> ast;
REQUIRE_FALSE(pg.parse(R"(public class Example {
public static void main(String[] args) {
int n = 5;
int f = 1;
while(0 < n) {
f = f * n;
n = n - 1
};
System.out.println(f);
}
}
)", ast));
ast = pg.optimize_ast(ast);
REQUIRE(ast_to_s(ast) ==
R"(+ Prog
- PUBLIC (public)
- CLASS (class)
- NAME (Example)
- PUBLIC (public)
- STATIC (static)
- VOID (void)
- MAIN (main)
- STRING (String)
- NAME (args)
+ BlockStmt
+ Stmt/3[DecStmt]
- INT (int)
- NAME (n)
- Exp/0[NUMBER] (5)
+ Stmt/3[DecStmt]
- INT (int)
- NAME (f)
- Exp/0[NUMBER] (1)
+ Stmt/1[WhileStmt]
+ Exp/0[RelExp]
- AddExp/0[NUMBER] (0)
- AddExp/0[NAME] (n)
+ Stmt/5[BlockStmt]
+ Stmt/4[AssignStmt]
- NAME (f)
+ Exp/0[MulExp]
- AtomExp/2[NAME] (f)
- TIMES (*)
- AtomExp/2[NAME] (n)
+ Stmt/4[AssignStmt]
- NAME (n)
+ Exp/0[AddExp]
- MulExp/0[NAME] (n)
- MINUS (-)
- MulExp/0[NUMBER] (1)
)");
}
| [
"yuji.hirose.bug@gmail.com"
] | yuji.hirose.bug@gmail.com |
d873f522d8c8cb504040f47b036b9e316f1b94d9 | 1afac375e35c837d00178793f8f3f6019d3e7fad | /src/L_PhysicsList.cpp | b4450ba4f741fc02089522b15ed6232fb28a05c0 | [] | no_license | Vlad-Orlov/Plume | 6f79403d3ff73535235e1de4b4110f7ec5cfb26e | 18994af57a81977853fd3b6e455dbd5cf3443642 | refs/heads/main | 2023-05-31T21:22:50.623674 | 2021-07-07T08:13:46 | 2021-07-07T08:13:46 | 383,718,608 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,259 | cpp | #include "L_PhysicsList.h"
// Physics list constructor inherited from QGSP_BERT
L_PhysicsList::L_PhysicsList() : QGSP_BERT()
{
theCerenkovProcess = 0;
defaultCutValue = 1.0*mm;
SetVerboseLevel(0);
G4cout << "Physics list constructor" << G4endl;
}
L_PhysicsList::~L_PhysicsList()
{
delete theCerenkovProcess;
}
void L_PhysicsList::ConstructParticle()
{
// Constructing HEP particles from base physics list
// and adding OpticalPhoton to them
QGSP_BERT::ConstructParticle();
G4OpticalPhoton::OpticalPhotonDefinition();
}
void L_PhysicsList::ConstructProcess()
{
// Constructing processes from base physics list and adding
// Cherenkov process and optical processes
QGSP_BERT::ConstructProcess();
ConstructOp();
}
//void SetCuts();
void L_PhysicsList::ConstructOp()
{
G4ParticleTable::G4PTblDicIterator *theParticleIterator = GetParticleIterator();
G4cout<<" 000 "<<G4endl;
// Optical Photon Processes
theCerenkovProcess = new G4Cerenkov("Cerenkov");
G4cout<<" 111 "<<G4endl;
SetVerbose(0);
theCerenkovProcess->SetMaxNumPhotonsPerStep(300);
theCerenkovProcess->SetTrackSecondariesFirst(true);
G4cout<<" 111 "<<G4endl;
theParticleIterator->reset();
while( (*theParticleIterator)() ) {
G4ParticleDefinition* particle = theParticleIterator->value();
G4ProcessManager* pmanager = particle->GetProcessManager();
G4String particleName = particle->GetParticleName();
if (theCerenkovProcess->IsApplicable(*particle)) {
G4cout << "Add Cerenkov process to " << particleName << G4endl;
pmanager->AddProcess(theCerenkovProcess);
pmanager->SetProcessOrdering(theCerenkovProcess, idxPostStep);
}
if (particleName == "opticalphoton") {
G4cout << " AddDiscreteProcess to OpticalPhoton " << G4endl;
pmanager->AddDiscreteProcess(new G4OpAbsorption());
pmanager->AddDiscreteProcess(new G4OpRayleigh());
pmanager->AddDiscreteProcess(new G4OpBoundaryProcess());
}
}
G4cout << "Optics constructed" << G4endl;
}
void L_PhysicsList::SetVerbose(G4int verbose)
{
theCerenkovProcess->SetVerboseLevel(verbose);
}
| [
"orlov.vlad.serg@gmail.com"
] | orlov.vlad.serg@gmail.com |
e60402227231452f1705a5e9944910ec48b73580 | e2d932210803c9243b4e3798c5edcab464a6a5b1 | /CustomMovieRenderPipeline/Intermediate/Build/Win64/UE4Editor/Inc/MovieRenderPipelineCore/MoviePipelineQueue.gen.cpp | 4613b268b7f7e3ac68c64698de99b66d7ca64471 | [] | no_license | hiteshsathawane/CustomUnrealMovieRenderQueue | f0b118b58d8b2ea09ee3c80dd318331861ae85f1 | 28753f698de6c79f108bc11b50f5c3472678a483 | refs/heads/master | 2022-12-09T13:48:20.199787 | 2020-09-11T03:32:50 | 2020-09-11T03:32:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 50,779 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "MovieRenderPipelineCore/Public/MoviePipelineQueue.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeMoviePipelineQueue() {}
// Cross Module References
MOVIERENDERPIPELINECORE_API UEnum* Z_Construct_UEnum_MovieRenderPipelineCore_EMoviePipelineExecutorJobStatus();
UPackage* Z_Construct_UPackage__Script_MovieRenderPipelineCore();
MOVIERENDERPIPELINECORE_API UClass* Z_Construct_UClass_UMoviePipelineExecutorJob_NoRegister();
MOVIERENDERPIPELINECORE_API UClass* Z_Construct_UClass_UMoviePipelineExecutorJob();
COREUOBJECT_API UClass* Z_Construct_UClass_UObject();
MOVIERENDERPIPELINECORE_API UClass* Z_Construct_UClass_UMoviePipelineMasterConfig_NoRegister();
LEVELSEQUENCE_API UClass* Z_Construct_UClass_ULevelSequence_NoRegister();
COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FSoftObjectPath();
MOVIERENDERPIPELINECORE_API UClass* Z_Construct_UClass_UMoviePipelineQueue_NoRegister();
MOVIERENDERPIPELINECORE_API UClass* Z_Construct_UClass_UMoviePipelineQueue();
// End Cross Module References
static UEnum* EMoviePipelineExecutorJobStatus_StaticEnum()
{
static UEnum* Singleton = nullptr;
if (!Singleton)
{
Singleton = GetStaticEnum(Z_Construct_UEnum_MovieRenderPipelineCore_EMoviePipelineExecutorJobStatus, Z_Construct_UPackage__Script_MovieRenderPipelineCore(), TEXT("EMoviePipelineExecutorJobStatus"));
}
return Singleton;
}
template<> MOVIERENDERPIPELINECORE_API UEnum* StaticEnum<EMoviePipelineExecutorJobStatus>()
{
return EMoviePipelineExecutorJobStatus_StaticEnum();
}
static FCompiledInDeferEnum Z_CompiledInDeferEnum_UEnum_EMoviePipelineExecutorJobStatus(EMoviePipelineExecutorJobStatus_StaticEnum, TEXT("/Script/MovieRenderPipelineCore"), TEXT("EMoviePipelineExecutorJobStatus"), false, nullptr, nullptr);
uint32 Get_Z_Construct_UEnum_MovieRenderPipelineCore_EMoviePipelineExecutorJobStatus_Hash() { return 3527694630U; }
UEnum* Z_Construct_UEnum_MovieRenderPipelineCore_EMoviePipelineExecutorJobStatus()
{
#if WITH_HOT_RELOAD
UPackage* Outer = Z_Construct_UPackage__Script_MovieRenderPipelineCore();
static UEnum* ReturnEnum = FindExistingEnumIfHotReloadOrDynamic(Outer, TEXT("EMoviePipelineExecutorJobStatus"), 0, Get_Z_Construct_UEnum_MovieRenderPipelineCore_EMoviePipelineExecutorJobStatus_Hash(), false);
#else
static UEnum* ReturnEnum = nullptr;
#endif // WITH_HOT_RELOAD
if (!ReturnEnum)
{
static const UE4CodeGen_Private::FEnumeratorParam Enumerators[] = {
{ "EMoviePipelineExecutorJobStatus::Uninitialized", (int64)EMoviePipelineExecutorJobStatus::Uninitialized },
{ "EMoviePipelineExecutorJobStatus::ReadyToStart", (int64)EMoviePipelineExecutorJobStatus::ReadyToStart },
{ "EMoviePipelineExecutorJobStatus::InProgress", (int64)EMoviePipelineExecutorJobStatus::InProgress },
{ "EMoviePipelineExecutorJobStatus::Finished", (int64)EMoviePipelineExecutorJobStatus::Finished },
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Enum_MetaDataParams[] = {
{ "BlueprintType", "true" },
{ "Finished.Name", "EMoviePipelineExecutorJobStatus::Finished" },
{ "InProgress.Name", "EMoviePipelineExecutorJobStatus::InProgress" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
{ "ReadyToStart.Name", "EMoviePipelineExecutorJobStatus::ReadyToStart" },
{ "Uninitialized.Name", "EMoviePipelineExecutorJobStatus::Uninitialized" },
};
#endif
static const UE4CodeGen_Private::FEnumParams EnumParams = {
(UObject*(*)())Z_Construct_UPackage__Script_MovieRenderPipelineCore,
nullptr,
"EMoviePipelineExecutorJobStatus",
"EMoviePipelineExecutorJobStatus",
Enumerators,
UE_ARRAY_COUNT(Enumerators),
RF_Public|RF_Transient|RF_MarkAsNative,
UE4CodeGen_Private::EDynamicType::NotDynamic,
(uint8)UEnum::ECppForm::EnumClass,
METADATA_PARAMS(Enum_MetaDataParams, UE_ARRAY_COUNT(Enum_MetaDataParams))
};
UE4CodeGen_Private::ConstructUEnum(ReturnEnum, EnumParams);
}
return ReturnEnum;
}
DEFINE_FUNCTION(UMoviePipelineExecutorJob::execSetConfiguration)
{
P_GET_OBJECT(UMoviePipelineMasterConfig,Z_Param_InPreset);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->SetConfiguration(Z_Param_InPreset);
P_NATIVE_END;
}
DEFINE_FUNCTION(UMoviePipelineExecutorJob::execGetConfiguration)
{
P_FINISH;
P_NATIVE_BEGIN;
*(UMoviePipelineMasterConfig**)Z_Param__Result=P_THIS->GetConfiguration();
P_NATIVE_END;
}
DEFINE_FUNCTION(UMoviePipelineExecutorJob::execGetPresetOrigin)
{
P_FINISH;
P_NATIVE_BEGIN;
*(UMoviePipelineMasterConfig**)Z_Param__Result=P_THIS->GetPresetOrigin();
P_NATIVE_END;
}
DEFINE_FUNCTION(UMoviePipelineExecutorJob::execSetPresetOrigin)
{
P_GET_OBJECT(UMoviePipelineMasterConfig,Z_Param_InPreset);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->SetPresetOrigin(Z_Param_InPreset);
P_NATIVE_END;
}
DEFINE_FUNCTION(UMoviePipelineExecutorJob::execHasFinished)
{
P_FINISH;
P_NATIVE_BEGIN;
*(bool*)Z_Param__Result=P_THIS->HasFinished();
P_NATIVE_END;
}
void UMoviePipelineExecutorJob::StaticRegisterNativesUMoviePipelineExecutorJob()
{
UClass* Class = UMoviePipelineExecutorJob::StaticClass();
static const FNameNativePtrPair Funcs[] = {
{ "GetConfiguration", &UMoviePipelineExecutorJob::execGetConfiguration },
{ "GetPresetOrigin", &UMoviePipelineExecutorJob::execGetPresetOrigin },
{ "HasFinished", &UMoviePipelineExecutorJob::execHasFinished },
{ "SetConfiguration", &UMoviePipelineExecutorJob::execSetConfiguration },
{ "SetPresetOrigin", &UMoviePipelineExecutorJob::execSetPresetOrigin },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs));
}
struct Z_Construct_UFunction_UMoviePipelineExecutorJob_GetConfiguration_Statics
{
struct MoviePipelineExecutorJob_eventGetConfiguration_Parms
{
UMoviePipelineMasterConfig* ReturnValue;
};
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UMoviePipelineExecutorJob_GetConfiguration_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MoviePipelineExecutorJob_eventGetConfiguration_Parms, ReturnValue), Z_Construct_UClass_UMoviePipelineMasterConfig_NoRegister, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UMoviePipelineExecutorJob_GetConfiguration_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UMoviePipelineExecutorJob_GetConfiguration_Statics::NewProp_ReturnValue,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UMoviePipelineExecutorJob_GetConfiguration_Statics::Function_MetaDataParams[] = {
{ "Category", "Movie Render Pipeline" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UMoviePipelineExecutorJob_GetConfiguration_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UMoviePipelineExecutorJob, nullptr, "GetConfiguration", nullptr, nullptr, sizeof(MoviePipelineExecutorJob_eventGetConfiguration_Parms), Z_Construct_UFunction_UMoviePipelineExecutorJob_GetConfiguration_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineExecutorJob_GetConfiguration_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x54020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UMoviePipelineExecutorJob_GetConfiguration_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineExecutorJob_GetConfiguration_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UMoviePipelineExecutorJob_GetConfiguration()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UMoviePipelineExecutorJob_GetConfiguration_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UMoviePipelineExecutorJob_GetPresetOrigin_Statics
{
struct MoviePipelineExecutorJob_eventGetPresetOrigin_Parms
{
UMoviePipelineMasterConfig* ReturnValue;
};
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UMoviePipelineExecutorJob_GetPresetOrigin_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MoviePipelineExecutorJob_eventGetPresetOrigin_Parms, ReturnValue), Z_Construct_UClass_UMoviePipelineMasterConfig_NoRegister, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UMoviePipelineExecutorJob_GetPresetOrigin_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UMoviePipelineExecutorJob_GetPresetOrigin_Statics::NewProp_ReturnValue,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UMoviePipelineExecutorJob_GetPresetOrigin_Statics::Function_MetaDataParams[] = {
{ "Category", "Movie Render Pipeline" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UMoviePipelineExecutorJob_GetPresetOrigin_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UMoviePipelineExecutorJob, nullptr, "GetPresetOrigin", nullptr, nullptr, sizeof(MoviePipelineExecutorJob_eventGetPresetOrigin_Parms), Z_Construct_UFunction_UMoviePipelineExecutorJob_GetPresetOrigin_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineExecutorJob_GetPresetOrigin_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x54020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UMoviePipelineExecutorJob_GetPresetOrigin_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineExecutorJob_GetPresetOrigin_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UMoviePipelineExecutorJob_GetPresetOrigin()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UMoviePipelineExecutorJob_GetPresetOrigin_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished_Statics
{
struct MoviePipelineExecutorJob_eventHasFinished_Parms
{
bool ReturnValue;
};
static void NewProp_ReturnValue_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
void Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished_Statics::NewProp_ReturnValue_SetBit(void* Obj)
{
((MoviePipelineExecutorJob_eventHasFinished_Parms*)Obj)->ReturnValue = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(MoviePipelineExecutorJob_eventHasFinished_Parms), &Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished_Statics::NewProp_ReturnValue_SetBit, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished_Statics::NewProp_ReturnValue,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished_Statics::Function_MetaDataParams[] = {
{ "Category", "Movie Render Pipeline" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UMoviePipelineExecutorJob, nullptr, "HasFinished", nullptr, nullptr, sizeof(MoviePipelineExecutorJob_eventHasFinished_Parms), Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x54020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UMoviePipelineExecutorJob_SetConfiguration_Statics
{
struct MoviePipelineExecutorJob_eventSetConfiguration_Parms
{
UMoviePipelineMasterConfig* InPreset;
};
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_InPreset;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UMoviePipelineExecutorJob_SetConfiguration_Statics::NewProp_InPreset = { "InPreset", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MoviePipelineExecutorJob_eventSetConfiguration_Parms, InPreset), Z_Construct_UClass_UMoviePipelineMasterConfig_NoRegister, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UMoviePipelineExecutorJob_SetConfiguration_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UMoviePipelineExecutorJob_SetConfiguration_Statics::NewProp_InPreset,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UMoviePipelineExecutorJob_SetConfiguration_Statics::Function_MetaDataParams[] = {
{ "Category", "Movie Render Pipeline" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UMoviePipelineExecutorJob_SetConfiguration_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UMoviePipelineExecutorJob, nullptr, "SetConfiguration", nullptr, nullptr, sizeof(MoviePipelineExecutorJob_eventSetConfiguration_Parms), Z_Construct_UFunction_UMoviePipelineExecutorJob_SetConfiguration_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineExecutorJob_SetConfiguration_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UMoviePipelineExecutorJob_SetConfiguration_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineExecutorJob_SetConfiguration_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UMoviePipelineExecutorJob_SetConfiguration()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UMoviePipelineExecutorJob_SetConfiguration_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UMoviePipelineExecutorJob_SetPresetOrigin_Statics
{
struct MoviePipelineExecutorJob_eventSetPresetOrigin_Parms
{
UMoviePipelineMasterConfig* InPreset;
};
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_InPreset;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UMoviePipelineExecutorJob_SetPresetOrigin_Statics::NewProp_InPreset = { "InPreset", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MoviePipelineExecutorJob_eventSetPresetOrigin_Parms, InPreset), Z_Construct_UClass_UMoviePipelineMasterConfig_NoRegister, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UMoviePipelineExecutorJob_SetPresetOrigin_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UMoviePipelineExecutorJob_SetPresetOrigin_Statics::NewProp_InPreset,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UMoviePipelineExecutorJob_SetPresetOrigin_Statics::Function_MetaDataParams[] = {
{ "Category", "Movie Render Pipeline" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UMoviePipelineExecutorJob_SetPresetOrigin_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UMoviePipelineExecutorJob, nullptr, "SetPresetOrigin", nullptr, nullptr, sizeof(MoviePipelineExecutorJob_eventSetPresetOrigin_Parms), Z_Construct_UFunction_UMoviePipelineExecutorJob_SetPresetOrigin_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineExecutorJob_SetPresetOrigin_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UMoviePipelineExecutorJob_SetPresetOrigin_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineExecutorJob_SetPresetOrigin_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UMoviePipelineExecutorJob_SetPresetOrigin()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UMoviePipelineExecutorJob_SetPresetOrigin_Statics::FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_UMoviePipelineExecutorJob_NoRegister()
{
return UMoviePipelineExecutorJob::StaticClass();
}
struct Z_Construct_UClass_UMoviePipelineExecutorJob_Statics
{
static UObject* (*const DependentSingletons[])();
static const FClassFunctionLinkInfo FuncInfo[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_LoadedSequence_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_LoadedSequence;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_PresetOrigin_MetaData[];
#endif
static const UE4CodeGen_Private::FSoftObjectPropertyParams NewProp_PresetOrigin;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Configuration_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Configuration;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Author_MetaData[];
#endif
static const UE4CodeGen_Private::FTextPropertyParams NewProp_Author;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_JobStatus_MetaData[];
#endif
static const UE4CodeGen_Private::FEnumPropertyParams NewProp_JobStatus;
static const UE4CodeGen_Private::FBytePropertyParams NewProp_JobStatus_Underlying;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Map_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_Map;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Sequence_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_Sequence;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_UObject,
(UObject* (*)())Z_Construct_UPackage__Script_MovieRenderPipelineCore,
};
const FClassFunctionLinkInfo Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::FuncInfo[] = {
{ &Z_Construct_UFunction_UMoviePipelineExecutorJob_GetConfiguration, "GetConfiguration" }, // 1382933140
{ &Z_Construct_UFunction_UMoviePipelineExecutorJob_GetPresetOrigin, "GetPresetOrigin" }, // 2226006382
{ &Z_Construct_UFunction_UMoviePipelineExecutorJob_HasFinished, "HasFinished" }, // 2505788580
{ &Z_Construct_UFunction_UMoviePipelineExecutorJob_SetConfiguration, "SetConfiguration" }, // 2108840216
{ &Z_Construct_UFunction_UMoviePipelineExecutorJob_SetPresetOrigin, "SetPresetOrigin" }, // 1257071995
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::Class_MetaDataParams[] = {
{ "BlueprintType", "true" },
{ "Comment", "/**\n* A particular job within the Queue\n*/" },
{ "IncludePath", "MoviePipelineQueue.h" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
{ "ToolTip", "A particular job within the Queue" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_LoadedSequence_MetaData[] = {
{ "Comment", "/** Cache our loaded sequence after the first time someone tries to retrieve information from this job that requires the Sequence. */" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
{ "ToolTip", "Cache our loaded sequence after the first time someone tries to retrieve information from this job that requires the Sequence." },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_LoadedSequence = { "LoadedSequence", nullptr, (EPropertyFlags)0x0040000000002000, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMoviePipelineExecutorJob, LoadedSequence), Z_Construct_UClass_ULevelSequence_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_LoadedSequence_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_LoadedSequence_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_PresetOrigin_MetaData[] = {
{ "Comment", "/**\n\x09*/" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
};
#endif
const UE4CodeGen_Private::FSoftObjectPropertyParams Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_PresetOrigin = { "PresetOrigin", nullptr, (EPropertyFlags)0x0044000000000000, UE4CodeGen_Private::EPropertyGenFlags::SoftObject, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMoviePipelineExecutorJob, PresetOrigin), Z_Construct_UClass_UMoviePipelineMasterConfig_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_PresetOrigin_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_PresetOrigin_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Configuration_MetaData[] = {
{ "Comment", "/** \n\x09*/" },
{ "EditInline", "true" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Configuration = { "Configuration", nullptr, (EPropertyFlags)0x0042000000080008, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMoviePipelineExecutorJob, Configuration), Z_Construct_UClass_UMoviePipelineMasterConfig_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Configuration_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Configuration_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Author_MetaData[] = {
{ "Category", "Movie Render Pipeline" },
{ "Comment", "/** (Optional) Name of the person who submitted the job. Can be shown in burn in as a first point of contact about the content. */" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
{ "ToolTip", "(Optional) Name of the person who submitted the job. Can be shown in burn in as a first point of contact about the content." },
};
#endif
const UE4CodeGen_Private::FTextPropertyParams Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Author = { "Author", nullptr, (EPropertyFlags)0x0010000000000004, UE4CodeGen_Private::EPropertyGenFlags::Text, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMoviePipelineExecutorJob, Author), METADATA_PARAMS(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Author_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Author_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_JobStatus_MetaData[] = {
{ "Category", "Movie Render Pipeline" },
{ "Comment", "/** What state is this particular job instance currently in? */" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
{ "ToolTip", "What state is this particular job instance currently in?" },
};
#endif
const UE4CodeGen_Private::FEnumPropertyParams Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_JobStatus = { "JobStatus", nullptr, (EPropertyFlags)0x0010000000000014, UE4CodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMoviePipelineExecutorJob, JobStatus), Z_Construct_UEnum_MovieRenderPipelineCore_EMoviePipelineExecutorJobStatus, METADATA_PARAMS(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_JobStatus_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_JobStatus_MetaData)) };
const UE4CodeGen_Private::FBytePropertyParams Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_JobStatus_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Map_MetaData[] = {
{ "Category", "Movie Render Pipeline" },
{ "Comment", "/** Which map should this job render on */" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
{ "ToolTip", "Which map should this job render on" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Map = { "Map", nullptr, (EPropertyFlags)0x0010000000000004, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMoviePipelineExecutorJob, Map), Z_Construct_UScriptStruct_FSoftObjectPath, METADATA_PARAMS(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Map_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Map_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Sequence_MetaData[] = {
{ "Category", "Movie Render Pipeline" },
{ "Comment", "/** Which sequence should this job render? */" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
{ "ToolTip", "Which sequence should this job render?" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Sequence = { "Sequence", nullptr, (EPropertyFlags)0x0010000000000004, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMoviePipelineExecutorJob, Sequence), Z_Construct_UScriptStruct_FSoftObjectPath, METADATA_PARAMS(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Sequence_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Sequence_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_LoadedSequence,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_PresetOrigin,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Configuration,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Author,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_JobStatus,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_JobStatus_Underlying,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Map,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::NewProp_Sequence,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<UMoviePipelineExecutorJob>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::ClassParams = {
&UMoviePipelineExecutorJob::StaticClass,
nullptr,
&StaticCppClassTypeInfo,
DependentSingletons,
FuncInfo,
Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::PropPointers,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
UE_ARRAY_COUNT(FuncInfo),
UE_ARRAY_COUNT(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::PropPointers),
0,
0x009000A0u,
METADATA_PARAMS(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_UMoviePipelineExecutorJob()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UMoviePipelineExecutorJob_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(UMoviePipelineExecutorJob, 817024653);
template<> MOVIERENDERPIPELINECORE_API UClass* StaticClass<UMoviePipelineExecutorJob>()
{
return UMoviePipelineExecutorJob::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UMoviePipelineExecutorJob(Z_Construct_UClass_UMoviePipelineExecutorJob, &UMoviePipelineExecutorJob::StaticClass, TEXT("/Script/MovieRenderPipelineCore"), TEXT("UMoviePipelineExecutorJob"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UMoviePipelineExecutorJob);
DEFINE_FUNCTION(UMoviePipelineQueue::execGetJobs)
{
P_FINISH;
P_NATIVE_BEGIN;
*(TArray<UMoviePipelineExecutorJob*>*)Z_Param__Result=P_THIS->GetJobs();
P_NATIVE_END;
}
DEFINE_FUNCTION(UMoviePipelineQueue::execDuplicateJob)
{
P_GET_OBJECT(UMoviePipelineExecutorJob,Z_Param_InJob);
P_FINISH;
P_NATIVE_BEGIN;
*(UMoviePipelineExecutorJob**)Z_Param__Result=P_THIS->DuplicateJob(Z_Param_InJob);
P_NATIVE_END;
}
DEFINE_FUNCTION(UMoviePipelineQueue::execDeleteJob)
{
P_GET_OBJECT(UMoviePipelineExecutorJob,Z_Param_InJob);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->DeleteJob(Z_Param_InJob);
P_NATIVE_END;
}
DEFINE_FUNCTION(UMoviePipelineQueue::execAllocateNewJob)
{
P_FINISH;
P_NATIVE_BEGIN;
*(UMoviePipelineExecutorJob**)Z_Param__Result=P_THIS->AllocateNewJob();
P_NATIVE_END;
}
void UMoviePipelineQueue::StaticRegisterNativesUMoviePipelineQueue()
{
UClass* Class = UMoviePipelineQueue::StaticClass();
static const FNameNativePtrPair Funcs[] = {
{ "AllocateNewJob", &UMoviePipelineQueue::execAllocateNewJob },
{ "DeleteJob", &UMoviePipelineQueue::execDeleteJob },
{ "DuplicateJob", &UMoviePipelineQueue::execDuplicateJob },
{ "GetJobs", &UMoviePipelineQueue::execGetJobs },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs));
}
struct Z_Construct_UFunction_UMoviePipelineQueue_AllocateNewJob_Statics
{
struct MoviePipelineQueue_eventAllocateNewJob_Parms
{
UMoviePipelineExecutorJob* ReturnValue;
};
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UMoviePipelineQueue_AllocateNewJob_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MoviePipelineQueue_eventAllocateNewJob_Parms, ReturnValue), Z_Construct_UClass_UMoviePipelineExecutorJob_NoRegister, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UMoviePipelineQueue_AllocateNewJob_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UMoviePipelineQueue_AllocateNewJob_Statics::NewProp_ReturnValue,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UMoviePipelineQueue_AllocateNewJob_Statics::Function_MetaDataParams[] = {
{ "Category", "Movie Render Pipeline|Queue" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UMoviePipelineQueue_AllocateNewJob_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UMoviePipelineQueue, nullptr, "AllocateNewJob", nullptr, nullptr, sizeof(MoviePipelineQueue_eventAllocateNewJob_Parms), Z_Construct_UFunction_UMoviePipelineQueue_AllocateNewJob_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineQueue_AllocateNewJob_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UMoviePipelineQueue_AllocateNewJob_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineQueue_AllocateNewJob_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UMoviePipelineQueue_AllocateNewJob()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UMoviePipelineQueue_AllocateNewJob_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UMoviePipelineQueue_DeleteJob_Statics
{
struct MoviePipelineQueue_eventDeleteJob_Parms
{
UMoviePipelineExecutorJob* InJob;
};
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_InJob;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UMoviePipelineQueue_DeleteJob_Statics::NewProp_InJob = { "InJob", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MoviePipelineQueue_eventDeleteJob_Parms, InJob), Z_Construct_UClass_UMoviePipelineExecutorJob_NoRegister, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UMoviePipelineQueue_DeleteJob_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UMoviePipelineQueue_DeleteJob_Statics::NewProp_InJob,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UMoviePipelineQueue_DeleteJob_Statics::Function_MetaDataParams[] = {
{ "Category", "Movie Render Pipeline|Queue" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UMoviePipelineQueue_DeleteJob_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UMoviePipelineQueue, nullptr, "DeleteJob", nullptr, nullptr, sizeof(MoviePipelineQueue_eventDeleteJob_Parms), Z_Construct_UFunction_UMoviePipelineQueue_DeleteJob_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineQueue_DeleteJob_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UMoviePipelineQueue_DeleteJob_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineQueue_DeleteJob_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UMoviePipelineQueue_DeleteJob()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UMoviePipelineQueue_DeleteJob_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob_Statics
{
struct MoviePipelineQueue_eventDuplicateJob_Parms
{
UMoviePipelineExecutorJob* InJob;
UMoviePipelineExecutorJob* ReturnValue;
};
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_InJob;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MoviePipelineQueue_eventDuplicateJob_Parms, ReturnValue), Z_Construct_UClass_UMoviePipelineExecutorJob_NoRegister, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob_Statics::NewProp_InJob = { "InJob", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MoviePipelineQueue_eventDuplicateJob_Parms, InJob), Z_Construct_UClass_UMoviePipelineExecutorJob_NoRegister, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob_Statics::NewProp_ReturnValue,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob_Statics::NewProp_InJob,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob_Statics::Function_MetaDataParams[] = {
{ "Category", "Movie Render Pipeline|Queue" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UMoviePipelineQueue, nullptr, "DuplicateJob", nullptr, nullptr, sizeof(MoviePipelineQueue_eventDuplicateJob_Parms), Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UMoviePipelineQueue_GetJobs_Statics
{
struct MoviePipelineQueue_eventGetJobs_Parms
{
TArray<UMoviePipelineExecutorJob*> ReturnValue;
};
static const UE4CodeGen_Private::FArrayPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ReturnValue_Inner;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FArrayPropertyParams Z_Construct_UFunction_UMoviePipelineQueue_GetJobs_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Array, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MoviePipelineQueue_eventGetJobs_Parms, ReturnValue), EArrayPropertyFlags::None, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UMoviePipelineQueue_GetJobs_Statics::NewProp_ReturnValue_Inner = { "ReturnValue", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, Z_Construct_UClass_UMoviePipelineExecutorJob_NoRegister, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UMoviePipelineQueue_GetJobs_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UMoviePipelineQueue_GetJobs_Statics::NewProp_ReturnValue,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UMoviePipelineQueue_GetJobs_Statics::NewProp_ReturnValue_Inner,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UMoviePipelineQueue_GetJobs_Statics::Function_MetaDataParams[] = {
{ "Category", "Movie Render Pipeline|Queue" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UMoviePipelineQueue_GetJobs_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UMoviePipelineQueue, nullptr, "GetJobs", nullptr, nullptr, sizeof(MoviePipelineQueue_eventGetJobs_Parms), Z_Construct_UFunction_UMoviePipelineQueue_GetJobs_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineQueue_GetJobs_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x54020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UMoviePipelineQueue_GetJobs_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UMoviePipelineQueue_GetJobs_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UMoviePipelineQueue_GetJobs()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UMoviePipelineQueue_GetJobs_Statics::FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_UMoviePipelineQueue_NoRegister()
{
return UMoviePipelineQueue::StaticClass();
}
struct Z_Construct_UClass_UMoviePipelineQueue_Statics
{
static UObject* (*const DependentSingletons[])();
static const FClassFunctionLinkInfo FuncInfo[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Jobs_MetaData[];
#endif
static const UE4CodeGen_Private::FArrayPropertyParams NewProp_Jobs;
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Jobs_Inner;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_UMoviePipelineQueue_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_UObject,
(UObject* (*)())Z_Construct_UPackage__Script_MovieRenderPipelineCore,
};
const FClassFunctionLinkInfo Z_Construct_UClass_UMoviePipelineQueue_Statics::FuncInfo[] = {
{ &Z_Construct_UFunction_UMoviePipelineQueue_AllocateNewJob, "AllocateNewJob" }, // 1329944567
{ &Z_Construct_UFunction_UMoviePipelineQueue_DeleteJob, "DeleteJob" }, // 388844117
{ &Z_Construct_UFunction_UMoviePipelineQueue_DuplicateJob, "DuplicateJob" }, // 1557732825
{ &Z_Construct_UFunction_UMoviePipelineQueue_GetJobs, "GetJobs" }, // 1391823918
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMoviePipelineQueue_Statics::Class_MetaDataParams[] = {
{ "BlueprintType", "true" },
{ "Comment", "/**\n* A queue is a list of jobs that have been executed, are executing and are waiting to be executed. These can be saved\n* to specific assets to allow \n*/" },
{ "IncludePath", "MoviePipelineQueue.h" },
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
{ "ToolTip", "A queue is a list of jobs that have been executed, are executing and are waiting to be executed. These can be saved\nto specific assets to allow" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMoviePipelineQueue_Statics::NewProp_Jobs_MetaData[] = {
{ "ModuleRelativePath", "Public/MoviePipelineQueue.h" },
};
#endif
const UE4CodeGen_Private::FArrayPropertyParams Z_Construct_UClass_UMoviePipelineQueue_Statics::NewProp_Jobs = { "Jobs", nullptr, (EPropertyFlags)0x0040000000000000, UE4CodeGen_Private::EPropertyGenFlags::Array, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMoviePipelineQueue, Jobs), EArrayPropertyFlags::None, METADATA_PARAMS(Z_Construct_UClass_UMoviePipelineQueue_Statics::NewProp_Jobs_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMoviePipelineQueue_Statics::NewProp_Jobs_MetaData)) };
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UMoviePipelineQueue_Statics::NewProp_Jobs_Inner = { "Jobs", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, Z_Construct_UClass_UMoviePipelineExecutorJob_NoRegister, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UMoviePipelineQueue_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMoviePipelineQueue_Statics::NewProp_Jobs,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMoviePipelineQueue_Statics::NewProp_Jobs_Inner,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_UMoviePipelineQueue_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<UMoviePipelineQueue>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UMoviePipelineQueue_Statics::ClassParams = {
&UMoviePipelineQueue::StaticClass,
nullptr,
&StaticCppClassTypeInfo,
DependentSingletons,
FuncInfo,
Z_Construct_UClass_UMoviePipelineQueue_Statics::PropPointers,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
UE_ARRAY_COUNT(FuncInfo),
UE_ARRAY_COUNT(Z_Construct_UClass_UMoviePipelineQueue_Statics::PropPointers),
0,
0x001000A0u,
METADATA_PARAMS(Z_Construct_UClass_UMoviePipelineQueue_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UMoviePipelineQueue_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_UMoviePipelineQueue()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UMoviePipelineQueue_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(UMoviePipelineQueue, 762955789);
template<> MOVIERENDERPIPELINECORE_API UClass* StaticClass<UMoviePipelineQueue>()
{
return UMoviePipelineQueue::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UMoviePipelineQueue(Z_Construct_UClass_UMoviePipelineQueue, &UMoviePipelineQueue::StaticClass, TEXT("/Script/MovieRenderPipelineCore"), TEXT("UMoviePipelineQueue"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UMoviePipelineQueue);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| [
"wingkdh@gmail.com"
] | wingkdh@gmail.com |
2702911f39a5e24dc004daf4013bfac76f6a374e | fe80860726329a37fae92675c655cf2d9418ad57 | /_GuardianFinalZero/PlayerCollection.cpp | a941baea4d9871bdd17e30d677c6e7fa2217b0c5 | [] | no_license | RDAppel/ArcadeShooter | 8734557e91f2b33de431dd7161c5595d3ab2ca6e | ee3542bb7916b7a569da92cb45c73ff6652cc50a | refs/heads/master | 2022-12-16T05:16:07.813856 | 2022-12-07T03:19:03 | 2022-12-07T03:19:03 | 85,904,850 | 4 | 2 | null | 2018-02-20T00:37:39 | 2017-03-23T03:53:59 | C++ | UTF-8 | C++ | false | false | 1,822 | cpp |
/* '888 88888888888 888888888',8888'
88 888888888888 8888888',8888'
8 8888 ,8',8888'
==̲=̲=̲=̲=̲=̲=== 8 8888 ========== ,8 ,̲8̲88̲8_==============
/ ____/__ 8_̲88̲8̲8̲8̲88̲88̲8̲8̲8__ ,̲8__/ //_/____ _ ____
/ / __ / / / /ˊ __ `// ___/ˊ __ /__ ˊ __ `// __ \
/ /__/ // /_/ // /_/ // / / /_/ // // /_/ // / / /
\_____/ \__,_/ \__,_//_/ \__,_//_/ \__,_//_/ /_/
============== 8 8888 ===== ,8',8888' ===============
88 8888 ,8',8888888888888
,88 8888 ,8',888888888888888,
ファイナル ゼロ
Guardian FZ © 2017 - Shuriken Studios LLC */
#include "GuardianFinalZero.h"
namespace GuardianFinalZero
{
PlayerCollection::PlayerCollection()
{
for (uint8_t i = 0; i < MAX_PLAYERS; i++) m_pPlayerShips[i] = nullptr;
InitializeShip(0);
}
void PlayerCollection::HandleInput(const InputState* pInput)
{
int8_t playerIndex = -1;
if (pInput->IsNewButtonPress(Button::START, playerIndex))
{
if (playerIndex >= 0 && !m_pPlayerShips[playerIndex])
{
InitializeShip(playerIndex);
}
}
}
void PlayerCollection::InitializeShip(uint8_t index)
{
PlayerShip* pShip = new PlayerShip(index);
Blaster* pBlaster = new Blaster(true);
pBlaster->SetTriggerType(TriggerType::SECONDARY);
/*
TriggerType *t0 = new TriggerType(0);
TriggerType *t1 = new TriggerType(1);
TriggerType *t2 = new TriggerType(2);
*/
pShip->AttachWeapon(pBlaster, Vector2(0, 0));
m_pPlayerShips[index] = pShip;
}
} | [
"appel@fvtc.edu"
] | appel@fvtc.edu |
54cd2c66d92e0ca2ebc6789e26200ffec4f8593c | dc5ee97a876ed01cc67b55edc425e35e361de37a | /ngraph_creator/operations/include/FullyConnected.hpp | 1e7228433c62e55523297a3bd0b002311adaf7e9 | [
"Apache-2.0"
] | permissive | intel/nn-hal | 30c6a20b212dc94455a84c4342a98e8cfa6acb84 | 405cc0ecbe062103ae09d67644346516d7c58726 | refs/heads/main | 2023-08-31T07:53:24.888335 | 2022-10-07T21:17:54 | 2022-10-07T21:40:43 | 125,920,516 | 47 | 51 | null | 2023-03-28T06:29:37 | 2018-03-19T21:08:07 | C++ | UTF-8 | C++ | false | false | 419 | hpp | #pragma once
#include <OperationsBase.hpp>
namespace android {
namespace hardware {
namespace neuralnetworks {
namespace nnhal {
class FullyConnected : public OperationsBase {
public:
FullyConnected(int operationIndex);
bool validate() override;
std::shared_ptr<ngraph::Node> createNode() override;
};
} // namespace nnhal
} // namespace neuralnetworks
} // namespace hardware
} // namespace android | [
"jeevakaprabu@gmail.com"
] | jeevakaprabu@gmail.com |
b34622377127e83c378f843b32dba8d40b0717c8 | 32da723b5c759c98845249bb51332109014b4f62 | /C++OOP.cpp/PracticalProjects1/Shopping_Cart/Inventory.cpp | 47481bc7bae81d6c7eaf9d1eb3d80712c0517539 | [] | no_license | IliyanKafedzhiev/FacultyOfMathematicAndInformatic | b8a810ca1100cc0f39c1460f60eb014e4c0b5ffc | a2b05a9aa7e677609447c0311ee79552464434ce | refs/heads/master | 2020-07-06T04:19:30.531000 | 2015-03-02T21:54:42 | 2015-03-02T21:54:42 | 18,809,355 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,289 | cpp | #include "Inventory.h"
Inventory::Inventory(void):count(0),capacity(1)
{
Name = new string[1];
price = new double[1];
}
Inventory::~Inventory(void)
{
delete[] this->Name;
delete[] this->price;
}
int Inventory::foundIndexByName(string searchedName)const
{
for (int i = 0; i < count; i++)
{
if (Name[i] == searchedName)
{
return i;
}
}
return -1;
}
void Inventory::ExtendCatalog()
{
if (capacity == 0)
{
capacity = 1;
}
this->capacity *= 2;
string* newNameCatalog = new string[capacity];
double* newPriceCatalog = new double[capacity];
for (int i = 0; i < count; i++)
{
newNameCatalog[i] = Name[i];
newPriceCatalog[i] = price[i];
}
delete[] Name;
delete[] price;
Name = newNameCatalog;
price = newPriceCatalog;
}
void Inventory::PringAllProducts()const
{
for (int i = 0; i < count; i++)
{
cout<<"Name :"<<Name[i]<<endl;
cout<<"Price :"<<price[i]<<endl<<endl;
}
}
void Inventory::Register(const string NameOfTheNewProduct, const double PriceOfTheNewProduct)
{
int index = foundIndexByName(NameOfTheNewProduct);
if (index == -1)
{
if (count >= capacity)
{
ExtendCatalog();
}
Name[count] = NameOfTheNewProduct;
price[count] = PriceOfTheNewProduct;
count++;
}
else
{
this->price[index] = PriceOfTheNewProduct;
}
}
| [
"iliqnkafedjiev@gmial.com"
] | iliqnkafedjiev@gmial.com |
fa973e65cd3a5901231c6736edf1290d64cc587f | fe91ffa11707887e4cdddde8f386a8c8e724aa58 | /ash/shelf/scrollable_shelf_view.h | 0527af471db418c74fd1a222e52531f49fd57926 | [
"BSD-3-Clause"
] | permissive | akshaymarch7/chromium | 78baac2b45526031846ccbaeca96c639d1d60ace | d273c844a313b1e527dec0d59ce70c95fd2bd458 | refs/heads/master | 2023-02-26T23:48:03.686055 | 2020-04-15T01:20:07 | 2020-04-15T01:20:07 | 255,778,651 | 2 | 1 | BSD-3-Clause | 2020-04-15T02:04:56 | 2020-04-15T02:04:55 | null | UTF-8 | C++ | false | false | 21,730 | h | // Copyright 2019 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 ASH_SHELF_SCROLLABLE_SHELF_VIEW_H_
#define ASH_SHELF_SCROLLABLE_SHELF_VIEW_H_
#include <memory>
#include "ash/app_list/views/app_list_drag_and_drop_host.h"
#include "ash/ash_export.h"
#include "ash/public/cpp/shelf_config.h"
#include "ash/public/cpp/shelf_model.h"
#include "ash/shelf/scroll_arrow_view.h"
#include "ash/shelf/shelf.h"
#include "ash/shelf/shelf_button_delegate.h"
#include "ash/shelf/shelf_container_view.h"
#include "ash/shelf/shelf_tooltip_delegate.h"
#include "ash/shelf/shelf_view.h"
#include "base/cancelable_callback.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/views/animation/ink_drop_host_view.h"
#include "ui/views/context_menu_controller.h"
#include "ui/views/controls/button/button.h"
namespace views {
class FocusSearch;
}
namespace ash {
class PresentationTimeRecorder;
class ScrollableShelfAnimationMetricsReporter;
class ASH_EXPORT ScrollableShelfView : public views::AccessiblePaneView,
public ShellObserver,
public ShelfConfig::Observer,
public ShelfButtonDelegate,
public ShelfTooltipDelegate,
public views::ContextMenuController,
public ApplicationDragAndDropHost,
public ui::ImplicitAnimationObserver {
public:
class TestObserver {
public:
virtual ~TestObserver() = default;
virtual void OnPageFlipTimerFired() = 0;
};
enum LayoutStrategy {
// The arrow buttons are not shown. It means that there is enough space to
// accommodate all of shelf icons.
kNotShowArrowButtons,
// Only the left arrow button is shown.
kShowLeftArrowButton,
// Only the right arrow button is shown.
kShowRightArrowButton,
// Both buttons are shown.
kShowButtons
};
ScrollableShelfView(ShelfModel* model, Shelf* shelf);
~ScrollableShelfView() override;
void Init();
// Called when the focus ring for ScrollableShelfView is enabled/disabled.
// |activated| is true when enabling the focus ring.
void OnFocusRingActivationChanged(bool activated);
// Scrolls to a new page of shelf icons. |forward| indicates whether the next
// page or previous page is shown.
void ScrollToNewPage(bool forward);
// AccessiblePaneView:
views::FocusSearch* GetFocusSearch() override;
views::FocusTraversable* GetFocusTraversableParent() override;
views::View* GetFocusTraversableParentView() override;
views::View* GetDefaultFocusableChild() override;
// Returns the |available_space_|.
gfx::Rect GetHotseatBackgroundBounds() const;
// Returns whether the view should adapt to RTL.
bool ShouldAdaptToRTL() const;
// Returns whether the scrollable shelf's current size is equal to the target
// size.
bool NeedUpdateToTargetBounds() const;
// Returns the icon's target bounds in screen. The returned bounds are
// calculated with the hotseat's target bounds instead of the actual bounds.
// It helps to get the icon's final location before the bounds animation on
// hotseat ends.
gfx::Rect GetTargetScreenBoundsOfItemIcon(const ShelfID& id) const;
views::View* GetShelfContainerViewForTest();
bool ShouldAdjustForTest() const;
void SetTestObserver(TestObserver* test_observer);
ShelfView* shelf_view() { return shelf_view_; }
ShelfContainerView* shelf_container_view() { return shelf_container_view_; }
const ShelfContainerView* shelf_container_view() const {
return shelf_container_view_;
}
ScrollArrowView* left_arrow() { return left_arrow_; }
const ScrollArrowView* left_arrow() const { return left_arrow_; }
ScrollArrowView* right_arrow() { return right_arrow_; }
const ScrollArrowView* right_arrow() const { return right_arrow_; }
LayoutStrategy layout_strategy_for_test() const { return layout_strategy_; }
gfx::Vector2dF scroll_offset_for_test() const { return scroll_offset_; }
const DragImageView* drag_icon_for_test() const { return drag_icon_.get(); }
int first_tappable_app_index() { return first_tappable_app_index_; }
int last_tappable_app_index() { return last_tappable_app_index_; }
void set_default_last_focusable_child(bool default_last_focusable_child) {
default_last_focusable_child_ = default_last_focusable_child;
}
void set_page_flip_time_threshold(base::TimeDelta page_flip_time_threshold) {
page_flip_time_threshold_ = page_flip_time_threshold;
}
const gfx::Rect& visible_space() const { return visible_space_; }
// Size of the arrow button.
static int GetArrowButtonSize();
// Padding at the two ends of the shelf.
static constexpr int kEndPadding = 4;
// The mouse wheel event (including touchpad scrolling) with the main axis
// offset smaller than the threshold will be ignored.
static constexpr int KScrollOffsetThreshold = 20;
private:
friend class ShelfTestApi;
class GradientLayerDelegate;
class ScrollableShelfArrowView;
class DragIconDropAnimationDelegate;
struct FadeZone {
// Bounds of the fade in/out zone.
gfx::Rect zone_rect;
// Specifies the type of FadeZone: fade in or fade out.
bool fade_in = false;
// Indicates the drawing direction.
bool is_horizontal = false;
};
enum ScrollStatus {
// Indicates whether the gesture scrolling is across the main axis.
// That is, whether it is scrolling vertically for bottom shelf, or
// whether it is scrolling horizontally for left/right shelf.
kAcrossMainAxisScroll,
// Indicates whether the gesture scrolling is along the main axis.
// That is, whether it is scrolling horizontally for bottom shelf, or
// whether it is scrolling vertically for left/right shelf.
kAlongMainAxisScroll,
// Not in scrolling.
kNotInScroll
};
// Returns the maximum scroll distance based on the given space for icons.
float CalculateScrollUpperBound(int available_space_for_icons) const;
// Returns the clamped scroll offset.
float CalculateClampedScrollOffset(float scroll,
int available_space_for_icons) const;
// Creates the animation for scrolling shelf by |scroll_distance|.
void StartShelfScrollAnimation(float scroll_distance);
// Calculates the layout strategy based on the three factors:
// (1) scroll offset on the main axis; (2) available space for shelf icons;
// (3) Bounds of the scrollable shelf view: actual view bounds or target
// bounds.
LayoutStrategy CalculateLayoutStrategy(float scroll_distance_on_main_axis,
int space_for_icons,
bool use_target_bounds) const;
Shelf* GetShelf();
const Shelf* GetShelf() const;
// views::View:
gfx::Size CalculatePreferredSize() const override;
void Layout() override;
void ChildPreferredSizeChanged(views::View* child) override;
const char* GetClassName() const override;
void OnScrollEvent(ui::ScrollEvent* event) override;
void OnMouseEvent(ui::MouseEvent* event) override;
void OnGestureEvent(ui::GestureEvent* event) override;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
void OnBoundsChanged(const gfx::Rect& previous_bounds) override;
void ViewHierarchyChanged(
const views::ViewHierarchyChangedDetails& details) override;
void ScrollRectToVisible(const gfx::Rect& rect) override;
std::unique_ptr<ui::Layer> RecreateLayer() override;
// ShelfButtonDelegate:
void OnShelfButtonAboutToRequestFocusFromTabTraversal(ShelfButton* button,
bool reverse) override;
void ButtonPressed(views::Button* sender,
const ui::Event& event,
views::InkDrop* ink_drop) override;
void HandleAccessibleActionScrollToMakeVisible(ShelfButton* button) override;
void NotifyInkDropActivity(bool activated, views::Button* sender) override;
// ContextMenuController:
void ShowContextMenuForViewImpl(views::View* source,
const gfx::Point& point,
ui::MenuSourceType source_type) override;
// ShellObserver:
void OnShelfAlignmentChanged(aura::Window* root_window,
ShelfAlignment old_alignment) override;
// ShelfConfig::Observer:
void OnShelfConfigUpdated() override;
// ShelfTooltipDelegate:
bool ShouldShowTooltipForView(const views::View* view) const override;
bool ShouldHideTooltip(const gfx::Point& cursor_location) const override;
const std::vector<aura::Window*> GetOpenWindowsForView(
views::View* view) override;
base::string16 GetTitleForView(const views::View* view) const override;
views::View* GetViewForEvent(const ui::Event& event) override;
// ApplicationDragAndDropHost:
void CreateDragIconProxyByLocationWithNoAnimation(
const gfx::Point& origin_in_screen_coordinates,
const gfx::ImageSkia& icon,
views::View* replaced_view,
float scale_factor,
int blur_radius) override;
void UpdateDragIconProxy(
const gfx::Point& location_in_screen_coordinates) override;
void DestroyDragIconProxy() override;
bool StartDrag(const std::string& app_id,
const gfx::Point& location_in_screen_coordinates) override;
bool Drag(const gfx::Point& location_in_screen_coordinates) override;
// ui::ImplicitAnimationObserver:
void OnImplicitAnimationsCompleted() override;
// Returns whether the left/right arrow button should show based on the
// current layout strategy. Because Layout(), where the visibility of arrow
// buttons is updated, may be called in asynchronous way, we should not use
// arrow buttons' visibility directly.
bool ShouldShowLeftArrow() const;
bool ShouldShowRightArrow() const;
// Returns the padding insets which guarantee the minimum gap between
// scrollable shelf and other components (like status area widget).
gfx::Insets CalculateBaseEdgePadding() const;
// Returns the extra padding inset which is influenced by the padding
// strategy. There are three strategies: (1) display centering alignment (2)
// scrollable shelf centering alignment (3) overflow mode
// |use_target_bounds| indicates which view bounds are used for calculation:
// actual view bounds or target view bounds.
gfx::Insets CalculateExtraEdgePadding(bool use_target_bounds) const;
// Returns the sum of the base padding and the extra padding.
gfx::Insets GetTotalEdgePadding() const;
int GetStatusWidgetSizeOnPrimaryAxis(bool use_target_bounds) const;
// Returns the local bounds depending on which view bounds are used: actual
// view bounds or target view bounds.
gfx::Rect GetAvailableLocalBounds(bool use_target_bounds) const;
// Calculates padding for display centering alignment depending on which view
// bounds are used: actual view bounds or target view bounds.
gfx::Insets CalculatePaddingForDisplayCentering(bool use_target_bounds) const;
// Returns whether the received gesture event should be handled here.
bool ShouldHandleGestures(const ui::GestureEvent& event);
// Resets the attributes related with gesture scroll to their default values.
void ResetScrollStatus();
// Handles events for scrolling the shelf. Returns whether the event has been
// consumed.
bool ProcessGestureEvent(const ui::GestureEvent& event);
void HandleMouseWheelEvent(ui::MouseWheelEvent* event);
// Scrolls the view by distance of |x_offset| or |y_offset|. |animating|
// indicates whether the animation displays. |x_offset| or |y_offset| has to
// be float. Otherwise the slow gesture drag is neglected.
void ScrollByXOffset(float x_offset, bool animating);
void ScrollByYOffset(float y_offset, bool animating);
// Scrolls the view to the target offset. |animating| indicates whether the
// scroll animation is needed. Note that |target_offset| may be an illegal
// value and may get adjusted in CalculateClampedScrollOffset function.
void ScrollToMainOffset(float target_offset, bool animating);
// Calculates the scroll distance to show a new page of shelf icons for
// the given layout strategy. |forward| indicates whether the next page or
// previous page is shown.
float CalculatePageScrollingOffset(bool forward,
LayoutStrategy layout_strategy) const;
// Calculates the absolute value of page scroll distance.
float CalculatePageScrollingOffsetInAbs(LayoutStrategy layout_strategy) const;
// Calculates the target offset on the main axis after scrolling by
// |scroll_distance| while the offset before scroll is |start_offset|.
float CalculateTargetOffsetAfterScroll(float start_offset,
float scroll_distance) const;
// Calculates the bounds of the gradient zone before/after the shelf
// container.
FadeZone CalculateStartGradientZone() const;
FadeZone CalculateEndGradientZone() const;
// Updates the visibility of gradient zones.
void UpdateGradientZoneState();
// Updates the gradient zone if the gradient zone's target bounds are
// different from the actual values.
void MaybeUpdateGradientZone();
void PaintGradientZone(const FadeZone& start_gradient_zone,
const FadeZone& end_gradient_zone);
bool ShouldApplyMaskLayerGradientZone() const;
// Returns the actual scroll offset for the given scroll distance along the
// main axis under the specific layout strategy. When the left arrow button
// shows, |shelf_view_| is translated due to the change in
// |shelf_container_view_|'s bounds. That translation offset is not included
// in |scroll_offset_|.
float GetActualScrollOffset(float main_axis_scroll_distance,
LayoutStrategy layout_strategy) const;
// Updates |first_tappable_app_index_| and |last_tappable_app_index_|.
void UpdateTappableIconIndices();
// Calculates the indices of the first/last tappable app under the given
// layout strategy and offset along the main axis (that is the x-axis when
// shelf is horizontally aligned or the y-axis if the shelf is vertically
// aligned).
std::pair<int, int> CalculateTappableIconIndices(
LayoutStrategy layout_strategy,
int scroll_distance_on_main_axis) const;
views::View* FindFirstFocusableChild();
views::View* FindLastFocusableChild();
// Returns the available space on the main axis for shelf icons.
int GetSpaceForIcons() const;
// Returns whether there is available space to accommodate all shelf icons.
// |use_target_bounds| indicates which view bounds are used for
// calculation: actual view bounds or target view bounds.
bool CanFitAllAppsWithoutScrolling(bool use_target_bounds) const;
// Returns whether scrolling should be handled. |is_gesture_fling| is true
// when the scrolling is triggered by gesture fling event; when it is false,
// the scrolling is triggered by touch pad or mouse wheel event.
bool ShouldHandleScroll(const gfx::Vector2dF& offset,
bool is_gesture_fling) const;
// May initiate the scroll animation to ensure that the app icons are shown
// correctly. Returns whether the animation is created.
bool AdjustOffset();
// Returns the offset by which the scroll distance along the main axis should
// be adjusted to ensure the correct UI under the specific layout strategy.
// Three parameters are needed: (1) scroll offset on the main axis (2) layout
// strategy (3) available space for shelf icons.
float CalculateAdjustmentOffset(int main_axis_scroll_distance,
LayoutStrategy layout_strategy,
int available_space_for_icons) const;
int CalculateScrollDistanceAfterAdjustment(
int main_axis_scroll_distance,
LayoutStrategy layout_strategy) const;
// Updates the available space for child views (such as the arrow button,
// shelf view) which is smaller than the view's bounds due to paddings.
void UpdateAvailableSpace();
// Returns the clip rectangle of |shelf_container_view_| for the given layout
// strategy. Note that |shelf_container_view_|'s bounds are the same with
// ScrollableShelfView's. It is why we can use |visible_space_| directly
// without coordinate transformation.
gfx::Rect CalculateVisibleSpace(LayoutStrategy layout_strategy) const;
// Calculates the padding insets which help to show the edging app icon's
// ripple ring correctly.
gfx::Insets CalculateRipplePaddingInsets() const;
// Calculates the rounded corners for |shelf_container_view_|. It contributes
// to cut off the child view out of the scrollable shelf's bounds, such as
// ripple ring.
gfx::RoundedCornersF CalculateShelfContainerRoundedCorners() const;
// Scrolls to a new page if |drag_icon_| is dragged out of |visible_space_|
// for enough time. The function is called when |page_flip_timer_| is fired.
void OnPageFlipTimer();
bool IsDragIconWithinVisibleSpace() const;
// Returns whether a scroll event should be handled by this view or delegated
// to the shelf.
bool ShouldDelegateScrollToShelf(const ui::ScrollEvent& event) const;
// Calculates the scroll distance along the main axis.
float CalculateMainAxisScrollDistance() const;
// Updates |scroll_offset_| from |target_offset_| using shelf alignment.
// |scroll_offset_| may need to update in following cases: (1) View bounds are
// changed. (2) View is scrolled. (3) A shelf icon is added/removed.
void UpdateScrollOffset(float target_offset);
// Updates the available space, which may also trigger the change in scroll
// offset and layout strategy.
void UpdateAvailableSpaceAndScroll();
// Returns the scroll offset assuming view bounds being the target bounds.
int CalculateScrollOffsetForTargetAvailableSpace(
const gfx::Rect& target_space) const;
// Returns whether the ink drop for the |sender| needs to be clipped.
bool InkDropNeedsClipping(views::Button* sender) const;
// Enable/disable the rounded corners of the shelf container.
void EnableShelfRoundedCorners(bool enable);
LayoutStrategy layout_strategy_ = kNotShowArrowButtons;
// Child views Owned by views hierarchy.
ScrollArrowView* left_arrow_ = nullptr;
ScrollArrowView* right_arrow_ = nullptr;
ShelfContainerView* shelf_container_view_ = nullptr;
// Available space to accommodate child views.
gfx::Rect available_space_;
ShelfView* shelf_view_ = nullptr;
// Padding insets based on |base_padding_| and shelf alignment.
gfx::Insets base_padding_insets_;
// Extra insets decided by the current padding strategy.
gfx::Insets extra_padding_insets_;
// Minimum gap between scrollable shelf and other components (like status area
// widget) in DIPs.
const int base_padding_;
// Visible space of |shelf_container_view| in ScrollableShelfView's local
// coordinates. Different from |available_space_|, |visible_space_| only
// contains app icons and is mirrored for horizontal shelf under RTL.
gfx::Rect visible_space_;
gfx::Vector2dF scroll_offset_;
ScrollStatus scroll_status_ = kNotInScroll;
// Gesture states are preserved when the gesture scrolling along the main axis
// (that is, whether it is scrolling horizontally for bottom shelf, or whether
// it is scrolling horizontally for left/right shelf) gets started. They help
// to handle the gesture fling event.
gfx::Vector2dF scroll_offset_before_main_axis_scrolling_;
LayoutStrategy layout_strategy_before_main_axis_scrolling_ =
kNotShowArrowButtons;
std::unique_ptr<GradientLayerDelegate> gradient_layer_delegate_;
std::unique_ptr<views::FocusSearch> focus_search_;
// The index of the first/last tappable app index.
int first_tappable_app_index_ = -1;
int last_tappable_app_index_ = -1;
// Whether this view should focus its last focusable child (instead of its
// first) when focused.
bool default_last_focusable_child_ = false;
// Indicates whether the focus ring on shelf items contained by
// ScrollableShelfView is enabled.
bool focus_ring_activated_ = false;
// Indicates that the view is during the scroll animation.
bool during_scroll_animation_ = false;
// Indicates whether the gradient zone before/after the shelf container view
// should show.
bool should_show_start_gradient_zone_ = false;
bool should_show_end_gradient_zone_ = false;
// Waiting time before flipping the page.
base::TimeDelta page_flip_time_threshold_;
TestObserver* test_observer_ = nullptr;
// Replaces the dragged app icon during drag procedure. It ensures that the
// app icon can be dragged out of the shelf view.
std::unique_ptr<DragImageView> drag_icon_;
// The delegate to create the animation of moving the dropped icon to the
// ideal place after drag release.
std::unique_ptr<DragIconDropAnimationDelegate>
drag_icon_drop_animation_delegate_;
base::OneShotTimer page_flip_timer_;
// Metric reporter for scrolling animations.
const std::unique_ptr<ScrollableShelfAnimationMetricsReporter>
animation_metrics_reporter_;
// Records the presentation time for the scrollable shelf dragging.
std::unique_ptr<PresentationTimeRecorder> presentation_time_recorder_;
DISALLOW_COPY_AND_ASSIGN(ScrollableShelfView);
};
} // namespace ash
#endif // ASH_SHELF_SCROLLABLE_SHELF_VIEW_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
fbf474e537f35ac7c7015dee814adb9acbc97cf2 | c0f5d7ef2b590c155af58d83e8cbbf0854a3f995 | /include/caffe/util/math_functions.hpp | 59bb074e2f8c93cb39289288e5d66210d7bdd0ce | [
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | JiahaoLi-gdut/CAFFE-DACH | c8a039d437775b65c6ed6f4508b47acc66e025d4 | 388c826d8019f66bf0657acb2041dfccf4797fc9 | refs/heads/master | 2023-03-27T16:00:10.865638 | 2021-03-30T15:18:51 | 2021-03-30T15:18:51 | 353,027,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,924 | hpp | #ifndef CAFFE_UTIL_MATH_FUNCTIONS_H_
#define CAFFE_UTIL_MATH_FUNCTIONS_H_
#include <stdint.h>
#include <cmath> // for std::fabs and std::signbit
#include "glog/logging.h"
#include "caffe/common.hpp"
#include "caffe/util/device_alternate.hpp"
#include "caffe/util/mkl_alternate.hpp"
namespace caffe {
template <typename Dtype>
Dtype caffe_cpu_lossness_sum(const int n_x, Dtype* const x);
// Caffe gemm provides a simpler interface to the gemm functions, with the
// limitation that the data has to be contiguous in memory.
template <typename Dtype>
void caffe_cpu_gemm(const CBLAS_TRANSPOSE TransA,
const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,
const Dtype alpha, const Dtype* A, const Dtype* B, const Dtype beta,
Dtype* C);
template <typename Dtype>
void caffe_cpu_gemv(const CBLAS_TRANSPOSE TransA, const int M, const int N,
const Dtype alpha, const Dtype* A, const Dtype* x, const Dtype beta,
Dtype* y);
template <typename Dtype>
void caffe_axpy(const int N, const Dtype alpha, const Dtype* X,
Dtype* Y);
template <typename Dtype>
void caffe_cpu_axpby(const int N, const Dtype alpha, const Dtype* X,
const Dtype beta, Dtype* Y);
template <typename Dtype>
void caffe_copy(const int N, const Dtype *X, Dtype *Y);
template <typename Dtype>
void caffe_set(const int N, const Dtype alpha, Dtype *X);
inline void caffe_memset(const size_t N, const int alpha, void* X) {
memset(X, alpha, N); // NOLINT(caffe/alt_fn)
}
template <typename Dtype>
void caffe_add_scalar(const int N, const Dtype alpha, Dtype *X);
template <typename Dtype>
void caffe_scal(const int N, const Dtype alpha, Dtype *X);
template <typename Dtype>
void caffe_sqr(const int N, const Dtype* a, Dtype* y);
template <typename Dtype>
void caffe_sqrt(const int N, const Dtype* a, Dtype* y);
template <typename Dtype>
void caffe_add(const int N, const Dtype* a, const Dtype* b, Dtype* y);
template <typename Dtype>
void caffe_sub(const int N, const Dtype* a, const Dtype* b, Dtype* y);
template <typename Dtype>
void caffe_mul(const int N, const Dtype* a, const Dtype* b, Dtype* y);
template <typename Dtype>
void caffe_div(const int N, const Dtype* a, const Dtype* b, Dtype* y);
template <typename Dtype>
void caffe_div_nz(const int N, const Dtype* a, const Dtype* b, Dtype* y);
template <typename Dtype>
void caffe_powx(const int n, const Dtype* a, const Dtype b, Dtype* y);
unsigned int caffe_rng_rand();
template <typename Dtype>
Dtype caffe_nextafter(const Dtype b);
template <typename Dtype>
void caffe_rng_uniform(const int n, const Dtype a, const Dtype b, Dtype* r);
template <typename Dtype>
void caffe_rng_gaussian(const int n, const Dtype mu, const Dtype sigma,
Dtype* r);
template <typename Dtype>
void caffe_rng_bernoulli(const int n, const Dtype p, int* r);
template <typename Dtype>
void caffe_rng_bernoulli(const int n, const Dtype p, unsigned int* r);
template <typename Dtype>
void caffe_exp(const int n, const Dtype* a, Dtype* y);
template <typename Dtype>
void caffe_log(const int n, const Dtype* a, Dtype* y);
template <typename Dtype>
void caffe_abs(const int n, const Dtype* a, Dtype* y);
template <typename Dtype>
Dtype caffe_cpu_dot(const int n, const Dtype* x, const Dtype* y);
template <typename Dtype>
Dtype caffe_cpu_strided_dot(const int n, const Dtype* x, const int incx,
const Dtype* y, const int incy);
// Returns the sum of the absolute values of the elements of vector x
template <typename Dtype>
Dtype caffe_cpu_asum(const int n, const Dtype* x);
// the branchless, type-safe version from
// http://stackoverflow.com/questions/1903954/is-there-a-standard-sign-function-signum-sgn-in-c-c
template<typename Dtype>
inline int8_t caffe_sign(Dtype val) {
return (Dtype(0) < val) - (val < Dtype(0));
}
// The following two macros are modifications of DEFINE_VSL_UNARY_FUNC
// in include/caffe/util/mkl_alternate.hpp authored by @Rowland Depp.
// Please refer to commit 7e8ef25c7 of the boost-eigen branch.
// Git cherry picking that commit caused a conflict hard to resolve and
// copying that file in convenient for code reviewing.
// So they have to be pasted here temporarily.
#define DEFINE_CAFFE_CPU_UNARY_FUNC(name, operation) \
template<typename Dtype> \
void caffe_cpu_##name(const int n, const Dtype* x, Dtype* y) { \
CHECK_GT(n, 0); CHECK(x); CHECK(y); \
for (int i = 0; i < n; ++i) { \
operation; \
} \
}
// output is 1 for the positives, 0 for zero, and -1 for the negatives
DEFINE_CAFFE_CPU_UNARY_FUNC(sign, y[i] = caffe_sign<Dtype>(x[i]))
// This returns a nonzero value if the input has its sign bit set.
// The name sngbit is meant to avoid conflicts with std::signbit in the macro.
// The extra parens are needed because CUDA < 6.5 defines signbit as a macro,
// and we don't want that to expand here when CUDA headers are also included.
DEFINE_CAFFE_CPU_UNARY_FUNC(sgnbit, \
y[i] = static_cast<bool>((std::signbit)(x[i])))
DEFINE_CAFFE_CPU_UNARY_FUNC(fabs, y[i] = std::fabs(x[i]))
template <typename Dtype>
void caffe_cpu_scale(const int n, const Dtype alpha, const Dtype *x, Dtype* y);
#ifndef CPU_ONLY // GPU
template <typename Dtype>
void caffe_gpu_lossness_sum(const int n_x, Dtype* const x, Dtype* const y);
// Decaf gpu gemm provides an interface that is almost the same as the cpu
// gemm function - following the c convention and calling the fortran-order
// gpu code under the hood.
template <typename Dtype>
void caffe_gpu_gemm(const CBLAS_TRANSPOSE TransA,
const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,
const Dtype alpha, const Dtype* A, const Dtype* B, const Dtype beta,
Dtype* C);
template <typename Dtype>
void caffe_gpu_gemv(const CBLAS_TRANSPOSE TransA, const int M, const int N,
const Dtype alpha, const Dtype* A, const Dtype* x, const Dtype beta,
Dtype* y);
template <typename Dtype>
void caffe_gpu_axpy(const int N, const Dtype alpha, const Dtype* X,
Dtype* Y);
template <typename Dtype>
void caffe_gpu_axpby(const int N, const Dtype alpha, const Dtype* X,
const Dtype beta, Dtype* Y);
void caffe_gpu_memcpy(const size_t N, const void *X, void *Y);
template <typename Dtype>
void caffe_gpu_set(const int N, const Dtype alpha, Dtype *X);
inline void caffe_gpu_memset(const size_t N, const int alpha, void* X) {
#ifndef CPU_ONLY
CUDA_CHECK(cudaMemset(X, alpha, N)); // NOLINT(caffe/alt_fn)
#else
NO_GPU;
#endif
}
template <typename Dtype>
void caffe_gpu_add_scalar(const int N, const Dtype alpha, Dtype *X);
template <typename Dtype>
void caffe_gpu_scal(const int N, const Dtype alpha, Dtype *X);
#ifndef CPU_ONLY
template <typename Dtype>
void caffe_gpu_scal(const int N, const Dtype alpha, Dtype* X, cudaStream_t str);
#endif
template <typename Dtype>
void caffe_gpu_add(const int N, const Dtype* a, const Dtype* b, Dtype* y);
template <typename Dtype>
void caffe_gpu_sub(const int N, const Dtype* a, const Dtype* b, Dtype* y);
template <typename Dtype>
void caffe_gpu_mul(const int N, const Dtype* a, const Dtype* b, Dtype* y);
template <typename Dtype>
void caffe_gpu_div(const int N, const Dtype* a, const Dtype* b, Dtype* y);
template <typename Dtype>
void caffe_gpu_div_nz(const int N, const Dtype* a, const Dtype* b, Dtype* y);
template <typename Dtype>
void caffe_gpu_abs(const int n, const Dtype* a, Dtype* y);
template <typename Dtype>
void caffe_gpu_exp(const int n, const Dtype* a, Dtype* y);
template <typename Dtype>
void caffe_gpu_log(const int n, const Dtype* a, Dtype* y);
template <typename Dtype>
void caffe_gpu_powx(const int n, const Dtype* a, const Dtype b, Dtype* y);
template <typename Dtype>
void caffe_gpu_sqrt(const int n, const Dtype* a, Dtype* y);
// caffe_gpu_rng_uniform with two arguments generates integers in the range
// [0, UINT_MAX].
void caffe_gpu_rng_uniform(const int n, unsigned int* r);
// caffe_gpu_rng_uniform with four arguments generates floats in the range
// (a, b] (strictly greater than a, less than or equal to b) due to the
// specification of curandGenerateUniform. With a = 0, b = 1, just calls
// curandGenerateUniform; with other limits will shift and scale the outputs
// appropriately after calling curandGenerateUniform.
template <typename Dtype>
void caffe_gpu_rng_uniform(const int n, const Dtype a, const Dtype b, Dtype* r);
template <typename Dtype>
void caffe_gpu_rng_gaussian(const int n, const Dtype mu, const Dtype sigma,
Dtype* r);
template <typename Dtype>
void caffe_gpu_rng_bernoulli(const int n, const Dtype p, int* r);
template <typename Dtype>
void caffe_gpu_dot(const int n, const Dtype* x, const Dtype* y, Dtype* out);
template <typename Dtype>
void caffe_gpu_asum(const int n, const Dtype* x, Dtype* y);
template<typename Dtype>
void caffe_gpu_sign(const int n, const Dtype* x, Dtype* y);
template<typename Dtype>
void caffe_gpu_sgnbit(const int n, const Dtype* x, Dtype* y);
template <typename Dtype>
void caffe_gpu_fabs(const int n, const Dtype* x, Dtype* y);
template <typename Dtype>
void caffe_gpu_scale(const int n, const Dtype alpha, const Dtype *x, Dtype* y);
#define DEFINE_AND_INSTANTIATE_GPU_UNARY_FUNC(name, operation) \
template<typename Dtype> \
__global__ void name##_kernel(const int n, const Dtype* x, Dtype* y) { \
CUDA_KERNEL_LOOP(index, n) { \
operation; \
} \
} \
template <> \
void caffe_gpu_##name<float>(const int n, const float* x, float* y) { \
/* NOLINT_NEXT_LINE(whitespace/operators) */ \
name##_kernel<float><<<CAFFE_GET_BLOCKS(n), CAFFE_CUDA_NUM_THREADS>>>( \
n, x, y); \
} \
template <> \
void caffe_gpu_##name<double>(const int n, const double* x, double* y) { \
/* NOLINT_NEXT_LINE(whitespace/operators) */ \
name##_kernel<double><<<CAFFE_GET_BLOCKS(n), CAFFE_CUDA_NUM_THREADS>>>( \
n, x, y); \
}
#endif // !CPU_ONLY
} // namespace caffe
#endif // CAFFE_UTIL_MATH_FUNCTIONS_H_
| [
"jiahaoli.gdut@gmail.com"
] | jiahaoli.gdut@gmail.com |
a8af6f26f10e9c3bb692b0ffee6ab28935a6c718 | 4e006837ed7b91e877ec0fc9bd1c9b6e43131901 | /oxygine-sound/src/sound/null/SoundNull.h | 1401ccd92851804cf98fa985e3a430a0e39c5cfa | [
"MIT"
] | permissive | Poscowekh/Project | 52be9104b0ab16c9a504b4295e0a23cadd72ac7a | 3385c24646c951e37097b8ec1cfc29e9c5f44e05 | refs/heads/master | 2022-09-18T13:33:37.504605 | 2020-06-02T19:03:08 | 2020-06-02T19:03:08 | 259,675,760 | 0 | 0 | null | 2020-05-01T08:58:11 | 2020-04-28T15:24:50 | C | UTF-8 | C++ | false | false | 314 | h | #pragma once
#include "../Sound.h"
namespace oxygine
{
class SoundNull: public Sound
{
public:
SoundNull(int duration);
~SoundNull();
int getDuration() const override;
SoundHandle* createSH() override;
private:
int _duration;
};
}
| [
"ziuwari@ya.ru"
] | ziuwari@ya.ru |
b78b278e31d12c1cbd7fb6f83f4848f6badbcfe6 | d63afcb6b86b21dbb34f25d5290734ef59a19029 | /12.22/I.cpp | 548644ef38fbc94e30cf00d335bc3e9a56522695 | [] | no_license | alicepolice/C_Practice_All | 7ce1f3392aafbd8fbb325836294848a896c422bd | f8e9c5773a56612e1cc6b1af8d170ff0833caed0 | refs/heads/main | 2023-03-21T14:01:00.915845 | 2021-03-04T09:11:09 | 2021-03-04T09:11:09 | 325,172,958 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | cpp | #include<stdio.h>
int getint(int a,int b);
int main(void)
{
int m,n,i,a,b,c,d,k,s;
while(scanf("%d",&n)!=EOF)
{
for(int i = 0;i<n;i++)
{
s = 0;
scanf("%d %d",&a,&b);
s = getint(a,b);
printf("%d\n",s);
}
}
return 0;
}
int getint(int a,int b)
{
int k;
if(a>b) k = b; else k = a;
while(k>0)
{
if(a%k==0&&b%k==0) return k;
k--;
}
}
| [
"1048146700@qq.com"
] | 1048146700@qq.com |
005cf0ace8ebed551b85ea716c7a39da11f8d0f5 | 98d812e8638a498c626ecbeb05345c9931e7ae7d | /vista-server/src/controller/Drag.cpp | 40b1676c513adf4a8506eedc1f455ce4ad85c95e | [] | no_license | joelruggieri/tp-taller-de-programacion | c58ba538fb00a8c66627fa2fc95830f794a662db | 3949b704516dc6c1fb6df3781f17af251cd1fe67 | refs/heads/master | 2020-08-27T06:28:06.750370 | 2013-11-27T21:35:52 | 2013-11-27T21:35:52 | 32,125,297 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 927 | cpp |
/*
*
* Created on: 19/09/2013
* Author: jonathan
*/
#include "Drag.h"
Drag::~Drag() {
// TODO Auto-generated destructor stub
}
Drag::Drag(FiguraView* view, float yMax) {
this->view = view;
xStart = view->getXCentro();
yStart = view->getYCentro();
this->yMax = yMax;
}
void Drag::drop() {
view->drop();
}
FiguraView* Drag::getView() {
return view;
}
float Drag::desplazarCentroA(float &x, float &y) {
if(y> yMax){
y = yMax;
}
if(y < 0){
y = 0;
}
if(x < 0){
x = 0;
}
view->desplazarCentroA(x,y);
if(view->getModelo()){
view->getModelo()->setPosicion(x,y);
}
return y;
}
float Drag::getXCentro() const {
return view->getXCentro();
}
void Drag::rollBack() {
view->desplazarCentroA(xStart,yStart);
}
bool Drag::isRolledBack() const {
return this->xStart == view->getXCentro() && this->yStart == this->getYCentro();
}
float Drag::getYCentro() const {
return view->getYCentro();
}
| [
"jonathan.tierno@gmail.com@0e055b33-9e10-a41d-64d9-2761cfc4d589"
] | jonathan.tierno@gmail.com@0e055b33-9e10-a41d-64d9-2761cfc4d589 |
3ece8966fbb52365c4df989c88824a9fdf3bbe40 | 566c56c1d16065d6b218a84e42472b19b9082022 | /src/zsmnc/zsmnctracker.cpp | d4b8be1053400b157adbc1e7663addcaba57e04c | [
"MIT"
] | permissive | c0de0x/src | d509e44b15043d1459f4be0cdf89b82022a4f31d | 45550875bd4e53fc6d016ef1b1ed80d7779edeec | refs/heads/master | 2023-01-04T18:31:57.240773 | 2020-10-27T10:58:53 | 2020-10-27T10:58:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,869 | cpp | // Copyright (c) 2018-2019 The SIMPLEMASTERNODE developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <zsmnc/deterministicmint.h>
#include "zsmnctracker.h"
#include "util.h"
#include "sync.h"
#include "main.h"
#include "txdb.h"
#include "wallet/walletdb.h"
#include "zsmnc/accumulators.h"
#include "zsmnc/zsmncwallet.h"
#include "witness.h"
CzSmncTracker::CzSmncTracker(std::string strWalletFile)
{
this->strWalletFile = strWalletFile;
mapSerialHashes.clear();
mapPendingSpends.clear();
fInitialized = false;
}
CzSmncTracker::~CzSmncTracker()
{
mapSerialHashes.clear();
mapPendingSpends.clear();
}
void CzSmncTracker::Init()
{
//Load all CZerocoinMints and CDeterministicMints from the database
if (!fInitialized) {
ListMints(false, false, true);
fInitialized = true;
}
}
bool CzSmncTracker::Archive(CMintMeta& meta)
{
if (mapSerialHashes.count(meta.hashSerial))
mapSerialHashes.at(meta.hashSerial).isArchived = true;
CWalletDB walletdb(strWalletFile);
CZerocoinMint mint;
if (walletdb.ReadZerocoinMint(meta.hashPubcoin, mint)) {
if (!CWalletDB(strWalletFile).ArchiveMintOrphan(mint))
return error("%s: failed to archive zerocoinmint", __func__);
} else {
//failed to read mint from DB, try reading deterministic
CDeterministicMint dMint;
if (!walletdb.ReadDeterministicMint(meta.hashPubcoin, dMint))
return error("%s: could not find pubcoinhash %s in db", __func__, meta.hashPubcoin.GetHex());
if (!walletdb.ArchiveDeterministicOrphan(dMint))
return error("%s: failed to archive deterministic ophaned mint", __func__);
}
LogPrintf("%s: archived pubcoinhash %s\n", __func__, meta.hashPubcoin.GetHex());
return true;
}
bool CzSmncTracker::UnArchive(const uint256& hashPubcoin, bool isDeterministic)
{
CWalletDB walletdb(strWalletFile);
if (isDeterministic) {
CDeterministicMint dMint;
if (!walletdb.UnarchiveDeterministicMint(hashPubcoin, dMint))
return error("%s: failed to unarchive deterministic mint", __func__);
Add(dMint, false);
} else {
CZerocoinMint mint;
if (!walletdb.UnarchiveZerocoinMint(hashPubcoin, mint))
return error("%s: failed to unarchivezerocoin mint", __func__);
Add(mint, false);
}
LogPrintf("%s: unarchived %s\n", __func__, hashPubcoin.GetHex());
return true;
}
CMintMeta CzSmncTracker::Get(const uint256 &hashSerial)
{
if (!mapSerialHashes.count(hashSerial))
return CMintMeta();
return mapSerialHashes.at(hashSerial);
}
CMintMeta CzSmncTracker::GetMetaFromPubcoin(const uint256& hashPubcoin)
{
for (auto it : mapSerialHashes) {
CMintMeta meta = it.second;
if (meta.hashPubcoin == hashPubcoin)
return meta;
}
return CMintMeta();
}
bool CzSmncTracker::GetMetaFromStakeHash(const uint256& hashStake, CMintMeta& meta) const
{
for (auto& it : mapSerialHashes) {
if (it.second.hashStake == hashStake) {
meta = it.second;
return true;
}
}
return false;
}
CoinWitnessData* CzSmncTracker::GetSpendCache(const uint256& hashStake)
{
AssertLockHeld(cs_spendcache);
if (!mapStakeCache.count(hashStake)) {
std::unique_ptr<CoinWitnessData> uptr(new CoinWitnessData());
mapStakeCache.insert(std::make_pair(hashStake, std::move(uptr)));
return mapStakeCache.at(hashStake).get();
}
return mapStakeCache.at(hashStake).get();
}
bool CzSmncTracker::ClearSpendCache()
{
AssertLockHeld(cs_spendcache);
if (!mapStakeCache.empty()) {
mapStakeCache.clear();
return true;
}
return false;
}
std::vector<uint256> CzSmncTracker::GetSerialHashes()
{
std::vector<uint256> vHashes;
for (auto it : mapSerialHashes) {
if (it.second.isArchived)
continue;
vHashes.emplace_back(it.first);
}
return vHashes;
}
CAmount CzSmncTracker::GetBalance(bool fConfirmedOnly, bool fUnconfirmedOnly) const
{
CAmount nTotal = 0;
//! zerocoin specific fields
std::map<libzerocoin::CoinDenomination, unsigned int> myZerocoinSupply;
for (auto& denom : libzerocoin::zerocoinDenomList) {
myZerocoinSupply.insert(std::make_pair(denom, 0));
}
{
//LOCK(cs_smnctracker);
// Get Unused coins
for (auto& it : mapSerialHashes) {
CMintMeta meta = it.second;
if (meta.isUsed || meta.isArchived)
continue;
bool fConfirmed = ((meta.nHeight < chainActive.Height() - Params().Zerocoin_MintRequiredConfirmations()) && !(meta.nHeight == 0));
if (fConfirmedOnly && !fConfirmed)
continue;
if (fUnconfirmedOnly && fConfirmed)
continue;
nTotal += libzerocoin::ZerocoinDenominationToAmount(meta.denom);
myZerocoinSupply.at(meta.denom)++;
}
}
if (nTotal < 0 ) nTotal = 0; // Sanity never hurts
return nTotal;
}
CAmount CzSmncTracker::GetUnconfirmedBalance() const
{
return GetBalance(false, true);
}
std::vector<CMintMeta> CzSmncTracker::GetMints(bool fConfirmedOnly) const
{
std::vector<CMintMeta> vMints;
for (auto& it : mapSerialHashes) {
CMintMeta mint = it.second;
if (mint.isArchived || mint.isUsed)
continue;
bool fConfirmed = (mint.nHeight < chainActive.Height() - Params().Zerocoin_MintRequiredConfirmations());
if (fConfirmedOnly && !fConfirmed)
continue;
vMints.emplace_back(mint);
}
return vMints;
}
//Does a mint in the tracker have this txid
bool CzSmncTracker::HasMintTx(const uint256& txid)
{
for (auto it : mapSerialHashes) {
if (it.second.txid == txid)
return true;
}
return false;
}
bool CzSmncTracker::HasPubcoin(const CBigNum &bnValue) const
{
// Check if this mint's pubcoin value belongs to our mapSerialHashes (which includes hashpubcoin values)
uint256 hash = GetPubCoinHash(bnValue);
return HasPubcoinHash(hash);
}
bool CzSmncTracker::HasPubcoinHash(const uint256& hashPubcoin) const
{
for (auto it : mapSerialHashes) {
CMintMeta meta = it.second;
if (meta.hashPubcoin == hashPubcoin)
return true;
}
return false;
}
bool CzSmncTracker::HasSerial(const CBigNum& bnSerial) const
{
uint256 hash = GetSerialHash(bnSerial);
return HasSerialHash(hash);
}
bool CzSmncTracker::HasSerialHash(const uint256& hashSerial) const
{
auto it = mapSerialHashes.find(hashSerial);
return it != mapSerialHashes.end();
}
bool CzSmncTracker::UpdateZerocoinMint(const CZerocoinMint& mint)
{
if (!HasSerial(mint.GetSerialNumber()))
return error("%s: mint %s is not known", __func__, mint.GetValue().GetHex());
uint256 hashSerial = GetSerialHash(mint.GetSerialNumber());
//Update the meta object
CMintMeta meta = Get(hashSerial);
meta.isUsed = mint.IsUsed();
meta.denom = mint.GetDenomination();
meta.nHeight = mint.GetHeight();
mapSerialHashes.at(hashSerial) = meta;
//Write to db
return CWalletDB(strWalletFile).WriteZerocoinMint(mint);
}
bool CzSmncTracker::UpdateState(const CMintMeta& meta)
{
CWalletDB walletdb(strWalletFile);
if (meta.isDeterministic) {
CDeterministicMint dMint;
if (!walletdb.ReadDeterministicMint(meta.hashPubcoin, dMint)) {
// Check archive just in case
if (!meta.isArchived)
return error("%s: failed to read deterministic mint from database", __func__);
// Unarchive this mint since it is being requested and updated
if (!walletdb.UnarchiveDeterministicMint(meta.hashPubcoin, dMint))
return error("%s: failed to unarchive deterministic mint from database", __func__);
}
dMint.SetTxHash(meta.txid);
dMint.SetHeight(meta.nHeight);
dMint.SetUsed(meta.isUsed);
dMint.SetDenomination(meta.denom);
dMint.SetStakeHash(meta.hashStake);
if (!walletdb.WriteDeterministicMint(dMint))
return error("%s: failed to update deterministic mint when writing to db", __func__);
} else {
CZerocoinMint mint;
if (!walletdb.ReadZerocoinMint(meta.hashPubcoin, mint))
return error("%s: failed to read mint from database", __func__);
mint.SetTxHash(meta.txid);
mint.SetHeight(meta.nHeight);
mint.SetUsed(meta.isUsed);
mint.SetDenomination(meta.denom);
if (!walletdb.WriteZerocoinMint(mint))
return error("%s: failed to write mint to database", __func__);
}
mapSerialHashes[meta.hashSerial] = meta;
return true;
}
void CzSmncTracker::Add(const CDeterministicMint& dMint, bool isNew, bool isArchived, CzSmncWallet* zSmncWallet)
{
bool iszSmncWalletInitialized = (NULL != zSmncWallet);
CMintMeta meta;
meta.hashPubcoin = dMint.GetPubcoinHash();
meta.nHeight = dMint.GetHeight();
meta.nVersion = dMint.GetVersion();
meta.txid = dMint.GetTxHash();
meta.isUsed = dMint.IsUsed();
meta.hashSerial = dMint.GetSerialHash();
meta.hashStake = dMint.GetStakeHash();
meta.denom = dMint.GetDenomination();
meta.isArchived = isArchived;
meta.isDeterministic = true;
if (! iszSmncWalletInitialized)
zSmncWallet = new CzSmncWallet(strWalletFile);
meta.isSeedCorrect = zSmncWallet->CheckSeed(dMint);
if (! iszSmncWalletInitialized)
delete zSmncWallet;
mapSerialHashes[meta.hashSerial] = meta;
if (isNew)
CWalletDB(strWalletFile).WriteDeterministicMint(dMint);
}
void CzSmncTracker::Add(const CZerocoinMint& mint, bool isNew, bool isArchived)
{
CMintMeta meta;
meta.hashPubcoin = GetPubCoinHash(mint.GetValue());
meta.nHeight = mint.GetHeight();
meta.nVersion = libzerocoin::ExtractVersionFromSerial(mint.GetSerialNumber());
meta.txid = mint.GetTxHash();
meta.isUsed = mint.IsUsed();
meta.hashSerial = GetSerialHash(mint.GetSerialNumber());
uint256 nSerial = mint.GetSerialNumber().getuint256();
meta.hashStake = Hash(nSerial.begin(), nSerial.end());
meta.denom = mint.GetDenomination();
meta.isArchived = isArchived;
meta.isDeterministic = false;
meta.isSeedCorrect = true;
mapSerialHashes[meta.hashSerial] = meta;
if (isNew)
CWalletDB(strWalletFile).WriteZerocoinMint(mint);
}
void CzSmncTracker::SetPubcoinUsed(const uint256& hashPubcoin, const uint256& txid)
{
if (!HasPubcoinHash(hashPubcoin))
return;
CMintMeta meta = GetMetaFromPubcoin(hashPubcoin);
meta.isUsed = true;
mapPendingSpends.insert(std::make_pair(meta.hashSerial, txid));
UpdateState(meta);
}
void CzSmncTracker::SetPubcoinNotUsed(const uint256& hashPubcoin)
{
if (!HasPubcoinHash(hashPubcoin))
return;
CMintMeta meta = GetMetaFromPubcoin(hashPubcoin);
meta.isUsed = false;
if (mapPendingSpends.count(meta.hashSerial))
mapPendingSpends.erase(meta.hashSerial);
UpdateState(meta);
}
void CzSmncTracker::RemovePending(const uint256& txid)
{
uint256 hashSerial;
for (auto it : mapPendingSpends) {
if (it.second == txid) {
hashSerial = it.first;
break;
}
}
if (hashSerial > 0)
mapPendingSpends.erase(hashSerial);
}
bool CzSmncTracker::UpdateStatusInternal(const std::set<uint256>& setMempool, CMintMeta& mint)
{
//! Check whether this mint has been spent and is considered 'pending' or 'confirmed'
// If there is not a record of the block height, then look it up and assign it
uint256 txidMint;
bool isMintInChain = zerocoinDB->ReadCoinMint(mint.hashPubcoin, txidMint);
//See if there is internal record of spending this mint (note this is memory only, would reset on restart)
bool isPendingSpend = static_cast<bool>(mapPendingSpends.count(mint.hashSerial));
// See if there is a blockchain record of spending this mint
uint256 txidSpend;
bool isConfirmedSpend = zerocoinDB->ReadCoinSpend(mint.hashSerial, txidSpend);
// Double check the mempool for pending spend
if (isPendingSpend) {
uint256 txidPendingSpend = mapPendingSpends.at(mint.hashSerial);
if (!setMempool.count(txidPendingSpend) || isConfirmedSpend) {
RemovePending(txidPendingSpend);
isPendingSpend = false;
LogPrintf("%s : Pending txid %s removed because not in mempool\n", __func__, txidPendingSpend.GetHex());
}
}
bool isUsed = isPendingSpend || isConfirmedSpend;
if (!mint.nHeight || !isMintInChain || isUsed != mint.isUsed) {
CTransaction tx;
uint256 hashBlock;
// Txid will be marked 0 if there is no knowledge of the final tx hash yet
if (mint.txid == 0) {
if (!isMintInChain) {
LogPrintf("%s : Failed to find mint in zerocoinDB %s\n", __func__, mint.hashPubcoin.GetHex().substr(0, 6));
mint.isArchived = true;
Archive(mint);
return true;
}
mint.txid = txidMint;
}
if (setMempool.count(mint.txid))
return true;
// Check the transaction associated with this mint
if (!IsInitialBlockDownload() && !GetTransaction(mint.txid, tx, hashBlock, true)) {
LogPrintf("%s : Failed to find tx for mint txid=%s\n", __func__, mint.txid.GetHex());
mint.isArchived = true;
Archive(mint);
return true;
}
// An orphan tx if hashblock is in mapBlockIndex but not in chain active
if (mapBlockIndex.count(hashBlock) && !chainActive.Contains(mapBlockIndex.at(hashBlock))) {
LogPrintf("%s : Found orphaned mint txid=%s\n", __func__, mint.txid.GetHex());
mint.isUsed = false;
mint.nHeight = 0;
if (tx.IsCoinStake()) {
mint.isArchived = true;
Archive(mint);
}
return true;
}
// Check that the mint has correct used status
if (mint.isUsed != isUsed) {
LogPrintf("%s : Set mint %s isUsed to %d\n", __func__, mint.hashPubcoin.GetHex(), isUsed);
mint.isUsed = isUsed;
return true;
}
}
return false;
}
std::set<CMintMeta> CzSmncTracker::ListMints(bool fUnusedOnly, bool fMatureOnly, bool fUpdateStatus, bool fWrongSeed, bool fExcludeV1)
{
CWalletDB walletdb(strWalletFile);
if (fUpdateStatus) {
std::list<CZerocoinMint> listMintsDB = walletdb.ListMintedCoins();
for (auto& mint : listMintsDB)
Add(mint);
LogPrint("zero", "%s: added %d zerocoinmints from DB\n", __func__, listMintsDB.size());
std::list<CDeterministicMint> listDeterministicDB = walletdb.ListDeterministicMints();
CzSmncWallet* zSmncWallet = new CzSmncWallet(strWalletFile);
for (auto& dMint : listDeterministicDB) {
if (fExcludeV1 && dMint.GetVersion() < 2)
continue;
Add(dMint, false, false, zSmncWallet);
}
delete zSmncWallet;
LogPrint("zero", "%s: added %d dzsmnc from DB\n", __func__, listDeterministicDB.size());
}
std::vector<CMintMeta> vOverWrite;
std::set<CMintMeta> setMints;
std::set<uint256> setMempool;
{
LOCK(mempool.cs);
mempool.getTransactions(setMempool);
}
std::map<libzerocoin::CoinDenomination, int> mapMaturity = GetMintMaturityHeight();
for (auto& it : mapSerialHashes) {
CMintMeta mint = it.second;
//This is only intended for unarchived coins
if (mint.isArchived)
continue;
// Update the metadata of the mints if requested
if (fUpdateStatus && UpdateStatusInternal(setMempool, mint)) {
if (mint.isArchived)
continue;
// Mint was updated, queue for overwrite
vOverWrite.emplace_back(mint);
}
if (fUnusedOnly && mint.isUsed)
continue;
if (fMatureOnly) {
// Not confirmed
if (!mint.nHeight || mint.nHeight > chainActive.Height() - Params().Zerocoin_MintRequiredConfirmations())
continue;
if (mint.nHeight >= mapMaturity.at(mint.denom))
continue;
}
if (!fWrongSeed && !mint.isSeedCorrect)
continue;
setMints.insert(mint);
}
//overwrite any updates
for (CMintMeta& meta : vOverWrite)
UpdateState(meta);
return setMints;
}
void CzSmncTracker::Clear()
{
mapSerialHashes.clear();
}
| [
""
] | |
b7286eefaef2270be471b84bb41a7553d090ba3f | 84d7bb585ff0f94b796b32f0ae88e1bc371f8c33 | /GPCoursework/cSoundMgr.cpp | 998ebec24805e0dd860605ac8d06b36b71b7c65e | [] | no_license | bigfootone/GPCoursework | e7174389e026388985634aaa702b5e184cbfc2c1 | 22d684856cdf37fc8702182754c96d8e4f47cd4a | refs/heads/master | 2020-05-01T05:13:43.414814 | 2015-05-01T06:57:31 | 2015-05-01T06:57:31 | 34,892,680 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,846 | cpp | /*
==================================================================================
cSoundMgr.cpp
==================================================================================
*/
#include "cSoundMgr.h"
cSoundMgr* cSoundMgr::pInstance = NULL;
/*
=================================================================================
Constructor
=================================================================================
*/
cSoundMgr::cSoundMgr()
{
createContext();
}
/*
=================================================================================
Singleton Design Pattern
=================================================================================
*/
cSoundMgr* cSoundMgr::getInstance()
{
if (pInstance == NULL)
{
pInstance = new cSoundMgr();
}
return cSoundMgr::pInstance;
}
void cSoundMgr::createContext()
{
m_OALDevice = alcOpenDevice(NULL);
if (m_OALDevice)
{
//Create a context
m_OALContext = alcCreateContext(m_OALDevice, NULL);
//Set active context
alcMakeContextCurrent(m_OALContext);
}
}
void cSoundMgr::add(LPCSTR sndName, LPCSTR fileName)
{
if (!getSnd(sndName))
{
cSound * newSnd = new cSound();
newSnd->loadWAVFile(fileName);
gameSnds.insert(make_pair(sndName, newSnd));
}
}
cSound* cSoundMgr::getSnd(LPCSTR sndName)
{
map<LPCSTR, cSound*>::iterator snd = gameSnds.find(sndName);
if (snd != gameSnds.end())
{
return snd->second;
}
else
{
return NULL;
}
}
void cSoundMgr::deleteSnd()
{
for (map<LPCSTR, cSound*>::iterator snd = gameSnds.begin(); snd != gameSnds.end(); ++snd)
{
delete snd->second;
}
}
cSoundMgr::~cSoundMgr()
{
m_OALContext = alcGetCurrentContext();
//Get device for active context
m_OALDevice = alcGetContextsDevice(m_OALContext);
//Release context(s)
alcDestroyContext(m_OALContext);
//Close device
alcCloseDevice(m_OALDevice);
}
| [
"ps3bigfootone@gmail.com"
] | ps3bigfootone@gmail.com |
2222cd83f6145c49efba2294e2aec8e371b58d3d | 6c77cf237697f252d48b287ae60ccf61b3220044 | /aws-cpp-sdk-ec2/include/aws/ec2/model/ClassicLoadBalancer.h | 9f5fe95f90e8aaa3b56aad4281db8331b5697b63 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | Gohan/aws-sdk-cpp | 9a9672de05a96b89d82180a217ccb280537b9e8e | 51aa785289d9a76ac27f026d169ddf71ec2d0686 | refs/heads/master | 2020-03-26T18:48:43.043121 | 2018-11-09T08:44:41 | 2018-11-09T08:44:41 | 145,232,234 | 1 | 0 | Apache-2.0 | 2018-08-30T13:42:27 | 2018-08-18T15:42:39 | C++ | UTF-8 | C++ | false | false | 2,724 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Xml
{
class XmlNode;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{
/**
* <p>Describes a Classic Load Balancer.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ClassicLoadBalancer">AWS
* API Reference</a></p>
*/
class AWS_EC2_API ClassicLoadBalancer
{
public:
ClassicLoadBalancer();
ClassicLoadBalancer(const Aws::Utils::Xml::XmlNode& xmlNode);
ClassicLoadBalancer& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);
void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
void OutputToStream(Aws::OStream& oStream, const char* location) const;
/**
* <p>The name of the load balancer.</p>
*/
inline const Aws::String& GetName() const{ return m_name; }
/**
* <p>The name of the load balancer.</p>
*/
inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }
/**
* <p>The name of the load balancer.</p>
*/
inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }
/**
* <p>The name of the load balancer.</p>
*/
inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }
/**
* <p>The name of the load balancer.</p>
*/
inline ClassicLoadBalancer& WithName(const Aws::String& value) { SetName(value); return *this;}
/**
* <p>The name of the load balancer.</p>
*/
inline ClassicLoadBalancer& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}
/**
* <p>The name of the load balancer.</p>
*/
inline ClassicLoadBalancer& WithName(const char* value) { SetName(value); return *this;}
private:
Aws::String m_name;
bool m_nameHasBeenSet;
};
} // namespace Model
} // namespace EC2
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
5b1fb07385aea026ce95c11993afe4dfd400705d | a7764174fb0351ea666faa9f3b5dfe304390a011 | /inc/Standard_CString.hxx | c84a105a143bf6e49d0fe0c23482d4de3eabee8c | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,264 | hxx | //============================================================================
//==== Titre: Standard_CString.hxx
//==== Role : The headr file of primitve type "CString" from package "Standard"
//====
//==== Implementation: This is a primitive type implementadef with typedef
//==== typedef char* Standard_CString;
//============================================================================
#ifndef _Standard_CString_HeaderFile
# define _Standard_CString_HeaderFile
# ifndef _Standard_TypeDef_HeaderFile
# include <Standard_TypeDef.hxx>
# endif
# ifdef WNT
# define strcasecmp _stricmp
# endif
# include <string.h>
# ifndef _Standard_Integer_HeaderFile
# include <Standard_Integer.hxx>
# endif
class Handle_Standard_Type;
__Standard_API Handle_Standard_Type& Standard_CString_Type_();
inline Standard_Integer Abs (const Standard_Integer);
inline Standard_CString ShallowCopy (const Standard_CString Value);
inline Standard_Boolean IsSimilar(const Standard_CString One
,const Standard_CString Two);
inline Standard_Boolean IsEqual(const Standard_CString One
,const Standard_CString Two);
__Standard_API Standard_Integer HashCode (const Standard_CString,
const Standard_Integer);
inline Standard_Integer HashCode (const Standard_CString,
const Standard_Integer,
const Standard_Integer);
inline Standard_Integer HashCode (const Standard_CString,
const Standard_Integer ,
const Standard_Integer ,
Standard_Integer& );
Standard_Integer HashCodes (const Standard_CString ,
const Standard_Integer );
inline Standard_Boolean ISEQUAL(const Standard_CString One ,
const Standard_Integer LenOne ,
const Standard_CString Two,
const Standard_Integer LenTwo );
__Standard_API Standard_Boolean ISSIMILAR(const Standard_CString One ,
const Standard_Integer Len ,
const Standard_CString Two );
inline Standard_Integer HASHCODE (const Standard_CString,
const Standard_Integer,
const Standard_Integer);
inline Standard_Integer HASHCODE (const Standard_CString,
const Standard_Integer,
const Standard_Integer ,
Standard_Integer& );
__Standard_API Standard_Integer HASHCODES (const Standard_CString,
const Standard_Integer);
//============================================================================
//==== ShallowCopy: Returns a CString
//============================================================================
inline Standard_CString ShallowCopy (const Standard_CString Value)
{
return Value;
}
//============================================================================
//==== IsSimilar : Returns Standard_True if two booleans have the same value
//============================================================================
inline Standard_Boolean IsSimilar(const Standard_CString One
,const Standard_CString Two)
{
return (strcmp(One,Two) == 0);
}
//============================================================================
// IsEqual : Returns Standard_True if two CString have the same value
//============================================================================
inline Standard_Boolean IsEqual(const Standard_CString One
,const Standard_CString Two)
{
return (One == Two);
}
//============================================================================
//==== HashCode of CString. Returns the HashCode itself and
//==== the HashCode % Upper
//============================================================================
inline Standard_Integer HashCode (const Standard_CString Value,
const Standard_Integer Len ,
const Standard_Integer Upper ,
Standard_Integer& aHashCode )
{
aHashCode = HashCodes( Value , Len );
// return (Abs( aHashCode ) % Upper ) + 1 ;
return HashCode( (Standard_Integer)aHashCode , Upper ) ;
}
//============================================================================
//==== HashCode of CString. Returns the HashCode itself and
//==== the HashCode % Upper
//============================================================================
inline Standard_Integer HashCode (const Standard_CString Value,
const Standard_Integer Len ,
const Standard_Integer Upper )
{
// return (Abs( HashCodes( Value , Len ) ) % Upper ) + 1 ;
return HashCode( (Standard_Integer) HashCodes( Value , Len ) , Upper ) ;
}
//============================================================================
//==== HashCode of CString converted to uppercase. Returns the HashCode itself
//==== and the HashCode % Upper
//============================================================================
inline Standard_Integer HASHCODE (const Standard_CString Value,
const Standard_Integer Len ,
const Standard_Integer Upper ,
Standard_Integer& aHashCode )
{
aHashCode = HASHCODES( Value , Len );
// return (Abs( aHashCode ) % Upper ) + 1 ;
return HashCode( (Standard_Integer) aHashCode , Upper ) ;
}
//============================================================================
//==== HashCode of a CString converted to uppercase
//============================================================================
inline Standard_Integer HASHCODE (const Standard_CString Value,
const Standard_Integer Len ,
const Standard_Integer Upper)
{
// return (Abs( HASHCODES( Value , Len ) ) % Upper ) + 1 ;
return HashCode( (Standard_Integer) HASHCODES( Value , Len ) , Upper ) ;
}
//============================================================================
// IsEqual : Returns Standard_True if two CString have the same value
// Comparison is done with discard of bit 5 (UpperCase<-->LowerCase)
// Efficient for Types and MethodNames (without copy of characters)
// Valid if we have only alphanumeric characters and "_" (unicity)
// Valid if the Strings address are aligned for Integers
//============================================================================
inline Standard_Boolean ISEQUAL(const Standard_CString One ,
const Standard_Integer LenOne ,
const Standard_CString Two,
const Standard_Integer LenTwo )
{
if ( One == Two )
return Standard_True ;
if ( LenOne != LenTwo )
return Standard_False ;
return ISSIMILAR( One , LenOne , Two ) ;
}
#endif
| [
"shoka.sho2@excel.co.jp"
] | shoka.sho2@excel.co.jp |
8bd53abdacb53e2e3684953c93b72a60144d740c | 86d4e5dd50cd5eac55819f89dd29ba346724868e | /ON_OLYMPIC/VMYT.cpp | 2111356c511693788bfb7c5ff3cb00d42778b0b4 | [] | no_license | ppkhang285/C-Codes | e074b1a184c975499d013e47eaceb371ee5dfa80 | 341a4e83a16a791f5fe2e4cc46c2a27107b59cfd | refs/heads/master | 2023-01-12T13:44:45.694680 | 2020-11-14T08:12:43 | 2020-11-14T08:12:43 | 294,895,942 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | cpp | #include <bits/stdc++.h>
#define task "VMYT"
#define REP(i,a,b) for(int i = a; i<=b; ++i)
#define module 1000000007
using namespace std;
int n,a[100000],k;
int main(){
freopen(task".inp","r",stdin);
freopen(task".out","w",stdout);
cin>>n>>k;
REP(i,1,k) cin>>a[i];
a[0] = 1;
if ( n<=k) cout<<a[n];
else{
a[k+1] = 1;
REP(i,1,k) a[k+1]*=a[i];
REP(i,k+2,n) a[i] = ( ((a[i-1] %module) * (a[i-1]%module)) /a[i-k-1]) %module;
cout<<a[n];
}
return 0;
}
| [
"ppkhang285@gmail.com"
] | ppkhang285@gmail.com |
8e2420f9dde1a15666f63cd5c1b1f1aa2a1b6e15 | 2a8ffc30cfb70a8e77c771eb9981c0115d39a2f1 | /whs1_client/MyForm.h | 84e27e3399e3460d7f0b7464c8b18bb1a0fc1375 | [] | no_license | irvs/whs1_client | 0d39eae1c44d23b806857a9a9050df3fc3a65d6f | dda2c409abbcd87112829aacc1dfd8f633131a60 | refs/heads/master | 2021-01-10T23:53:04.559103 | 2016-10-14T08:30:22 | 2016-10-14T08:30:22 | 70,769,129 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 29,293 | h | #ifndef MYFORM_H_
#define MYFORM_H_
#include <msclr/marshal.h>
#include "whs1.h"
#include "socket.h"
namespace WHS1_test {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace msclr::interop;
/// <summary>
/// MyForm の概要
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: ここにコンストラクター コードを追加します
//
}
protected:
/// <summary>
/// 使用中のリソースをすべてクリーンアップします。
/// </summary>
~MyForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Button^ button2;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Button^ button3;
private: System::Windows::Forms::Button^ button4;
private: System::Windows::Forms::Button^ button5;
private: System::Windows::Forms::Button^ button6;
private: System::Windows::Forms::GroupBox^ groupBox1;
private: System::Windows::Forms::TextBox^ textBox2;
private: System::Windows::Forms::TextBox^ textBox3;
private: System::Windows::Forms::Label^ label3;
private: System::Windows::Forms::Label^ label4;
private: System::Windows::Forms::Timer^ timer1;
private: System::Windows::Forms::TextBox^ textBox1;
private: System::Windows::Forms::DataVisualization::Charting::Chart^ chart1;
private: System::Windows::Forms::CheckBox^ checkBox1;
private: System::Windows::Forms::GroupBox^ groupBox2;
private: System::Windows::Forms::Button^ button7;
private: System::Windows::Forms::TextBox^ textBox8;
private: System::Windows::Forms::Label^ label6;
private: System::Windows::Forms::Label^ label5;
private: System::Windows::Forms::TextBox^ textBox7;
private: System::Windows::Forms::TextBox^ textBox6;
private: System::Windows::Forms::TextBox^ textBox5;
private: System::Windows::Forms::TextBox^ textBox4;
private: System::Windows::Forms::DataVisualization::Charting::Chart^ chart2;
private: System::Windows::Forms::Label^ label7;
private: System::Windows::Forms::TextBox^ textBox9;
private: System::Windows::Forms::Label^ label8;
private: System::Windows::Forms::TextBox^ textBox10;
private: System::Windows::Forms::TextBox^ textBox11;
private: System::Windows::Forms::Label^ label9;
private: System::Windows::Forms::TextBox^ textBox12;
private: System::Windows::Forms::Label^ label10;
private: System::ComponentModel::IContainer^ components;
protected:
private:
/// <summary>
/// 必要なデザイナー変数です。
/// </summary>
#pragma region Windows Form Designer generated code
/// <summary>
/// デザイナー サポートに必要なメソッドです。このメソッドの内容を
/// コード エディターで変更しないでください。
/// </summary>
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
System::Windows::Forms::DataVisualization::Charting::ChartArea^ chartArea1 = (gcnew System::Windows::Forms::DataVisualization::Charting::ChartArea());
System::Windows::Forms::DataVisualization::Charting::Legend^ legend1 = (gcnew System::Windows::Forms::DataVisualization::Charting::Legend());
System::Windows::Forms::DataVisualization::Charting::Series^ series1 = (gcnew System::Windows::Forms::DataVisualization::Charting::Series());
System::Windows::Forms::DataVisualization::Charting::DataPoint^ dataPoint1 = (gcnew System::Windows::Forms::DataVisualization::Charting::DataPoint(0,
500));
System::Windows::Forms::DataVisualization::Charting::DataPoint^ dataPoint2 = (gcnew System::Windows::Forms::DataVisualization::Charting::DataPoint(100,
800));
System::Windows::Forms::DataVisualization::Charting::DataPoint^ dataPoint3 = (gcnew System::Windows::Forms::DataVisualization::Charting::DataPoint(200,
200));
System::Windows::Forms::DataVisualization::Charting::DataPoint^ dataPoint4 = (gcnew System::Windows::Forms::DataVisualization::Charting::DataPoint(300,
500));
System::Windows::Forms::DataVisualization::Charting::DataPoint^ dataPoint5 = (gcnew System::Windows::Forms::DataVisualization::Charting::DataPoint(400,
800));
System::Windows::Forms::DataVisualization::Charting::DataPoint^ dataPoint6 = (gcnew System::Windows::Forms::DataVisualization::Charting::DataPoint(500,
300));
System::Windows::Forms::DataVisualization::Charting::ChartArea^ chartArea2 = (gcnew System::Windows::Forms::DataVisualization::Charting::ChartArea());
System::Windows::Forms::DataVisualization::Charting::Legend^ legend2 = (gcnew System::Windows::Forms::DataVisualization::Charting::Legend());
System::Windows::Forms::DataVisualization::Charting::Series^ series2 = (gcnew System::Windows::Forms::DataVisualization::Charting::Series());
System::Windows::Forms::DataVisualization::Charting::DataPoint^ dataPoint7 = (gcnew System::Windows::Forms::DataVisualization::Charting::DataPoint(0,
500));
System::Windows::Forms::DataVisualization::Charting::DataPoint^ dataPoint8 = (gcnew System::Windows::Forms::DataVisualization::Charting::DataPoint(100,
800));
System::Windows::Forms::DataVisualization::Charting::DataPoint^ dataPoint9 = (gcnew System::Windows::Forms::DataVisualization::Charting::DataPoint(200,
200));
System::Windows::Forms::DataVisualization::Charting::DataPoint^ dataPoint10 = (gcnew System::Windows::Forms::DataVisualization::Charting::DataPoint(300,
500));
System::Windows::Forms::DataVisualization::Charting::DataPoint^ dataPoint11 = (gcnew System::Windows::Forms::DataVisualization::Charting::DataPoint(400,
800));
System::Windows::Forms::DataVisualization::Charting::DataPoint^ dataPoint12 = (gcnew System::Windows::Forms::DataVisualization::Charting::DataPoint(500,
300));
this->button1 = (gcnew System::Windows::Forms::Button());
this->label1 = (gcnew System::Windows::Forms::Label());
this->button2 = (gcnew System::Windows::Forms::Button());
this->label2 = (gcnew System::Windows::Forms::Label());
this->button3 = (gcnew System::Windows::Forms::Button());
this->button4 = (gcnew System::Windows::Forms::Button());
this->button5 = (gcnew System::Windows::Forms::Button());
this->button6 = (gcnew System::Windows::Forms::Button());
this->groupBox1 = (gcnew System::Windows::Forms::GroupBox());
this->textBox1 = (gcnew System::Windows::Forms::TextBox());
this->textBox2 = (gcnew System::Windows::Forms::TextBox());
this->textBox3 = (gcnew System::Windows::Forms::TextBox());
this->label3 = (gcnew System::Windows::Forms::Label());
this->label4 = (gcnew System::Windows::Forms::Label());
this->timer1 = (gcnew System::Windows::Forms::Timer(this->components));
this->chart1 = (gcnew System::Windows::Forms::DataVisualization::Charting::Chart());
this->checkBox1 = (gcnew System::Windows::Forms::CheckBox());
this->groupBox2 = (gcnew System::Windows::Forms::GroupBox());
this->button7 = (gcnew System::Windows::Forms::Button());
this->textBox8 = (gcnew System::Windows::Forms::TextBox());
this->label6 = (gcnew System::Windows::Forms::Label());
this->label5 = (gcnew System::Windows::Forms::Label());
this->textBox7 = (gcnew System::Windows::Forms::TextBox());
this->textBox6 = (gcnew System::Windows::Forms::TextBox());
this->textBox5 = (gcnew System::Windows::Forms::TextBox());
this->textBox4 = (gcnew System::Windows::Forms::TextBox());
this->chart2 = (gcnew System::Windows::Forms::DataVisualization::Charting::Chart());
this->label7 = (gcnew System::Windows::Forms::Label());
this->textBox9 = (gcnew System::Windows::Forms::TextBox());
this->label8 = (gcnew System::Windows::Forms::Label());
this->textBox10 = (gcnew System::Windows::Forms::TextBox());
this->textBox11 = (gcnew System::Windows::Forms::TextBox());
this->label9 = (gcnew System::Windows::Forms::Label());
this->textBox12 = (gcnew System::Windows::Forms::TextBox());
this->label10 = (gcnew System::Windows::Forms::Label());
this->groupBox1->SuspendLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->chart1))->BeginInit();
this->groupBox2->SuspendLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->chart2))->BeginInit();
this->SuspendLayout();
//
// button1
//
this->button1->Location = System::Drawing::Point(12, 16);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(75, 23);
this->button1->TabIndex = 0;
this->button1->Text = L"open";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click);
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(93, 22);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(31, 12);
this->label1->TabIndex = 1;
this->label1->Text = L"state";
//
// button2
//
this->button2->Location = System::Drawing::Point(12, 52);
this->button2->Name = L"button2";
this->button2->Size = System::Drawing::Size(75, 23);
this->button2->TabIndex = 2;
this->button2->Text = L"close";
this->button2->UseVisualStyleBackColor = true;
this->button2->Click += gcnew System::EventHandler(this, &MyForm::button2_Click);
//
// label2
//
this->label2->AutoSize = true;
this->label2->Location = System::Drawing::Point(93, 58);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(31, 12);
this->label2->TabIndex = 3;
this->label2->Text = L"state";
//
// button3
//
this->button3->Location = System::Drawing::Point(12, 90);
this->button3->Name = L"button3";
this->button3->Size = System::Drawing::Size(75, 23);
this->button3->TabIndex = 4;
this->button3->Text = L"受信開始";
this->button3->UseVisualStyleBackColor = true;
this->button3->Click += gcnew System::EventHandler(this, &MyForm::button3_Click);
//
// button4
//
this->button4->Location = System::Drawing::Point(95, 90);
this->button4->Name = L"button4";
this->button4->Size = System::Drawing::Size(75, 23);
this->button4->TabIndex = 5;
this->button4->Text = L"受信終了";
this->button4->UseVisualStyleBackColor = true;
this->button4->Click += gcnew System::EventHandler(this, &MyForm::button4_Click);
//
// button5
//
this->button5->Location = System::Drawing::Point(151, 14);
this->button5->Name = L"button5";
this->button5->Size = System::Drawing::Size(77, 23);
this->button5->TabIndex = 6;
this->button5->Text = L"取得";
this->button5->UseVisualStyleBackColor = true;
this->button5->Click += gcnew System::EventHandler(this, &MyForm::button5_Click);
//
// button6
//
this->button6->Location = System::Drawing::Point(151, 42);
this->button6->Name = L"button6";
this->button6->Size = System::Drawing::Size(77, 23);
this->button6->TabIndex = 7;
this->button6->Text = L"設定";
this->button6->UseVisualStyleBackColor = true;
this->button6->Click += gcnew System::EventHandler(this, &MyForm::button6_Click);
//
// groupBox1
//
this->groupBox1->Controls->Add(this->textBox1);
this->groupBox1->Controls->Add(this->button6);
this->groupBox1->Controls->Add(this->button5);
this->groupBox1->Location = System::Drawing::Point(244, 7);
this->groupBox1->Name = L"groupBox1";
this->groupBox1->Size = System::Drawing::Size(236, 72);
this->groupBox1->TabIndex = 9;
this->groupBox1->TabStop = false;
this->groupBox1->Text = L"受信機アドレス";
this->groupBox1->Enter += gcnew System::EventHandler(this, &MyForm::groupBox1_Enter);
//
// textBox1
//
this->textBox1->Location = System::Drawing::Point(7, 31);
this->textBox1->Name = L"textBox1";
this->textBox1->Size = System::Drawing::Size(125, 19);
this->textBox1->TabIndex = 8;
this->textBox1->Text = L"0020003798";
//
// textBox2
//
this->textBox2->Location = System::Drawing::Point(72, 133);
this->textBox2->Name = L"textBox2";
this->textBox2->Size = System::Drawing::Size(47, 19);
this->textBox2->TabIndex = 10;
//
// textBox3
//
this->textBox3->Location = System::Drawing::Point(177, 133);
this->textBox3->Name = L"textBox3";
this->textBox3->Size = System::Drawing::Size(47, 19);
this->textBox3->TabIndex = 11;
//
// label3
//
this->label3->AutoSize = true;
this->label3->Location = System::Drawing::Point(13, 136);
this->label3->Name = L"label3";
this->label3->Size = System::Drawing::Size(53, 12);
this->label3->TabIndex = 12;
this->label3->Text = L"心拍波形";
//
// label4
//
this->label4->AutoSize = true;
this->label4->Location = System::Drawing::Point(130, 136);
this->label4->Name = L"label4";
this->label4->Size = System::Drawing::Size(41, 12);
this->label4->TabIndex = 13;
this->label4->Text = L"体表温";
//
// timer1
//
this->timer1->Enabled = true;
this->timer1->Tick += gcnew System::EventHandler(this, &MyForm::timer1_Tick);
//
// chart1
//
chartArea1->AxisX->Crossing = 1.7976931348623157E+308;
chartArea1->AxisX->LabelStyle->Enabled = false;
chartArea1->AxisX->LineColor = System::Drawing::Color::DarkGray;
chartArea1->AxisX->MajorGrid->LineColor = System::Drawing::Color::DarkGray;
chartArea1->AxisX->MajorTickMark->Enabled = false;
chartArea1->AxisX->Maximum = 500;
chartArea1->AxisX->Minimum = 0;
chartArea1->AxisX->MinorGrid->Enabled = true;
chartArea1->AxisX->MinorGrid->LineColor = System::Drawing::Color::DarkGray;
chartArea1->AxisX->TitleForeColor = System::Drawing::Color::DarkGray;
chartArea1->AxisY->LabelStyle->Enabled = false;
chartArea1->AxisY->LineColor = System::Drawing::Color::DarkGray;
chartArea1->AxisY->MajorGrid->LineColor = System::Drawing::Color::DarkGray;
chartArea1->AxisY->MajorTickMark->Enabled = false;
chartArea1->AxisY->Maximum = 1000;
chartArea1->AxisY->Minimum = 0;
chartArea1->AxisY->TitleForeColor = System::Drawing::Color::DarkGray;
chartArea1->BorderColor = System::Drawing::Color::DarkGray;
chartArea1->Name = L"ChartArea1";
this->chart1->ChartAreas->Add(chartArea1);
legend1->Enabled = false;
legend1->Name = L"Legend1";
legend1->TextWrapThreshold = 0;
this->chart1->Legends->Add(legend1);
this->chart1->Location = System::Drawing::Point(12, 162);
this->chart1->Name = L"chart1";
series1->ChartArea = L"ChartArea1";
series1->ChartType = System::Windows::Forms::DataVisualization::Charting::SeriesChartType::Line;
series1->Legend = L"Legend1";
series1->Name = L"Series1";
series1->Points->Add(dataPoint1);
series1->Points->Add(dataPoint2);
series1->Points->Add(dataPoint3);
series1->Points->Add(dataPoint4);
series1->Points->Add(dataPoint5);
series1->Points->Add(dataPoint6);
series1->XValueType = System::Windows::Forms::DataVisualization::Charting::ChartValueType::UInt32;
series1->YValueType = System::Windows::Forms::DataVisualization::Charting::ChartValueType::UInt32;
this->chart1->Series->Add(series1);
this->chart1->Size = System::Drawing::Size(468, 113);
this->chart1->TabIndex = 15;
this->chart1->Text = L"chart1";
this->chart1->Click += gcnew System::EventHandler(this, &MyForm::chart1_Click_1);
//
// checkBox1
//
this->checkBox1->AutoSize = true;
this->checkBox1->Location = System::Drawing::Point(182, 49);
this->checkBox1->Name = L"checkBox1";
this->checkBox1->Size = System::Drawing::Size(48, 16);
this->checkBox1->TabIndex = 16;
this->checkBox1->Text = L"送信";
this->checkBox1->UseVisualStyleBackColor = true;
this->checkBox1->CheckedChanged += gcnew System::EventHandler(this, &MyForm::checkBox1_CheckedChanged);
//
// groupBox2
//
this->groupBox2->Controls->Add(this->button7);
this->groupBox2->Controls->Add(this->textBox8);
this->groupBox2->Controls->Add(this->label6);
this->groupBox2->Controls->Add(this->label5);
this->groupBox2->Controls->Add(this->textBox7);
this->groupBox2->Controls->Add(this->textBox6);
this->groupBox2->Controls->Add(this->textBox5);
this->groupBox2->Controls->Add(this->textBox4);
this->groupBox2->Controls->Add(this->checkBox1);
this->groupBox2->Location = System::Drawing::Point(244, 85);
this->groupBox2->Name = L"groupBox2";
this->groupBox2->Size = System::Drawing::Size(236, 71);
this->groupBox2->TabIndex = 17;
this->groupBox2->TabStop = false;
this->groupBox2->Text = L"ソケット";
//
// button7
//
this->button7->Location = System::Drawing::Point(119, 44);
this->button7->Name = L"button7";
this->button7->Size = System::Drawing::Size(57, 23);
this->button7->TabIndex = 24;
this->button7->Text = L"設定";
this->button7->UseVisualStyleBackColor = true;
this->button7->Click += gcnew System::EventHandler(this, &MyForm::button7_Click);
//
// textBox8
//
this->textBox8->Location = System::Drawing::Point(66, 46);
this->textBox8->Name = L"textBox8";
this->textBox8->Size = System::Drawing::Size(47, 19);
this->textBox8->TabIndex = 23;
this->textBox8->Text = L"65001";
//
// label6
//
this->label6->AutoSize = true;
this->label6->Location = System::Drawing::Point(6, 50);
this->label6->Name = L"label6";
this->label6->Size = System::Drawing::Size(57, 12);
this->label6->TabIndex = 22;
this->label6->Text = L"ポート番号";
//
// label5
//
this->label5->AutoSize = true;
this->label5->Location = System::Drawing::Point(6, 25);
this->label5->Name = L"label5";
this->label5->Size = System::Drawing::Size(51, 12);
this->label5->TabIndex = 21;
this->label5->Text = L"IPアドレス";
//
// textBox7
//
this->textBox7->Location = System::Drawing::Point(190, 21);
this->textBox7->Name = L"textBox7";
this->textBox7->Size = System::Drawing::Size(38, 19);
this->textBox7->TabIndex = 20;
this->textBox7->Text = L"170";
//
// textBox6
//
this->textBox6->Location = System::Drawing::Point(146, 21);
this->textBox6->Name = L"textBox6";
this->textBox6->Size = System::Drawing::Size(38, 19);
this->textBox6->TabIndex = 19;
this->textBox6->Text = L"4";
//
// textBox5
//
this->textBox5->Location = System::Drawing::Point(103, 21);
this->textBox5->Name = L"textBox5";
this->textBox5->Size = System::Drawing::Size(38, 19);
this->textBox5->TabIndex = 18;
this->textBox5->Text = L"168";
//
// textBox4
//
this->textBox4->Location = System::Drawing::Point(59, 22);
this->textBox4->Name = L"textBox4";
this->textBox4->Size = System::Drawing::Size(38, 19);
this->textBox4->TabIndex = 17;
this->textBox4->Text = L"192";
//
// chart2
//
chartArea2->AxisX->Crossing = 1.7976931348623157E+308;
chartArea2->AxisX->LabelStyle->Enabled = false;
chartArea2->AxisX->LineColor = System::Drawing::Color::DarkGray;
chartArea2->AxisX->MajorGrid->LineColor = System::Drawing::Color::DarkGray;
chartArea2->AxisX->MajorTickMark->Enabled = false;
chartArea2->AxisX->Maximum = 500;
chartArea2->AxisX->Minimum = 0;
chartArea2->AxisX->MinorGrid->Enabled = true;
chartArea2->AxisX->MinorGrid->LineColor = System::Drawing::Color::DarkGray;
chartArea2->AxisX->TitleForeColor = System::Drawing::Color::DarkGray;
chartArea2->AxisY->LabelStyle->Enabled = false;
chartArea2->AxisY->LineColor = System::Drawing::Color::DarkGray;
chartArea2->AxisY->MajorGrid->LineColor = System::Drawing::Color::DarkGray;
chartArea2->AxisY->MajorTickMark->Enabled = false;
chartArea2->AxisY->Maximum = 4;
chartArea2->AxisY->Minimum = -1;
chartArea2->AxisY->TitleForeColor = System::Drawing::Color::DarkGray;
chartArea2->BorderColor = System::Drawing::Color::DarkGray;
chartArea2->Name = L"ChartArea1";
this->chart2->ChartAreas->Add(chartArea2);
legend2->Enabled = false;
legend2->Name = L"Legend1";
legend2->TextWrapThreshold = 0;
this->chart2->Legends->Add(legend2);
this->chart2->Location = System::Drawing::Point(12, 309);
this->chart2->Name = L"chart2";
series2->ChartArea = L"ChartArea1";
series2->ChartType = System::Windows::Forms::DataVisualization::Charting::SeriesChartType::Line;
series2->Legend = L"Legend1";
series2->Name = L"Series1";
series2->Points->Add(dataPoint7);
series2->Points->Add(dataPoint8);
series2->Points->Add(dataPoint9);
series2->Points->Add(dataPoint10);
series2->Points->Add(dataPoint11);
series2->Points->Add(dataPoint12);
series2->XValueType = System::Windows::Forms::DataVisualization::Charting::ChartValueType::UInt32;
series2->YValueType = System::Windows::Forms::DataVisualization::Charting::ChartValueType::UInt32;
this->chart2->Series->Add(series2);
this->chart2->Size = System::Drawing::Size(468, 113);
this->chart2->TabIndex = 18;
this->chart2->Text = L"chart2";
//
// label7
//
this->label7->AutoSize = true;
this->label7->Location = System::Drawing::Point(37, 287);
this->label7->Name = L"label7";
this->label7->Size = System::Drawing::Size(29, 12);
this->label7->TabIndex = 19;
this->label7->Text = L"体動";
//
// textBox9
//
this->textBox9->Location = System::Drawing::Point(72, 284);
this->textBox9->Name = L"textBox9";
this->textBox9->Size = System::Drawing::Size(47, 19);
this->textBox9->TabIndex = 20;
//
// label8
//
this->label8->AutoSize = true;
this->label8->Location = System::Drawing::Point(130, 287);
this->label8->Name = L"label8";
this->label8->Size = System::Drawing::Size(40, 12);
this->label8->TabIndex = 21;
this->label8->Text = L"ACC_X";
//
// textBox10
//
this->textBox10->Location = System::Drawing::Point(177, 284);
this->textBox10->Name = L"textBox10";
this->textBox10->Size = System::Drawing::Size(47, 19);
this->textBox10->TabIndex = 22;
//
// textBox11
//
this->textBox11->Location = System::Drawing::Point(282, 284);
this->textBox11->Name = L"textBox11";
this->textBox11->Size = System::Drawing::Size(47, 19);
this->textBox11->TabIndex = 24;
//
// label9
//
this->label9->AutoSize = true;
this->label9->Location = System::Drawing::Point(235, 287);
this->label9->Name = L"label9";
this->label9->Size = System::Drawing::Size(40, 12);
this->label9->TabIndex = 23;
this->label9->Text = L"ACC_Y";
//
// textBox12
//
this->textBox12->Location = System::Drawing::Point(388, 284);
this->textBox12->Name = L"textBox12";
this->textBox12->Size = System::Drawing::Size(47, 19);
this->textBox12->TabIndex = 26;
//
// label10
//
this->label10->AutoSize = true;
this->label10->Location = System::Drawing::Point(341, 287);
this->label10->Name = L"label10";
this->label10->Size = System::Drawing::Size(40, 12);
this->label10->TabIndex = 25;
this->label10->Text = L"ACC_Z";
//
// MyForm
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 12);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(492, 431);
this->Controls->Add(this->textBox12);
this->Controls->Add(this->label10);
this->Controls->Add(this->textBox11);
this->Controls->Add(this->label9);
this->Controls->Add(this->textBox10);
this->Controls->Add(this->label8);
this->Controls->Add(this->textBox9);
this->Controls->Add(this->label7);
this->Controls->Add(this->chart2);
this->Controls->Add(this->groupBox2);
this->Controls->Add(this->chart1);
this->Controls->Add(this->label4);
this->Controls->Add(this->label3);
this->Controls->Add(this->textBox3);
this->Controls->Add(this->textBox2);
this->Controls->Add(this->groupBox1);
this->Controls->Add(this->button4);
this->Controls->Add(this->button3);
this->Controls->Add(this->label2);
this->Controls->Add(this->button2);
this->Controls->Add(this->label1);
this->Controls->Add(this->button1);
this->Name = L"MyForm";
this->Text = L"WHS-1 test";
this->Load += gcnew System::EventHandler(this, &MyForm::MyForm_Load);
this->groupBox1->ResumeLayout(false);
this->groupBox1->PerformLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->chart1))->EndInit();
this->groupBox2->ResumeLayout(false);
this->groupBox2->PerformLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->chart2))->EndInit();
this->ResumeLayout(false);
this->PerformLayout();
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
char *s = rrd.open();
String^ msg = gcnew String(s);
label1->Text = msg;
}
private: System::Void MyForm_Load(System::Object^ sender, System::EventArgs^ e) {
chart1->Series->Clear();
chart1->Series->Add("hakei");
chart1->Series["hakei"]->ChartType = System::Windows::Forms::DataVisualization::Charting::SeriesChartType::Line;
chart1->Series["hakei"]->Color = Color::LightGreen;
chart2->Series->Clear();
chart2->Series->Add("motion");
chart2->Series["motion"]->ChartType = System::Windows::Forms::DataVisualization::Charting::SeriesChartType::Line;
chart2->Series["motion"]->Color = Color::LightSkyBlue;
int ip[4];
ip[0] = Convert::ToInt32(textBox4->Text);
ip[1] = Convert::ToInt32(textBox5->Text);
ip[2] = Convert::ToInt32(textBox6->Text);
ip[3] = Convert::ToInt32(textBox7->Text);
int port;
port = Convert::ToInt32(textBox8->Text);
if (!sock.Prepare(port, sock.IPitoc4(ip[0], ip[1], ip[2], ip[3]))){
MessageBox::Show("ソケット失敗");
}
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
char *s = rrd.close();
String^ msg = gcnew String(s);
label2->Text = msg;
}
private: System::Void groupBox1_Enter(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void button5_Click(System::Object^ sender, System::EventArgs^ e) {
if (rrd.get_address()) {
String^ address = gcnew String(rrd.address);
textBox1->Text = address;
}
else{
MessageBox::Show("失敗しました");
}
}
private: System::Void button6_Click(System::Object^ sender, System::EventArgs^ e) {
String^ str = textBox1->Text;
const char* ptr;
marshal_context^ mycontext = gcnew marshal_context();
ptr = mycontext->marshal_as<const char*>(str);
rrd.set_address((char*)ptr);
}
private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) {
rrd.start();
}
private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) {
rrd.stop();
}
private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e) {
if (rrd.is_received){
textBox2->Text = rrd.hakei[rrd.now_count-1].ToString();
textBox3->Text = rrd.temp[rrd.now_count-1].ToString("F");
textBox9->Text = rrd.motion[rrd.now_count - 1].ToString("F");
textBox10->Text = rrd.acc_x[rrd.now_count - 1].ToString("F");
textBox11->Text = rrd.acc_y[rrd.now_count - 1].ToString("F");
textBox12->Text = rrd.acc_z[rrd.now_count - 1].ToString("F");
chart1->Series["hakei"]->Points->Clear();
chart2->Series["motion"]->Points->Clear();
for (int i = 0; i < MAX_DATA; i++){
int k = i;
if (rrd.now_count - 1 - k < 0) k -= MAX_DATA;
if (rrd.hakei[rrd.now_count - 1 - k]!=0) chart1->Series["hakei"]->Points->AddXY(MAX_DATA-i, rrd.hakei[rrd.now_count-1-k]);
if (rrd.motion[rrd.now_count - 1 - k]!=0) chart2->Series["motion"]->Points->AddXY(MAX_DATA-i, rrd.motion[rrd.now_count-1-k]);
}
}
}
private: System::Void chart1_Click(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void groupBox2_Enter(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void button7_Click(System::Object^ sender, System::EventArgs^ e) {
int ip[4];
ip[0] = Convert::ToInt32(textBox4->Text);
ip[1] = Convert::ToInt32(textBox5->Text);
ip[2] = Convert::ToInt32(textBox6->Text);
ip[3] = Convert::ToInt32(textBox7->Text);
int port;
port = Convert::ToInt32(textBox8->Text);
if (!sock.Prepare(port, sock.IPitoc4(ip[0], ip[1], ip[2], ip[3]))){
MessageBox::Show("ソケット失敗");
}
else{
MessageBox::Show("設定しました");
}
}
private: System::Void checkBox1_CheckedChanged(System::Object^ sender, System::EventArgs^ e) {
if (checkBox1->Checked == true) rrd.send_flag = true;
else rrd.send_flag = false;
}
private: System::Void button8_Click(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void chart1_Click_1(System::Object^ sender, System::EventArgs^ e) {
}
};
}
#endif | [
"sakamoto@irvs.ait.kyushu-u.ac.jp"
] | sakamoto@irvs.ait.kyushu-u.ac.jp |
7ec309189f9d3665a2b5847f216a0a4d996443ef | b43ce540528598d96855e8218ae6857ec6d21858 | /DIrectX11_3D/IMBO_MAINFRAME/DebugRenderContainer.cpp | 1b48b9e549a65d3f4938a437e0bf5f0bc3f3a9b6 | [] | no_license | costa0217/portfolio_codes | db249293ae1e662753c1f9e8f5f0067464165a16 | c52cb36a84ef10e6c7680b34fc12872f4361a027 | refs/heads/master | 2020-03-28T08:01:47.715789 | 2018-09-08T14:44:51 | 2018-09-08T14:44:51 | 147,941,305 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,531 | cpp | #include "stdafx.h"
#include "DebugRenderContainer.h"
//--------------------------container---------------------------------
void CDebugRenderContainer::UpdateShaderState( CCamera* pCamera) {
if (m_vpBuffer.empty()) return;
m_vpMesh[0]->UpdateShaderState();
m_pShader->UpdateShaderState();
for (auto p : m_vpTexture) {
p->UpdateShaderState();
}
for (auto p : m_vpMaterial) {
//p->UpdateShaderState();
}
for (auto p : m_vpBuffer) {
p->UpdateShaderState();
}
//if (m_pGlobalBuffer) m_pGlobalBuffer->UpdateShaderState();
//----------------------------update instance buffer--------------------------
int nInstance = 0;
int nBuffer = 0;
//map
size_t vecSize = m_vpBuffer.size();
for (size_t i = 0; i < vecSize; ++i)
{
m_ppBufferData[nBuffer++] = m_vpBuffer[i]->Map();
}
//for (auto p : m_vpBuffer) {
// m_ppBufferData[nBuffer++] = p->Map();
//}
vecSize = m_lpObjects.size();
for (size_t i = 0; i < vecSize; ++i)
{
m_lpObjects[i]->SetBufferInfo(m_ppBufferData, nInstance, pCamera);
nInstance++;
}
/*for (auto pObject : m_lpObjects) {
pObject->SetBufferInfo(m_ppBufferData, nInstance, pCamera);
nInstance++;
}*/
//unmap
vecSize = m_vpBuffer.size();
for (size_t i = 0; i < vecSize; ++i)
{
m_vpBuffer[i]->Unmap();
}
//for (auto p : m_vpBuffer) {
// p->Unmap();
//}
//----------------------------update instance buffer--------------------------
}
CDebugRenderContainer::CDebugRenderContainer() : CRenderContainer() {
}
CDebugRenderContainer::~CDebugRenderContainer() {
} | [
"choga0217@gmail.com"
] | choga0217@gmail.com |
d679922c1db66345a34ca88d506cc949fdea7e4f | a586699434fe7f563c2004a755a7d108d743bf9b | /IMC/Spec/WaterDensity.hpp | 25a29b06b3d16f9e3aaf5af4d1608ed7872fe66e | [] | no_license | nikkone/ho5_imc_ttk22 | 73394d6c70ef72175f236d0371f411a74b3081dc | 046b587b54530236c24817c34c35f8d5745106d2 | refs/heads/master | 2020-07-12T21:54:21.564794 | 2019-08-28T11:26:23 | 2019-08-28T11:26:23 | 204,915,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,035 | hpp | //***************************************************************************
// Copyright 2017 OceanScan - Marine Systems & Technology, Lda. *
//***************************************************************************
// Licensed under the Apache License, Version 2.0 (the "License"); *
// you may not use this file except in compliance with the License. *
// You may obtain a copy of the License at *
// *
// http://www.apache.org/licenses/LICENSE-2.0 *
// *
// Unless required by applicable law or agreed to in writing, software *
// distributed under the License is distributed on an "AS IS" BASIS, *
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
// See the License for the specific language governing permissions and *
// limitations under the License. *
//***************************************************************************
// Author: Ricardo Martins *
//***************************************************************************
// Automatically generated. *
//***************************************************************************
// IMC XML MD5: 0adc43a7ddd00a255e2ea47f969c64aa *
//***************************************************************************
#ifndef IMC_WATERDENSITY_HPP_INCLUDED_
#define IMC_WATERDENSITY_HPP_INCLUDED_
// ISO C++ 98 headers.
#include <ostream>
#include <string>
#include <vector>
// IMC headers.
#include <IMC/Base/Config.hpp>
#include <IMC/Base/Message.hpp>
#include <IMC/Base/InlineMessage.hpp>
#include <IMC/Base/MessageList.hpp>
#include <IMC/Base/JSON.hpp>
#include <IMC/Base/Serialization.hpp>
#include <IMC/Spec/Enumerations.hpp>
#include <IMC/Spec/Bitfields.hpp>
namespace IMC
{
//! Water Density.
class WaterDensity: public Message
{
public:
//! Computed Water Density.
float value;
static uint16_t
getIdStatic(void)
{
return 268;
}
static WaterDensity*
cast(Message* msg__)
{
return (WaterDensity*)msg__;
}
WaterDensity(void)
{
m_header.mgid = WaterDensity::getIdStatic();
clear();
}
WaterDensity*
clone(void) const
{
return new WaterDensity(*this);
}
void
clear(void)
{
value = 0;
}
bool
fieldsEqual(const Message& msg__) const
{
const IMC::WaterDensity& other__ = static_cast<const WaterDensity&>(msg__);
if (value != other__.value) return false;
return true;
}
uint8_t*
serializeFields(uint8_t* bfr__) const
{
uint8_t* ptr__ = bfr__;
ptr__ += IMC::serialize(value, ptr__);
return ptr__;
}
size_t
deserializeFields(const uint8_t* bfr__, size_t size__)
{
const uint8_t* start__ = bfr__;
bfr__ += IMC::deserialize(value, bfr__, size__);
return bfr__ - start__;
}
size_t
reverseDeserializeFields(const uint8_t* bfr__, size_t size__)
{
const uint8_t* start__ = bfr__;
bfr__ += IMC::reverseDeserialize(value, bfr__, size__);
return bfr__ - start__;
}
uint16_t
getId(void) const
{
return WaterDensity::getIdStatic();
}
const char*
getName(void) const
{
return "WaterDensity";
}
size_t
getFixedSerializationSize(void) const
{
return 4;
}
double
getValueFP(void) const
{
return static_cast<double>(value);
}
void
setValueFP(double val)
{
value = static_cast<float>(val);
}
void
fieldsToJSON(std::ostream& os__, unsigned nindent__) const
{
IMC::toJSON(os__, "value", value, nindent__);
}
};
}
#endif
| [
"nikolal@stud.ntnu.no"
] | nikolal@stud.ntnu.no |
a65d8bb07bb37d1c0bf475a3f3eb333f2ba1894a | 2280287e4dc53f46302e86249253b024321e31a5 | /codility test/MaxCounters.cpp | 7f88e38f7b9098dd415702ef0d06ba3dd48c39d0 | [] | no_license | leeheejoo/algorithm | 57fd16672d24887ca065eea9dc4cd1edf9ff98bb | eae97cd69b5f3759642b4dcd0af9eab24b058395 | refs/heads/master | 2020-05-01T11:17:43.859709 | 2019-06-02T15:23:54 | 2019-06-02T15:23:54 | 177,439,192 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,170 | cpp | /*
You are given N counters, initially set to 0, and you have two possible operations on them:
increase(X) − counter X is increased by 1,
max counter − all counters are set to the maximum value of any counter.
A non-empty array A of M integers is given. This array represents consecutive operations:
if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
if A[K] = N + 1 then operation K is max counter.
For example, given integer N = 5 and array A such that:
A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
the values of the counters after each consecutive operation will be:
(0, 0, 1, 0, 0)
(0, 0, 1, 1, 0)
(0, 0, 1, 2, 0)
(2, 2, 2, 2, 2)
(3, 2, 2, 2, 2)
(3, 2, 2, 3, 2)
(3, 2, 2, 4, 2)
The goal is to calculate the value of every counter after all operations.
Write a function:
vector<int> solution(int N, vector<int> &A);
that, given an integer N and a non-empty array A consisting of M integers, returns a sequence of integers representing the values of the counters.
Result array should be returned as a vector of integers.
For example, given:
A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
the function should return [3, 2, 2, 4, 2], as explained above.
Write an efficient algorithm for the following assumptions:
N and M are integers within the range [1..100,000];
each element of array A is an integer within the range [1..N + 1].
https://app.codility.com/demo/results/trainingSQHJX7-G7Z/
*/
#include <vector>
using namespace std;
vector<int> solution(int N, vector<int> &A) {
vector<int> ret;
// init
ret.assign(N,0);
int maxCount = 0;
for(int a=0; a<A.size(); a++){
int opValue = A[a];
if(opValue == N+1){
ret.assign(N,maxCount);
}
else{
ret[opValue-1]++;
int retValue = ret[opValue-1];
if(retValue > maxCount)
maxCount = retValue;
}
}
return ret;
}
int main() {
vector<int> A = {3,4,4,6,1,4,4};
vector<int> ret = solution(5, A);
return 0;
} | [
"spdm1254@gmail.com"
] | spdm1254@gmail.com |
36547c1598aa247132876c654b2f45602b979e0c | 3cb889e26a8e94782c637aa1126ad897ccc0d7a9 | /C++/CompilerStudy/Lesson17_StrongType/TypeSystem.cpp | 0a78fa81adb6c09417dd01194893187ba127ffd4 | [] | no_license | GHScan/DailyProjects | 1d35fd5d69e574758d68980ac25b979ef2dc2b4d | 52e0ca903ee4e89c825a14042ca502bb1b1d2e31 | refs/heads/master | 2021-04-22T06:43:42.374366 | 2020-06-15T17:04:59 | 2020-06-15T17:04:59 | 8,292,627 | 29 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 1,369 | cpp |
#include "pch.h"
#include "TypeSystem.h"
TypeSystem::TypeSystem()
{
addType("void", new SimpleType(4));
addType("char", new SimpleType(1));
addType("int", new SimpleType(4));
}
TypeSystem::~TypeSystem()
{
for (auto p : m_name2Type) delete p.second;
for (auto p : m_type2Pointer) delete p.second;
for (auto p : m_type2Array) {
for (auto p2 : p.second) delete p2.second;
}
}
IType* TypeSystem::addType(const string& name, IType *type)
{
ASSERT(m_name2Type.count(name) == 0);
return m_name2Type[name] = type;
}
IType* TypeSystem::getType(const string& name)
{
if (m_name2Type.count(name) == 0) return NULL;
return m_name2Type[name];
}
IType* TypeSystem::getPointer(IType *type)
{
if (m_type2Pointer.count(type) == 0) {
m_type2Pointer[type] = new PointerType(type);
}
return m_type2Pointer[type];
}
IType* TypeSystem::getArray(IType *elemType, int n)
{
if (m_type2Array[elemType].count(n) == 0) {
m_type2Array[elemType][n] = new ArrayType(elemType, n);
}
return m_type2Array[elemType][n];
}
IType* TypeSystem::getFunc(IType* ret, const vector<IType*>& args)
{
string sig = format("%x,", ret);
for (auto t : args) sig += format("%x,", t);
if (m_type2Func.count(sig) == 0) {
m_type2Func[sig] = new FunctionType(ret, args);
}
return m_type2Func[sig];
}
| [
"ppscan@qq.com"
] | ppscan@qq.com |
be2e147f12a83e9d4e6c81bb7baef18cb695e5e9 | f2f3a0ece9ef08cb8cff3272d3b4326a7f1ab1a0 | /Homework 1/Parser/Parser.ipp | 3b6751bab40206b8656fb5ea108449c39a96a32e | [] | no_license | DarkArc/UAkron-Simple-Calculator | de691378508c76f16355f05658452461a87f2e7f | bb91cb2eeae697707138206ee119a6af7c4e35de | refs/heads/master | 2021-01-18T14:22:48.336455 | 2015-10-25T23:53:53 | 2015-10-25T23:53:53 | 42,557,426 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,176 | ipp | #include <stdexcept>
#include <sstream>
inline Expr* parse(const std::string& in) {
std::stringstream ss;
ss.str(in);
return parse(ss);
}
inline Expr* parse(std::istream& is) {
Parser p(is);
Expr* expr = p.expr();
if (p.la != "\n") {
throw std::logic_error("Invalid syntax");
}
return expr;
}
template <typename T>
inline void Parser::match(T& e) {
if (!optMatch(e)) {
throw std::logic_error("Invalid syntax");
}
}
template <typename T>
inline bool Parser::optMatch(T& e) {
if (e == la) {
next();
return true;
}
return false;
}
template <typename MapType>
inline Expr* Parser::binaryOpParse(MapType& map, SubParserPtr subParse) {
// Call the recursive function
Expr* e1 = (this->*subParse)();
typename MapType::iterator it;
// While the operator in the map is valid, remove
// the current look ahead, call the recursive function
// and join using the correct AST node, as determined
// by the corresponding factory
while ((it = map.find(la)) != map.end()) {
next();
Expr* e2 = (this->*subParse)();
e1 = it->second(e1, e2);
}
return e1;
}
| [
"wchilders@nearce.com"
] | wchilders@nearce.com |
7fe9633a1a53bc7db9689c421e37a58dcad0cd69 | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/CodeJamData/14/23/17.cpp | 47eb75cb62c1361b68934184b19106f7ccddace9 | [] | no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 2,870 | cpp | /*
* in the name of god
*
*
*
*
*
*
*
*
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <set>
#include <map>
#include <complex>
#include <bitset>
#include <iomanip>
#include <utility>
using namespace std;
typedef long long LL;
typedef pair<int,int> pii;
typedef complex<double> point;
bool active[100],mark[100],vis[100];
int n,e;
int val[100],par[100],hei[100];
vector <int> adj[100];
bool go (int v, int p, int last){
for (int i = last; i != p; i = par[i])
active[i] = false;
queue <int> Q;
vector <bool> vis(n, false);
for (int i=0; i<n; i++) if (mark[i] && active[i]){
Q.push(i);
vis[i] = true;
}
while (!Q.empty()){
int front = Q.front(); Q.pop();
for (int i=0; i<(int)adj[front].size(); i++){
int tmp = adj[front][i];
if ((!vis[tmp]) && ((!mark[tmp]))){
Q.push(tmp);
vis[tmp] = true;
}
}
}
for (int i=0; i<n; i++) if (mark[i]==false && vis[i]==false){
for (int j=last; j!=p; j=par[j])
active[j] = true;
return false;
}
for (int j=last; j!=p; j=par[j])
active[j] = true;
return true;
}
inline void main2(){
cin >> n >> e;
for (int i=0; i<n; i++)
adj[i].clear();
vector < pair<int,int> > Q;
for (int i=0; i<n; i++){
cin >> val[i];
Q.push_back(pair<int,int>(val[i], i));
}
for (int j=0; j<e; j++){
int e1,e2; cin >> e1 >> e2;
e1--; e2--;
adj[e1].push_back(e2);
adj[e2].push_back(e1);
}
memset(mark, 0, sizeof mark);
memset(active, 0, sizeof active);
sort(Q.begin(), Q.end());
mark[Q[0].second] = true;
active[Q[0].second] = true;
cout << Q[0].first;
int last = Q[0].second;
for (int rep = 1; rep < n; rep++){
for (int j=0; j<n; j++) if (!mark[Q[j].second]){
memset(vis, false, sizeof vis);
int temp = last;
int C = 0;
while (temp != Q[0].second){
vis[temp] = true;
hei[temp] = C++;
temp = par[temp];
}
hei[Q[0].second] = C++;
vis[Q[0].second] = true;
int pos = -1;
for (int k=0; k<(int)adj[Q[j].second].size(); k++){
int B = adj[Q[j].second][k];
if (vis[B]){
if (go(Q[j].second, B, last)){
if ((pos==-1) || (hei[B] < hei[pos]))
pos = B;
}
}
}
if (pos != -1){
cout << Q[j].first;
mark[Q[j].second] = active[Q[j].second] = true;
par[Q[j].second] = pos;
for (int k=last; k != pos; k = par[k])
active[k] = false;
last = Q[j].second;
break;
}
}
}
cout << endl;
}
int main(){
int tt; cin >> tt;
for (int o=1; o<=tt; o++){
cout << "Case #" << o << ": ";
main2();
}
return 0;
}
| [
"kwnafi@yahoo.com"
] | kwnafi@yahoo.com |
2fd7ca965add809b76a3829f47e78e07a4184319 | b938babcbca9f082127e2bf7e6e12026f3a3cb8e | /src/model.h | 346f65e9faee9aad0832e9698ee4e3daec72d308 | [] | no_license | hmatuschek/qnecpp | 54aadc0752a7c9b8f8a63243bbfc783a56dac99f | 73d38b04ab4e7ec8e0371b2680bc306e3376a30f | refs/heads/master | 2020-09-16T22:46:26.527993 | 2019-11-25T14:14:38 | 2019-11-25T14:14:38 | 223,909,460 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 802 | h | #ifndef __MODEL_H__
#define __MODEL_H__
#include <string>
#include <list>
#include "object.h"
#include "nec_context.h"
#include "geometry.h"
#include "ground.h"
#include "excitation.h"
#include "measurement.h"
class ModelObj: public Object
{
public:
ModelObj(const std::wstring &name=L"");
virtual ~ModelObj();
void mark();
GeometryObj *geometry() const;
void setGround(GroundObj *ground);
void setExcitation(ExcitationObj *excitation);
void addFrequency(double F_in_MHz);
void setMeasurement(MeasurementObj *measurement);
virtual std::list<ResultObj*> run();
protected:
std::wstring _name;
GeometryObj *_geometry;
GroundObj *_ground;
ExcitationObj *_excitation;
std::vector<double> _frequencies;
MeasurementObj *_measurement;
};
#endif // __MODEL_H__
| [
"hmatuschek@gmail.com"
] | hmatuschek@gmail.com |
b024e3f430cc78878e8c4bd46255348384e48472 | 6c027bc36e6c9c167cae54351bf00826d9e62143 | /src/client/Display.cpp | 6439ea7cbcca7a42ff958e079f095b611cb69f25 | [] | no_license | JoshBlythe/SituationalDisplay | 1bd89398a4640a4ccd5f27316d2d6e1d5ca4e3be | e63aabff34a53eff38f4b19312b68edd8007d2e1 | refs/heads/master | 2021-01-07T14:09:36.865391 | 2020-10-20T14:02:18 | 2020-10-20T14:02:18 | 241,719,485 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,105 | cpp | #include "Display.h"
Display::Display(int argc, char** argv)
{
enviroment = new Enviroment(argc, argv);
std::string GlobeImageLoc = enviroment->fileLocations() + "/" + "GlobeImage" + ".png";
GlobeImage = new SprtieRender(GlobeImageLoc, 0, 0, 800, 600);
}
Display::~Display()
{
SDL_DestroyWindow(window);
SDL_Quit();
}
void Display::InitWindow()
{
//initalise SDL
if(SDL_WasInit(SDL_INIT_EVERYTHING) < 0)
{
//throw a exception
throw Exception("Error initalising SDL!");
}
//create window
window = SDL_CreateWindow("Situational Display",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
800, 600, SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL);
//check if window is initalised
if(!window)
{
//throw exception.
throw Exception("Error creating SDL window!!");
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if(!renderer)
{
throw Exception("Error Creating SDL renderer!");
}
// if(!SDL_GL_CreateContext(window))
// {
// //throw exception.
// throw Exception("Error during SDL_GL_CreateContext!");
// }
// if(glewInit() != GLEW_OK)
// {
// throw Exception("Glew Init Error.");
// }
}
void Display::RunDisplay()
{
bool _running = true;
SDL_Event e = {0};
while(_running)
{
while (SDL_PollEvent(&e) != 0)
{
if(e.type == SDL_QUIT)
{
_running = false;
}
}
manger.StateProcessNetwork();
// glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
SDL_PumpEvents();
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 0,0,0, 255);
//Draw Globe Map.
//GlobeImage->DrawSprite(renderer);
//SDL_RenderPresent(renderer);
//SDL_Delay(3000000);
//SDL_GL_SwapWindow(window);
}
}
void Display::DrawPlane()
{
}
| [
"you@example.com"
] | you@example.com |
9d0e42421b4f021154f9bd0cbd8da8ff6916c9e5 | 1af49694004c6fbc31deada5618dae37255ce978 | /chrome/browser/android/ntp/most_visited_sites_bridge.h | c04d0152576c87637ab5f21f0ba416f0b44ad461 | [
"BSD-3-Clause"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | C++ | false | false | 2,710 | h | // Copyright 2016 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_ANDROID_NTP_MOST_VISITED_SITES_BRIDGE_H_
#define CHROME_BROWSER_ANDROID_NTP_MOST_VISITED_SITES_BRIDGE_H_
#include <jni.h>
#include <memory>
#include "base/android/scoped_java_ref.h"
#include "base/macros.h"
class Profile;
namespace ntp_tiles {
class MostVisitedSites;
} // namespace ntp_tiles
// Provides the list of most visited sites and their thumbnails to Java.
class MostVisitedSitesBridge {
public:
explicit MostVisitedSitesBridge(Profile* profile);
void Destroy(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj);
void OnHomepageStateChanged(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj);
void SetObserver(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
const base::android::JavaParamRef<jobject>& j_observer,
jint num_sites);
void SetHomepageClient(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
const base::android::JavaParamRef<jobject>& j_client);
void AddOrRemoveBlockedUrl(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
const base::android::JavaParamRef<jobject>& j_url,
jboolean add_url);
void RecordPageImpression(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
jint jtiles_count);
void RecordTileImpression(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
jint jindex,
jint jvisual_type,
jint jicon_type,
jint jtitle_source,
jint jsource,
jlong jdata_generation_time_ms,
const base::android::JavaParamRef<jobject>& jurl);
void RecordOpenedMostVisitedItem(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
jint index,
jint tile_type,
jint title_source,
jint source,
jlong jdata_generation_time_ms);
private:
~MostVisitedSitesBridge();
class JavaObserver;
std::unique_ptr<JavaObserver> java_observer_;
std::unique_ptr<ntp_tiles::MostVisitedSites> most_visited_;
Profile* profile_;
DISALLOW_COPY_AND_ASSIGN(MostVisitedSitesBridge);
};
#endif // CHROME_BROWSER_ANDROID_NTP_MOST_VISITED_SITES_BRIDGE_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
b8e8db97298eba078cf0ba939cf45303554f8c51 | 8d1ee4bfb88b5f884d23a14cc83799b79904a7b0 | /theblocksproblems.cpp | 48a6c42a013d8569528e268c51e331371790421f | [] | no_license | mojoe12/UVa | aefb2020fe3b48c115557be131acb62ede08f5dc | dba57e95b3f387b187a872620ae9e72290fa1a61 | refs/heads/master | 2021-01-23T01:45:54.335619 | 2017-09-29T02:22:29 | 2017-09-29T02:22:29 | 92,890,593 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,373 | cpp | #include <iostream>
#include <vector>
using namespace std;
vector<int> blank () {
vector<int> dante (0);
return dante;
}
int findcol(vector< vector<int> > blox, int a) {
for (int i = 0; i < blox.size(); i++) {
for (int j = 0; j < blox[i].size(); j++) {
if (blox[i][j] == a) return i;
}
}
return 0;
}
int findrow(vector< vector<int> > blox, int a) {
for (int i = 0; i < blox.size(); i++) {
for (int j = 0; j < blox[i].size(); j++) {
if (blox[i][j] == a) return j;
}
}
return 0;
}
int main(int argc, char *argv[]) {
int n;
cin >> n;
vector< vector<int> > blox (n, vector<int> (1));
for (int i = 0; i < n; i++) blox[i][0] = i;
string command;
cin >> command;
while (command != "quit") {
string oo;
int a, b;
cin >> a >> oo >> b;
int acol = findcol(blox, a), bcol = findcol(blox, b);
int arow = findrow(blox, a), brow = findrow(blox, b);
if (acol == bcol || a == b) {
cin >> command;
continue;
};
if (command == "pile" && oo == "over") {
for (int i = arow; i < blox[acol].size(); i++) {
blox[bcol].push_back(blox[acol][i]);
}
for (int i = blox[acol].size()-1; i >= arow; i--) {
blox[acol].pop_back();
}
}
else if (command == "pile" && oo == "onto") {
for (int i = blox[bcol].size()-1; i > brow; i--) {
int num = blox[bcol][i];
blox[num].push_back(num);
blox[bcol].pop_back();
}
for (int i = arow; i < blox[acol].size(); i++) {
blox[bcol].push_back(blox[acol][i]);
}
for (int i = blox[acol].size()-1; i >= arow; i--) {
blox[acol].pop_back();
}
}
else if (command == "move" && oo == "over") {
for (int i = blox[acol].size()-1; i > arow; i--) {
int num = blox[acol][i];
blox[num].push_back(num);
blox[acol].pop_back();
}
blox[bcol].push_back(a);
blox[acol].pop_back();
}
else if (command == "move" && oo == "onto") {
for (int i = blox[bcol].size()-1; i > brow; i--) {
int num = blox[bcol][i];
blox[num].push_back(num);
blox[bcol].pop_back();
}
for (int i = blox[acol].size()-1; i > arow; i--) {
int num = blox[acol][i];
blox[num].push_back(num);
blox[acol].pop_back();
}
blox[bcol].push_back(a);
blox[acol].pop_back();
}
cin >> command;
}
for (int i = 0; i < n; i++) {
cout << i << ':';
for (int j = 0; j < blox[i].size(); j++) cout << ' ' << blox[i][j];
cout << endl;
}
} | [
"josephahutter@gmail.com"
] | josephahutter@gmail.com |
5cbc7fd466874a2f3ac3d031f7785a4f43981dc4 | 5c861a39f940a75733bd8cd7f475ce615b5e8a7c | /lib/server.h | a0d74e9ba769f752264c424414df71a58a4a9ab0 | [] | no_license | CloudFundoo/cheeta | a1127834963bac9478c03804008cd579c9cd3aa0 | 45a80e456869d37d3a74a3e15718c98d58cea16f | refs/heads/master | 2021-01-25T08:59:51.071443 | 2012-08-23T05:22:22 | 2012-08-23T05:22:22 | 4,555,120 | 0 | 1 | null | 2020-08-17T06:03:33 | 2012-06-05T02:56:36 | C++ | UTF-8 | C++ | false | false | 274 | h | #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
class server{
public:
server();
~server();
int socketfd;
int rsocketfd;
struct sockaddr_in instanceaddr;
struct sockaddr_in remoteaddr;
};
| [
"cloudfundoo@gmail.com"
] | cloudfundoo@gmail.com |
82ccb11334b8d4e34218a590b92cd1ba67ae1ff4 | cfd66fb49f5856f9c862038a628e160e6fa0a18d | /berlinunited/src/management/config/configProtobuf.h | 5907a3479621cb94d1fa9af54f67686eae29f6c4 | [] | no_license | sergiyvan/robotic_vl | c977fea8503ea2a10c319759ed1727301e6472bd | 1d3b66819e37a58e0ab752ea86aa2d8522643e1e | refs/heads/master | 2021-01-20T12:04:01.507082 | 2014-11-03T15:41:42 | 2014-11-03T15:41:42 | 25,864,171 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,491 | h | #ifndef CONFIGPROTOBUF_H
#define CONFIGPROTOBUF_H
#include "configStorage.h"
#include <msg_configuration.pb.h>
#include <string>
#include <iostream>
#include <map>
/*------------------------------------------------------------------------------------------------*/
/**
** configuration provider based on protobuf.
**
** @note This class can't use the comm object to send warnings, as comm only starts
** after having read the configuration.
**
** @ingroup config
*/
class ConfigProtobuf : public ConfigStorage {
friend class Config;
protected:
de::fumanoids::message::Configuration configuration;
de::fumanoids::message::Configuration *getPBSection(const std::string §ionName);
const de::fumanoids::message::Configuration *getPBSection(const std::string §ionName) const;
de::fumanoids::message::ConfigurationOption *getPBOption(const std::string &fullOptionName);
const de::fumanoids::message::ConfigurationOption *getPBOption(const std::string &fullOptionName) const;
bool createConfigurationSection(std::string parentSection, std::string sectionName);
bool createConfigurationSection(std::string sectionName);
de::fumanoids::message::ConfigurationOption* createEmptyConfigurationOption(const std::string &fullOptionName);
void assemblePBConfiguration();
void saveTextBackup(const std::string filename) const;
void saveTextSection(const de::fumanoids::message::Configuration& section, int indentation, std::ostream &out) const;
static void sort(de::fumanoids::message::Configuration *currentSection);
const de::fumanoids::message::Configuration & getConfiguration();
public:
ConfigProtobuf();
virtual ~ConfigProtobuf();
virtual bool loadFromStream(std::istream &in) override;
virtual bool save() override {
return ConfigStorage::save();
}
virtual bool save(const std::string &filename) override;
virtual bool saveToStream(std::ostream &out) override;
/** Derived configuration classes (namely those that load configuration files)
** may have a value for this configuration option cached that should now be
** applied.
**
** @param name Name of option to apply value to
*/
virtual void applyPreloadedValue(std::string name) {
// make option name lowercase
std::transform(name.begin(), name.end(), name.begin(), ::tolower);
de::fumanoids::message::ConfigurationOption *pbConfig = getPBOption(name);
if (nullptr != pbConfig)
getOption(name)->fromProtobuf(pbConfig);
}
};
#endif
| [
"lutz.freitag@fu-berlin.de"
] | lutz.freitag@fu-berlin.de |
62ba2f3a18d5b752dcea56b81c74c28727afe232 | b38ecff4d90805ad1d882172f234571cfef0ee2b | /Code/client/src/Systems/InterpolationSystem.cpp | 41996e67b158a9a4ae76887b3cc10170e32d6dc4 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | blipvert/TiltedOnline | d46294c3f89bf74cc9acff93fe7fcad055955433 | 9210870580b00710a9e5c98edb28924284f1dd7a | refs/heads/master | 2022-11-11T16:08:52.732293 | 2020-06-26T15:07:33 | 2020-06-26T15:08:55 | 275,181,709 | 0 | 0 | NOASSERTION | 2020-06-26T14:58:16 | 2020-06-26T14:58:16 | null | UTF-8 | C++ | false | false | 2,936 | cpp | #include <Systems/InterpolationSystem.h>
#include <Components.h>
#include <Games/Skyrim/Misc/ActorProcessManager.h>
#include <Games/Skyrim/Misc/MiddleProcess.h>
#include <Games/Fallout4/Misc/ProcessManager.h>
#include <Games/Fallout4/Misc/MiddleProcess.h>
#include <Games/References.h>
#include <World.h>
void InterpolationSystem::Update(Actor* apActor, InterpolationComponent& aInterpolationComponent, const uint64_t aTick) noexcept
{
auto& movements = aInterpolationComponent.TimePoints;
while (movements.size() > 2)
{
const auto second = *(++movements.begin());
if (aTick > second.Tick)
movements.pop_front();
else
break;
}
if (movements.size() < 2)
{
auto pName = apActor->GetName();
pName = pName != nullptr ? pName : "UNKNOWN";
//spdlog::warn("Actor {s} is missing interpolation points, skipping frame.", pName);
return;
}
const auto& first = *(movements.begin());
const auto& second = *(++movements.begin());
// Calculate delta movement since last update
auto delta = 0.0001f;
const auto tickDelta = float(second.Tick - first.Tick);
if (tickDelta > 0.f)
{
delta = 1.f / tickDelta * float(aTick - first.Tick);
}
delta = TiltedPhoques::Min(delta, 1.0f);
NiPoint3 position{};
TiltedPhoques::Lerp(first.Position, second.Position, delta)
.Decompose(position.x, position.y, position.z);
apActor->ForcePosition(position);
float firstX, firstY, firstZ;
float secondX, secondY, secondZ;
first.Rotation.Decompose(firstX, firstY, firstZ);
second.Rotation.Decompose(secondX, secondY, secondZ);
const auto deltaX = TiltedPhoques::DeltaAngle(firstX, secondX, true) * delta;
const auto deltaY = TiltedPhoques::DeltaAngle(firstY, secondY, true) * delta;
const auto deltaZ = TiltedPhoques::DeltaAngle(firstZ, secondZ, true) * delta;
const auto finalX = TiltedPhoques::Mod(firstX + deltaX, TiltedPhoques::Pi * 2);
const auto finalY = TiltedPhoques::Mod(firstY + deltaY, TiltedPhoques::Pi * 2);
const auto finalZ = TiltedPhoques::Mod(firstZ + deltaZ, TiltedPhoques::Pi * 2);
apActor->SetRotation(finalX, finalY, finalZ);
}
void InterpolationSystem::AddPoint(InterpolationComponent& aInterpolationComponent,
const InterpolationComponent::TimePoint& acPoint) noexcept
{
auto itor = std::begin(aInterpolationComponent.TimePoints);
const auto end = std::cend(aInterpolationComponent.TimePoints);
while(itor != end)
{
if(itor->Tick > acPoint.Tick)
{
aInterpolationComponent.TimePoints.insert(itor, acPoint);
return;
}
++itor;
}
aInterpolationComponent.TimePoints.push_back(acPoint);
}
void InterpolationSystem::Setup(World& aWorld, const entt::entity aEntity) noexcept
{
aWorld.emplace<InterpolationComponent>(aEntity);
}
| [
"maxime@griot.fr"
] | maxime@griot.fr |
4f652dc71e0f09f2108e8223a92ff22f05fb841d | eec2eb8d09c05ae3ef92ff1ff7c43d8e0ee67784 | /rfc/gui/KGridViewListener.h | 336df7bc718e5be5a2be1ab356431e7a67d210af | [
"MIT"
] | permissive | camark/RFC-Framework | 6dc9c6668f2d01c6648f99c1b86913c2b257ad51 | e82b51be20750f47ab73bb2176bd0344d3f32b57 | refs/heads/master | 2020-03-24T16:48:20.644669 | 2018-07-19T03:05:26 | 2018-07-19T03:05:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,308 | h |
/*
RFC - KGridViewListener.h
Copyright (C) 2013-2018 CrownSoft
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.
*/
#ifndef _RFC_KGRIDVIEWLISTENER_H_
#define _RFC_KGRIDVIEWLISTENER_H_
#include"../config.h"
class KGridView;
class RFC_API KGridViewListener
{
public:
KGridViewListener();
virtual ~KGridViewListener();
virtual void OnGridViewItemSelect(KGridView *gridView);
virtual void OnGridViewItemRightClick(KGridView *gridView);
virtual void OnGridViewItemDoubleClick(KGridView *gridView);
};
#endif | [
"ruchira66@gmail.com"
] | ruchira66@gmail.com |
ca96c8ca615fb0b32abfb4862bdfde2071f569d9 | b65ffe11899f9542ab213154b0c2d3c24bc60371 | /src/ripple/test/jtx/impl/memo.cpp | 0b0e799580f4af2bf6ba74773a34553abdbaa6b3 | [
"ISC",
"MIT-Wu",
"MIT",
"BSL-1.0"
] | permissive | rec/rippled | 86bada74dd782fbe7d09ed29eb9e8fc4a7f00432 | ea0bd086600d642c5f8e4ab9ba1f0164dc5b64f0 | refs/heads/develop | 2021-01-18T01:23:40.037370 | 2015-09-13T21:28:46 | 2015-09-13T21:28:46 | 18,302,070 | 2 | 0 | null | 2014-04-08T16:56:04 | 2014-03-31T17:41:21 | C++ | UTF-8 | C++ | false | false | 2,848 | cpp | //------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <BeastConfig.h>
#include <ripple/test/jtx/memo.h>
#include <ripple/basics/StringUtilities.h>
#include <ripple/protocol/JsonFields.h>
namespace ripple {
namespace test {
namespace jtx {
void
memo::operator()(Env const&, JTx& jt) const
{
auto& jv = jt.jv;
auto& ma = jv["Memos"];
auto& mi = ma[ma.size()];
auto& m = mi["Memo"];
m["MemoData"] = strHex(data_);
m["MemoFormat"] = strHex(format_);
m["MemoType"] = strHex(type_);
}
void
memodata::operator()(Env const&, JTx& jt) const
{
auto& jv = jt.jv;
auto& ma = jv["Memos"];
auto& mi = ma[ma.size()];
auto& m = mi["Memo"];
m["MemoData"] = strHex(s_);
}
void
memoformat::operator()(Env const&, JTx& jt) const
{
auto& jv = jt.jv;
auto& ma = jv["Memos"];
auto& mi = ma[ma.size()];
auto& m = mi["Memo"];
m["MemoFormat"] = strHex(s_);
}
void
memotype::operator()(Env const&, JTx& jt) const
{
auto& jv = jt.jv;
auto& ma = jv["Memos"];
auto& mi = ma[ma.size()];
auto& m = mi["Memo"];
m["MemoType"] = strHex(s_);
}
void
memondata::operator()(Env const&, JTx& jt) const
{
auto& jv = jt.jv;
auto& ma = jv["Memos"];
auto& mi = ma[ma.size()];
auto& m = mi["Memo"];
m["MemoFormat"] = strHex(format_);
m["MemoType"] = strHex(type_);
}
void
memonformat::operator()(Env const&, JTx& jt) const
{
auto& jv = jt.jv;
auto& ma = jv["Memos"];
auto& mi = ma[ma.size()];
auto& m = mi["Memo"];
m["MemoData"] = strHex(data_);
m["MemoType"] = strHex(type_);
}
void
memontype::operator()(Env const&, JTx& jt) const
{
auto& jv = jt.jv;
auto& ma = jv["Memos"];
auto& mi = ma[ma.size()];
auto& m = mi["Memo"];
m["MemoData"] = strHex(data_);
m["MemoFormat"] = strHex(format_);
}
} // jtx
} // test
} // ripple
| [
"vinnie.falco@gmail.com"
] | vinnie.falco@gmail.com |
285ef217a5c3d74676b1d3d1bade6dc414300e95 | 67cf763cc0f45b15fb8b43707d7d4ee571d01139 | /AsyncEntityBuffer.cpp | 2e66242e6400a2da5d9713317c72836c8bdbadea | [] | no_license | mhoff12358/VRBackend | 38b72eded419e8c1c5e6b505dddc19db330da60b | 88fca6bbcd0df644564a340cc58b35dae9e71081 | refs/heads/master | 2016-08-09T19:30:49.627075 | 2015-08-31T09:56:13 | 2015-08-31T09:56:13 | 36,851,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,178 | cpp | #include "AsyncEntityBuffer.h"
AsyncEntityBuffer::AsyncEntityBuffer()
{
writing_group = groups;
new_reading_group = groups + 1;
old_reading_group = groups + 2;
}
AsyncEntityBuffer::~AsyncEntityBuffer()
{
}
RenderGroup* AsyncEntityBuffer::Initialize() {
return writing_group;
}
RenderGroup* AsyncEntityBuffer::ProducerFinish() {
state_ownership_lock.lock();
// Mark W as N
RenderGroup* previous_new_reading_group = new_reading_group;
new_reading_group = writing_group;
if (reader_on_new) {
// Mark O as W and N as O
writing_group = old_reading_group;
old_reading_group = previous_new_reading_group;
reader_on_new = false;
} else {
// Mark N as W
writing_group = previous_new_reading_group;
}
state_ownership_lock.unlock();
// Copy the contents of the old writing group (now the new reading group)
// to the new writing group
writing_group->Update(new_reading_group);
return writing_group;
}
RenderGroup* AsyncEntityBuffer::ConsumerFinish() {
state_ownership_lock.lock();
// Claim the current new reading group
reader_on_new = true;
RenderGroup* returned_group = new_reading_group;
state_ownership_lock.unlock();
return returned_group;
} | [
"mhoff12358@gmail.com"
] | mhoff12358@gmail.com |
22d050dc7884cf78d16044805c2b516b59449620 | a6a7b8742f5299e6537fa8065eff71d65132ea1a | /Coding-Ninjas/Assignment-3-BackTrack/distribute_candidates.cpp | 6e7a82f5cdd0a8449a86a74f3fdb94015a81d2ba | [] | no_license | blackenwhite/Competitive-Coding | bb25994a9ffe3c8ac1476b4b11640a01f10e36e7 | c95ecfc1dfc7879c02899341083569a4e60da2f8 | refs/heads/master | 2021-05-19T08:23:41.785230 | 2020-04-02T13:12:04 | 2020-04-02T13:12:04 | 251,603,623 | 0 | 0 | null | 2020-03-31T12:59:16 | 2020-03-31T12:59:16 | null | UTF-8 | C++ | false | false | 1,050 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool checkPossible(vector<long long> arr,int n,long long mid,int k)
{
int count = 0;
for(int i=0;i<n;i++)
{
count += arr[i]/mid;
}
// cout<<count<<endl;
if(count >= k)
return true;
else
return false;
}
int main()
{
int t;
cin >> t;
for(int t0 = 0; t0 < t; t0++)
{
long long n,k;
cin >> n >> k;
vector<long long> arr(n);
long long i,sum = 0;
for(i = 0;i < n; i++)
{
cin >> arr[i];
sum += arr[i];
}
sort(arr.begin(),arr.end());
long long beg = 1;
long long end = sum/k;
long long ans = -1;
while(beg <= end)
{
long long mid=(beg+end)/2;
if(checkPossible(arr,n,mid,k))
{
ans = mid;
beg = mid +1;
}
else
end = mid -1;
}
cout<<ans<<endl;
}
} | [
"amrithchallenger@gmail.com"
] | amrithchallenger@gmail.com |
28beeff864527d5a41740aac5aeaf1d08e5e192f | 34ea7c33bba68d50471f2e6ff659418388fbe67a | /Engine/Animation/AnimationSystem.h | 1a8da17078601fbeda66ff0957d06e8b75a617e8 | [] | no_license | asdlei99/renderer-1 | 23eb1a23036291bd0001165689ab1b7e6bde4893 | 6bd75d1b29e89767c943db48c36288a5077bbc97 | refs/heads/master | 2021-01-03T00:15:09.665734 | 2020-01-18T14:20:57 | 2020-01-18T14:20:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 643 | h | #ifndef __ANIMATION_SYSTEM__
#define __ANIMATION_SYSTEM__
#include "Core\System.h"
#include "Container\Vector.h"
#include "Container\LinkList.h"
#include "Container\List.h"
#include "Animator.h"
class AnimationSystem : public System
{
BASEOBJECT(System);
OBJECT(AnimationSystem);
private:
// all the animators
List<Animator> Animators;
// destroyed animator
Vector<Animator*> Destroyed;
public:
AnimationSystem(Context* context);
virtual ~AnimationSystem();
// add animator
void AddAnimator(Animator* animator);
// remove animator
void RemoveAnimator(Animator* animator);
// update
virtual int Update(int ms);
};
#endif
| [
"nick12@live.cn"
] | nick12@live.cn |
3efc64563fe8b4db631156a9bbb337a29b0a08b5 | 7aa1743c918b482a27dc843173b6bab05b511e21 | /C++14_2/1_타입추론5.cpp | a4e55888a8a380e429add6a72719d5395cb87207 | [] | no_license | RealChaser/Cpp_Lecture | 7021be1b1f02c9f62f83db5a14885b8d8f34ebbb | b947bb6defdad4bb1c598c2c39a4d7f05cfc50de | refs/heads/master | 2021-06-24T18:20:14.247040 | 2020-02-22T14:11:24 | 2020-02-22T14:11:24 | 91,180,286 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 505 | cpp | #include <iostream>
#include <boost/type_index.hpp>
using namespace std;
using namespace boost;
using namespace boost::typeindex;
// 규칙 3. param 타입이 Forwarding Reference 일때
template<typename T> void foo(T&& param)
{
cout << type_id_with_cvr<T>().pretty_name() << endl;
cout << type_id_with_cvr<decltype(param)>().pretty_name() << endl;
}
int main()
{
int n = 10;
foo(n); // lvalue T : int&, T&& : int& && => int&
foo(10); // rvalue T : int T&& : int && => int&&
}
| [
"realchaser86@gmail.com"
] | realchaser86@gmail.com |
d16bd4769dab1af6c5272216357448acca061bd9 | 2df280433353d1b42275b4af9eccec40499ca0b4 | /include/Managers/ClusterManager.h | e5f397ca5a4c516154f3d2b44ae092f1e1dba48a | [] | no_license | bonoxu/PandoraSDK | 40f7480aa7f867ee7e9835a05cd26cd0fac3b0e5 | f60a9af7ecce90b0f8d4b74722d7503ddb2dd041 | refs/heads/master | 2021-01-21T07:34:14.991465 | 2016-07-12T20:41:20 | 2016-07-12T20:41:20 | 48,260,780 | 0 | 0 | null | 2015-12-18T23:17:15 | 2015-12-18T23:17:15 | null | UTF-8 | C++ | false | false | 5,554 | h | /**
* @file PandoraSDK/include/Managers/ClusterManager.h
*
* @brief Header file for the cluster manager class.
*
* $Log: $
*/
#ifndef PANDORA_CLUSTER_MANAGER_H
#define PANDORA_CLUSTER_MANAGER_H 1
#include "Api/PandoraContentApi.h"
#include "Managers/AlgorithmObjectManager.h"
#include "Pandora/PandoraInternal.h"
namespace pandora
{
/**
* @brief ClusterManager class
*/
class ClusterManager : public AlgorithmObjectManager<Cluster>
{
public:
/**
* @brief Constructor
*
* @param pPandora address of the associated pandora object
*/
ClusterManager(const Pandora *const pPandora);
/**
* @brief Destructor
*/
~ClusterManager();
private:
/**
* @brief Create cluster
*
* @param parameters the cluster parameters
* @param pCluster to receive the address of the cluster created
* @param factory the factory that performs the object allocation
*/
StatusCode Create(const PandoraContentApi::Cluster::Parameters ¶meters, const Cluster *&pCluster,
const ObjectFactory<PandoraContentApi::Cluster::Parameters, Cluster> &factory);
/**
* @brief Alter the metadata information stored in a cluster
*
* @param pCluster address of the cluster to modify
* @param metaData the metadata (only populated metadata fields will be propagated to the object)
*/
StatusCode AlterMetadata(const Cluster *const pCluster, const PandoraContentApi::Cluster::Metadata &metadata) const;
/**
* @brief Is a cluster, or a list of clusters, available to add to a particle flow object
*
* @param pT address of the object or object list
*
* @return boolean
*/
template <typename T>
bool IsAvailable(const T *const pT) const;
/**
* @brief Set availability of a cluster, or a list of clusters, to be added to a particle flow object
*
* @param pT the address of the object or object list
* @param isAvailable the availability
*/
template <typename T>
void SetAvailability(const T *const pT, bool isAvailable) const;
/**
* @brief Add a calo hit to a cluster
*
* @param pCluster address of the cluster to modify
* @param pCaloHit address of the hit to add
*/
StatusCode AddToCluster(const Cluster *const pCluster, const CaloHit *const pCaloHit);
/**
* @brief Remove a calo hit from a cluster
*
* @param pCluster address of the cluster to modify
* @param pCaloHit address of the hit to remove
*/
StatusCode RemoveFromCluster(const Cluster *const pCluster, const CaloHit *const pCaloHit);
/**
* @brief Add an isolated calo hit to a cluster. This is not counted as a regular calo hit: it contributes only
* towards the cluster energy and does not affect any other cluster properties.
*
* @param pCluster address of the cluster to modify
* @param pCaloHit address of the hit to add
*/
StatusCode AddIsolatedToCluster(const Cluster *const pCluster, const CaloHit *const pCaloHit);
/**
* @brief Remove an isolated calo hit from a cluster
*
* @param pCluster address of the cluster to modify
* @param pCaloHit address of the hit to remove
*/
StatusCode RemoveIsolatedFromCluster(const Cluster *const pCluster, const CaloHit *const pCaloHit);
/**
* @brief Merge two clusters from two specified lists, enlarging one cluster and deleting the second
*
* @param pClusterToEnlarge address of the cluster to enlarge
* @param pClusterToDelete address of the cluster to delete
* @param enlargeListName name of the list containing the cluster to enlarge
* @param deleteListName name of the list containing the cluster to delete
*/
StatusCode MergeAndDeleteClusters(const Cluster *const pClusterToEnlarge, const Cluster *const pClusterToDelete,
const std::string &enlargeListName, const std::string &deleteListName);
/**
* @brief Add an association between a cluster and a track
*
* @param pCluster the address of the relevant cluster
* @param pTrack the address of the track with which the cluster is associated
*/
StatusCode AddTrackAssociation(const Cluster *const pCluster, const Track *const pTrack) const;
/**
* @brief Remove an association between a cluster and a track
*
* @param pCluster the address of the relevant cluster
* @param pTrack the address of the track with which the cluster is no longer associated
*/
StatusCode RemoveTrackAssociation(const Cluster *const pCluster, const Track *const pTrack) const;
/**
* @brief Remove all cluster to track associations
*/
StatusCode RemoveAllTrackAssociations() const;
/**
* @brief Remove cluster to track associations from all clusters in the current list
*
* @param danglingTracks to receive the list of "dangling" associations
*/
StatusCode RemoveCurrentTrackAssociations(TrackList &danglingTracks) const;
/**
* @brief Remove a specified list of cluster to track associations
*
* @param trackToClusterList the specified track to cluster list
*/
StatusCode RemoveTrackAssociations(const TrackToClusterMap &trackToClusterList) const;
friend class PandoraContentApiImpl;
friend class PandoraImpl;
};
} // namespace pandora
#endif // #ifndef PANDORA_CLUSTER_MANAGER_H
| [
"marshall@hep.phy.cam.ac.uk"
] | marshall@hep.phy.cam.ac.uk |
85811bbf40c2c03730afa63018cc37403f6eb040 | 450e175d17b377ccebb731b9c40c2e8f57b424f2 | /src/rsptilt_kinematics_plugin/src/RSPtilt_kinematics.cpp | fa7a0c4aaf3aeb48e15ee10df10b07d51fe02e55 | [] | no_license | jlane1590/pose_trajectory_packages | 42b913b3f72100a77b30dc46a2839813699647c7 | 88cdf13cd31f12d1ba725b72ecc6e0ea4cf8e1f0 | refs/heads/master | 2020-03-13T16:03:08.587447 | 2018-06-08T20:09:06 | 2018-06-08T20:09:06 | 131,189,339 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,399 | cpp | /*
* RSPtilt_kinematics.cpp
*
* Created on: 31-Aug-2016
* Author: jlane
*/
#include <pluginlib/class_list_macros.h>
#include <rsptilt_kinematics_plugin/RSPtilt_kinematics.h>
#include <ros/ros.h>
#include <iostream>
#include <sstream>
#include <math.h>
PLUGINLIB_EXPORT_CLASS(rsptilt_kinematics::Kinematics,
kinematics_base::KinematicsPlugin);
using namespace rsptilt_kinematics;
#define DEG_TO_RAD(x) ((x) * M_PI / 180.0)
const double Kinematics::ALMOST_PLUS_ONE = 0.9999999;
const double Kinematics::ALMOST_MINUS_ONE = -0.9999999;
/* radius of base joints; 0 index for even joints, 1 index for odd joints */
const double Kinematics::baseRadius[2] = {
0.0402,
0.0622
};
/* radius of platform joints; 0 index for even joints, 1 index for odd joints */
const double Kinematics::platformRadius[2] = {
0.0408,
0.0408
};
/* angle from x axis of base joints */
const double Kinematics::baseAngles[6] = {
38.43,
120.48,
158.43,
240.48,
278.43,
0.48
};
/* angle from x axis of platform joints */
const double Kinematics::platformAngles[6] = {
74.32,
105.68,
194.32,
225.68,
314.32,
345.68
};
/* angle from x axis of servo horn planes */
const double Kinematics::beta[6] = {
90.0,
270.0,
210.0,
30.0,
330.0,
150.0
};
const double Kinematics::initialHeight = 0.0980;
const double Kinematics::hornLength = 0.0318;
const double Kinematics::legLength = 0.1016;
const double Kinematics::lambda = 12.0; //angle of tilt of servos
std::stringstream sstr;
//InverseKinematics::InverseKinematics()
//{
//}
Kinematics::~Kinematics()
{
}
bool Kinematics::initialize(
const std::vector<double> &min_angles,
const std::vector<double> &max_angles)
{
min_angles_ = min_angles;
max_angles_ = max_angles;
/* calculate base and platform joint positions wrt their own frames */
for(unsigned int i = 0; i < 6; i++) {
b[i].x(baseRadius[i%2]*cos(DEG_TO_RAD(baseAngles[i])));
b[i].y(baseRadius[i%2]*sin(DEG_TO_RAD(baseAngles[i])));
b[i].z(0);
//ROS_DEBUG("Base Positions: (%f, %f, %f)", b[i].x(), b[i].y(), b[i].z());
p[i].x(platformRadius[i%2]*cos(DEG_TO_RAD(platformAngles[i])));
p[i].y(platformRadius[i%2]*sin(DEG_TO_RAD(platformAngles[i])));
p[i].z(0);
//ROS_DEBUG("Platform Positions: (%f, %f, %f)", p[i].x(), p[i].y(), p[i].z());
}
return true;
}
/*
int InverseKinematics::CartToJnt(const KDL::JntArray &q_init,
const KDL::Frame &p_in,
std::vector<KDL::JntArray> &q_out)
{
KDL::JntArray solution;
bool bools[] = { true, false };
// there are no solutions available yet
q_out.clear();
// iterate over all redundant solutions
solution = ik(p_in);
if (isSolutionValid(solution)) q_out.push_back(solution);
if (q_out.size() > 0) {
logger_.write("Inverse kinematics found a solution",
__FILE__, __LINE__);
return 1;
} else {
logger_.write("Inverse kinematics found no solution",
__FILE__, __LINE__);
return -1;
}
}KDL::Frame& g0
*/
int Kinematics::getIK(std::vector<double> &pose, std::vector<double> &joints)
{
if(joints.size() != 7)
return -1;
if(pose.size() != 6)
return -1;
KDL::Vector q, l;
//std::vector<double> joints;
//joints.resize(7);
double R, P, Y, lMag, L, M, N;
KDL::Vector pos(pose[0],pose[1],pose[2]);
R = pose[3];
P = pose[4];
Y = pose[5];
sstr << "Goal Position is: "
<< pos.x() << ","
<< pos.y() << ","
<< pos.z()
<< std::endl;
//ROS_INFO("Goal Position: (%f, %f, %f)", pos.x(), pos.y(), pos.z());
sstr << "RPY is: "
<< R << ","
<< P << ","
<< Y
<< std::endl;
//ROS_INFO("Goal Rotation: (%f, %f, %f)", R, P, Y);
for(unsigned int i = 0; i < 6; i++)
{
//calculate q vector, platform joints wrt base coord system
q.x(p[i].x()*cos(P) + p[i].y()*sin(P)*sin(R) + pos.x());
q.y(p[i].y()*cos(R) + pos.y());
q.z(-p[i].x()*sin(P) + p[i].y()*cos(P)*sin(R) + pos.z() + initialHeight);
//ROS_DEBUG("q[%d] = (%f, %f, %f)", i, q.x(), q.y(), q.z());
//calculate virtual leg length
l = q - b[i];
//ROS_DEBUG("l[%d] = (%f, %f, %f)", i, l.x(), l.y(), l.z());
lMag = l.Norm();
//ROS_DEBUG("lMag[%d] = %f", i, lMag);
L = (lMag*lMag) - (legLength*legLength) + (hornLength*hornLength);
//ROS_DEBUG("L[%d] = %f", i, L);
M = 2*hornLength*(-sin(DEG_TO_RAD(lambda))*sin(DEG_TO_RAD(beta[i]))*(q.x()-b[i].x()) + sin(DEG_TO_RAD(lambda))*cos(DEG_TO_RAD(beta[i]))*(q.y()-b[i].y()) + cos(DEG_TO_RAD(lambda))*(q.z()-b[i].z()));
//ROS_DEBUG("M[%d] = %f", i, M);
N = 2*hornLength*(cos(DEG_TO_RAD(beta[i]))*(q.x()-b[i].x()) + sin(DEG_TO_RAD(beta[i]))*(q.y()-b[i].y()));
//ROS_DEBUG("N[%d] = %f", i, N);
//ROS_DEBUG("sqrt(M^2 + N^2) = %f", sqrt(M*M+N*N));
//ROS_DEBUG("ASIN = %f", asin(L/sqrt(M*M+N*N)));
//ROS_DEBUG("ATAN = %f", atan2(N,M));
joints[i] = asin(L/sqrt(M*M+N*N)) - atan2(N,M);
}
//write yaw to joint6
joints[6] = Y;
//ROS_DEBUG("IK Joint Solution");
//for(unsigned int i = 0; i < 7; i++){
// ROS_DEBUG("Joint %d: %f", i, joints[i]);
//}
for(unsigned int i = 0; i < 7; i++)
{
if(joints[i] < -M_PI_2 || joints[i] > M_PI_2){
ROS_DEBUG("Joint %d out of bounds",i);
return -1;
}
}
//log solution
sstr << "j0: " << joints[0] << std::endl ;
sstr << "j1: " << joints[1] << std::endl ;
sstr << "j2: " << joints[2] << std::endl ;
sstr << "j3: " << joints[3] << std::endl ;
sstr << "j4: " << joints[4] << std::endl ;
sstr << "j5: " << joints[5] << std::endl ;
sstr << "j6: " << joints[6] << std::endl ;
/* KDL::JntArray solution(5);
solution(0) = j1;
solution(1) = j2;
solution(2) = j3;
solution(3) = j4;
solution(4) = j5;
*/
// logger_.write(sstr.str(), __FILE__, __LINE__);
return 1;
}
/*
bool InverseKinematics::isSolutionValid(const KDL::JntArray &solution) const
{
bool valid = true;
if (solution.rows() != 5) return false;
for (unsigned int i = 0; i < solution.rows(); i++) {
if ((solution(i) < min_angles_[i]) || (solution(i) > max_angles_[i])) {
valid = false;
}
}
return valid;
}
*/
| [
"jlane1590@gmail.com"
] | jlane1590@gmail.com |
e0f422db451e30d0cd3ebc2c8a1de26e16414cf3 | a843cc668ce1b67a7b88a6dd257567741804165a | /lv1/vector/std/make.cpp | a71455e2f2605bb595339517ce5ca4d404120553 | [] | no_license | yuxaij/noip_ro | 53aff24527550ae432d1eaf5c41238f7149a070a | 661636f5b829255b5d2019225b9fb28d0fde7b51 | refs/heads/master | 2022-03-06T15:05:06.137717 | 2019-11-06T02:14:12 | 2019-11-06T02:14:12 | 218,312,461 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,473 | cpp | #include <ctime>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <set>
//#include <utility>
const double pi = acos(-1.);
using namespace std;
set <pair<int, int> > t;
int main(int argc, char **argv) {
time_t tn = time(NULL);
srand((unsigned)tn);
int n, mode, a, b, c, d;
sscanf(argv[1], "%d", &n);
sscanf(argv[2], "%d", &mode);
cout << n << endl;
double ang;
int range1 = (int) 2e3, mid1 = (int) 1e3;
int range2 = (int) 2e4, mid2 = (int) 1e4;
if (mode == 0)
c = 0, d = rand() % mid2 + 1;
else
ang = (double) rand() / (~0U>>1) * pi / 2,
c = round(cos(ang) * mid2), d = round(sin(ang) * mid2);
ang = (double) rand() / (~0U>>1) * pi / 2,
a = round(cos(ang) * mid2), b = round(sin(ang) * mid2);
if ((long long) a * d - (long long) b * c <= 0)
swap(a, c), swap(b, d);
cout << a << " " << b << endl;
cout << c << " " << d << endl;
t.insert(make_pair(0, 0));
for (int i = 1; i <= n; ++i) {
int a = 0, b = 0;
while (t.find(make_pair(a, b)) != t.end())
if (rand() & 1)
a = mid1 - rand() % range1, b = mid1 - rand() % range1;
else
a = mid2 - rand() % range2, b = mid2 - rand() % range2;
t.insert(make_pair(a, b));
cout << a << " " << b << endl;
}
while (time(NULL) - tn == 0);
}
| [
"yuxaij@gmail.com"
] | yuxaij@gmail.com |
82de2f4e24d4a3f7be0b6009996da72307523202 | 706a830ce08509b0d2339dfdb8394e321cfe521a | /src/IntersonArrayCxxImagingScanConverter.cxx | e18bbd2707377bd5346a301a02ec27887fa4126d | [
"Apache-2.0"
] | permissive | sjh26/IntersonArraySDKCxx | 0aba595158be1de27f6ed760f1906fa8def85f3a | 119955d168439aedf46c7bc15f121b802779dc43 | refs/heads/master | 2021-01-18T21:35:48.886478 | 2017-03-08T16:41:40 | 2017-03-08T16:41:40 | 84,370,738 | 0 | 0 | null | 2017-03-08T22:07:45 | 2017-03-08T22:07:45 | null | UTF-8 | C++ | false | false | 4,921 | cxx | /*=========================================================================
Library: IntersonArray
Copyright Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
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.
=========================================================================*/
#pragma unmanaged
#include "IntersonArrayCxxImagingScanConverter.h"
#pragma managed
#include <vcclr.h>
#include <msclr/marshal_cppstd.h>
#include <msclr/auto_gcroot.h>
#using "IntersonArray.dll"
namespace IntersonArrayCxx
{
namespace Imaging
{
class ScanConverterImpl
{
public:
ScanConverterImpl()
{
Wrapped = gcnew IntersonArray::Imaging::ScanConverter();
}
~ScanConverterImpl()
{
}
bool GetCompound()
{
return Wrapped->Compound;
}
void SetCompound( bool value )
{
Wrapped->Compound = value;
}
bool GetDoubler()
{
return Wrapped->Doubler;
}
void SetDoubler( bool value )
{
Wrapped->Doubler = value;
}
int GetHeightScan() const
{
return Wrapped->HeightScan;
}
float GetMmPerPixel() const
{
return Wrapped->MmPerPixel;
}
double GetTrueDepth() const
{
return Wrapped->TrueDepth;
}
int GetWidthScan() const
{
return Wrapped->WidthScan;
}
int GetZeroOfYScale() const
{
return Wrapped->ZeroOfYScale;
}
ScanConverter::ScanConverterError HardInitScanConverter( int depth,
int widthScan, int heightScan, int steering, Capture & capture,
ImageBuilding & imageBuilding )
{
msclr::auto_gcroot< IntersonArray::Imaging::Capture ^ >
captureWrapped;
captureWrapped = gcnew IntersonArray::Imaging::Capture();
captureWrapped->RFData = capture.GetRFData();
captureWrapped->FrameAvg = capture.GetFrameAvg();
msclr::auto_gcroot< IntersonArray::Imaging::ImageBuilding ^ >
imageWrapped;
imageWrapped = gcnew IntersonArray::Imaging::ImageBuilding();
return static_cast< ScanConverter::ScanConverterError >( Wrapped->
HardInitScanConverter( depth, widthScan, heightScan, steering,
captureWrapped.get(), imageWrapped.get() ) );
}
ScanConverter::ScanConverterError IdleInitScanConverter( int depth,
int widthScan, int heightScan, short idleId, int idleSteering,
bool idleDoubler, bool idleCompound, int idleCompoundAngle,
ImageBuilding & imageBuilding )
{
msclr::auto_gcroot< IntersonArray::Imaging::ImageBuilding ^ >
imageWrapped;
imageWrapped = gcnew IntersonArray::Imaging::ImageBuilding();
return static_cast< ScanConverter::ScanConverterError >( Wrapped->
IdleInitScanConverter( depth, widthScan, heightScan, idleId,
idleSteering, idleDoubler, idleCompound, idleCompoundAngle,
imageWrapped.get() ) );
}
private:
gcroot< IntersonArray::Imaging::ScanConverter ^ >
Wrapped;
};
#pragma unmanaged
ScanConverter
::ScanConverter():
Impl( new ScanConverterImpl() )
{
}
ScanConverter
::~ScanConverter()
{
delete Impl;
}
bool
ScanConverter
::GetCompound()
{
return Impl->GetCompound();
}
void
ScanConverter
::SetCompound( bool value )
{
Impl->SetCompound( value );
}
bool
ScanConverter
::GetDoubler()
{
return Impl->GetDoubler();
}
void
ScanConverter
::SetDoubler( bool value )
{
Impl->SetDoubler( value );
}
int
ScanConverter
::GetHeightScan() const
{
return Impl->GetHeightScan();
}
float
ScanConverter
::GetMmPerPixel() const
{
return Impl->GetMmPerPixel();
}
double
ScanConverter
::GetTrueDepth() const
{
return Impl->GetMmPerPixel();
}
int
ScanConverter
::GetWidthScan() const
{
return Impl->GetWidthScan();
}
int
ScanConverter
::GetZeroOfYScale() const
{
return Impl->GetZeroOfYScale();
}
ScanConverter::ScanConverterError
ScanConverter
::HardInitScanConverter( int depth, int widthScan, int heightScan,
int steering, Capture & capture, ImageBuilding & imageBuilding )
{
return Impl->HardInitScanConverter( depth, widthScan, heightScan,
steering, capture, imageBuilding );
}
ScanConverter::ScanConverterError
ScanConverter
::IdleInitScanConverter( int depth, int width, int height, short idleId,
int idleSteering, bool idleDoubler, bool idleCompound,
int idleCompoundAngle, ImageBuilding & imageBuilding )
{
return Impl->IdleInitScanConverter( depth, width, height, idleId,
idleSteering, idleDoubler, idleCompound, idleCompoundAngle,
imageBuilding );
}
} // end namespace Imaging
} // end namespace IntersonArrayCxx
| [
"stephen@aylward.org"
] | stephen@aylward.org |
a00488e23cacbd6a56a9cb2ce2190e3cfe0ad922 | edf5e48d8877e5a182193605b9e75b3bca79399d | /src/main/Resources/CppCode/CharSetConvert.cpp | a57b69214a9a208ff7432a884d8deaa33cc0f791 | [] | no_license | LuoYuWuSheng/javaLearn | be1357aea783a4e6ea10ba1ae56ecd0e68bdd762 | 7cd9f7df292cf8ea71ee2a15b3a29db55c11b093 | refs/heads/master | 2020-06-29T07:05:53.356213 | 2017-12-13T13:37:06 | 2017-12-13T13:37:06 | 74,442,602 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,289 | cpp | #include "CharSetConvert.h"
CharSetConvert::CharSetConvert()
{
}
CharSetConvert::~CharSetConvert()
{
}
string CharSetConvert::UnicodeToUTF8 ( const wstring& str )
{
char* pElementText;
int iTextLen;
// wide char to multi char
iTextLen = WideCharToMultiByte ( CP_UTF8, 0, str.c_str(), -1, NULL, 0, NULL, NULL );
pElementText = new char[iTextLen + 1];
memset ( ( void* ) pElementText, 0, sizeof ( char ) * ( iTextLen + 1 ) );
::WideCharToMultiByte ( CP_UTF8, 0, str.c_str(), -1, pElementText, iTextLen, NULL, NULL );
string strText;
strText = pElementText;
delete[] pElementText;
return strText;
}
wstring CharSetConvert::ANSIToUnicode ( const string& str )
{
int len = 0;
len = str.length();
int unicodeLen = ::MultiByteToWideChar ( CP_ACP, 0, str.c_str(), -1, NULL, 0 );
wchar_t * pUnicode;
pUnicode = new wchar_t[unicodeLen + 1];
memset ( pUnicode, 0, ( unicodeLen + 1 ) *sizeof ( wchar_t ) );
::MultiByteToWideChar ( CP_ACP, 0, str.c_str(), -1, ( LPWSTR ) pUnicode, unicodeLen );
wstring rt;
rt = ( wchar_t* ) pUnicode;
delete[] pUnicode;
return rt;
}
wstring CharSetConvert::UTF8ToUnicode ( const string& str )
{
int len = 0;
len = str.length();
int unicodeLen = ::MultiByteToWideChar ( CP_UTF8, 0, str.c_str(), -1, NULL, 0 );
wchar_t * pUnicode;
pUnicode = new wchar_t[unicodeLen + 1];
memset ( pUnicode, 0, ( unicodeLen + 1 ) *sizeof ( wchar_t ) );
::MultiByteToWideChar ( CP_UTF8, 0, str.c_str(), -1, ( LPWSTR ) pUnicode, unicodeLen );
wstring rt;
rt = ( wchar_t* ) pUnicode;
delete[] pUnicode;
return rt;
}
string CharSetConvert::UnicodeToANSI ( const wstring& str )
{
char* pElementText;
int iTextLen;
// wide char to multi char
iTextLen = WideCharToMultiByte ( CP_ACP, 0, str.c_str(), -1, NULL, 0, NULL, NULL );
pElementText = new char[iTextLen + 1];
memset ( ( void* ) pElementText, 0, sizeof ( char ) * ( iTextLen + 1 ) );
::WideCharToMultiByte ( CP_ACP, 0, str.c_str(), -1, pElementText, iTextLen, NULL, NULL );
string strText;
strText = pElementText;
delete[] pElementText;
return strText;
}
string CharSetConvert::ANSIToUTF8 ( const string& str )
{
return UnicodeToUTF8 ( ANSIToUnicode ( str ) );
}
string CharSetConvert::UTF8ToANSI ( const string& str )
{
return UnicodeToANSI ( UTF8ToUnicode ( str ) );
} | [
"z_y_ang@163.com"
] | z_y_ang@163.com |
af63bedc698e6ba3e3a509e4b6827b2dc5789791 | 0ba447ad10da4415235a4aef88f8a33fa3ac85d6 | /OLD/POSN Computer/TrainingFor2/fulltank2.cpp | f6a5325c51f797da1b39d65547fc1c2fe6bb892d | [] | no_license | jojoclt/C | 9aeef9364c17284446cacf7ca2222af5fe5062ad | 30fd09812c6436b28adf742347cb54947ba6a9d7 | refs/heads/master | 2023-01-08T01:50:29.555281 | 2023-01-05T15:19:34 | 2023-01-05T15:19:34 | 174,821,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,722 | cpp | #include<bits/stdc++.h>
using namespace std;
const int MAXN = 2e5+1;
struct road{
int y,p,t;
bool operator <(road a)const{
return a.p<p;
}
};
struct coor{
int y,v;
};
priority_queue<road>pq;
vector<coor>a[MAXN];
int mem[MAXN][101];
int p[1000];
int n,m,t[1000],s[1000],e[1000];
int main(){
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)scanf("%d",&p[i]);
int x,y,v;
for(int i=0;i<m;i++){
scanf("%d %d %d",&x,&y,&v);
a[x].push_back({y,v});
a[y].push_back({x,v});
}
int k;
scanf("%d",&k);
for(int f=0;f<k;f++){
scanf("%d%d%d",&t[f],&s[f],&e[f]);
}
for(int f=0;f<k;f++){
for(int i=1;i<=n;i++)for(int j=0;j<=t[f];j++)mem[i][j]=1e9;
mem[s[f]][0]=0;
pq.push({s[f],0,0});
int par=0;
while(!pq.empty()){
road g=pq.top();
pq.pop();
if(g.y==e[f]){
printf("%d\n",mem[e[f]][g.t]);
par++;
break;
}
int u=g.p;
for(int i=g.t;i<=t[f];i++){
for(int j=0;j<a[g.y].size();j++){
if(mem[a[g.y][j].y][i-a[g.y][j].v]>u&&a[g.y][j].v<=i){
//printf("from %d to %d i=%d >= a[g.y][j]=%d",g.y,a[g.y][j],i,a[g.y][j].y);
mem[a[g.y][j].y][i-a[g.y][j].v]=u;
//printf(" u=%d\n",u);
pq.push({a[g.y][j].y,mem[a[g.y][j].y][i-a[g.y][j].v],i-a[g.y][j].v});
}
}
u+=p[g.y];
}
}
if(!par)printf("impossible\n");
}
}
/*
5 5
10 10 20 12 13
0 1 9
0 2 8
1 2 1
1 3 11
2 3 7
2
10 0 3
20 1 4
*/
| [
"Chalanthorn_jojo@Hotmail.com"
] | Chalanthorn_jojo@Hotmail.com |
4947b414e9827fde8d01d526a34be9a88988a0af | 4910ef8b690e110ccf279609290548dd6b70e5b4 | /chapter_7/exer_sec_7_1_4/sales.cc | 63d081c454dcc2bb06983dc1c8d7f7b993b02506 | [] | no_license | poetchess/cpprunner | a6653d4c2e007f7f55246bcb5adf00474c092e72 | 6cef9495c12a934b4414b690193426cd41eb1522 | refs/heads/master | 2021-01-21T11:24:25.081439 | 2017-05-04T15:21:57 | 2017-05-04T15:21:57 | 83,566,873 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,779 | cc | #include <iostream>
#include <string>
#include "Sales_data.h"
using std::cin; using std::cout; using std::cerr; using std::endl;
using std::string;
using std::istream; using std::ostream;
// This function is intended to act like the compound assignment operator '+='.
// When we define a function that operates like a built-in operator, our
// function should mimic the behavior of that operator. The built-in
// assignment operators return their left-hand operand as an lvalue. To return
// an lvalue, our combine function must return a reference.
Sales_data & Sales_data::combine(const Sales_data &rhs)
{
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
// Although the function defines operation that is conceptually part of the
// interface of the class, it is not part of the class itself.
istream &read(istream &is, Sales_data &sd)
{
double price = 0;
is >> sd.bookNo >> sd.units_sold >> price;
sd.revenue = price * sd.units_sold;
return is;
}
ostream &print(ostream &os, const Sales_data &sd)
{
os << sd.bookNo << " " << sd.units_sold << " "
<< sd.revenue << " " << sd.avg_price();
return os;
}
Sales_data add(const Sales_data &lhs, const Sales_data &rhs)
{
Sales_data sum = lhs;
sum.combine(rhs);
return sum;
}
int main() {
Sales_data total(cin);
if (!cin) {
cerr << "No data?!" << endl;
return -1;
}
while (cin) {
Sales_data trans(cin);
if (cin) {
if (total.isbn() == trans.isbn()) {
total.combine(trans);
}
else {
print(cout, total) << endl;
total = trans;
}
}
}
print(cout, total) << endl;
return 0;
}
| [
"ilvbaicai@126.com"
] | ilvbaicai@126.com |
61dfa9c447bdc9f3074256b3056db9d5d8af8a22 | 45229380094a0c2b603616e7505cbdc4d89dfaee | /lstm/app/LSTM/neuralNetBase.cpp | f5ad42c243239f707c2f3de803f99eb084cea350 | [] | no_license | xcud/msrds | a71000cc096723272e5ada7229426dee5100406c | 04764859c88f5c36a757dbffc105309a27cd9c4d | refs/heads/master | 2021-01-10T01:19:35.834296 | 2011-11-04T09:26:01 | 2011-11-04T09:26:01 | 45,697,313 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 15,786 | cpp | // NeuralNetBase.cpp
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <string>
//#include <new.h> // for memory error handling
//#include <ctype.h>
//#include <unistd.h> // sleep
//#include <termios.h> // struct termios
#include <fcntl.h>
//#include <sys/param.h>
#include <math.h>
#include <errno.h>
#include <time.h>
#include "neuralNetBase.h"
#define lrand48 rand
#define drand48 drand
#define M_PI 3.14159265358979323846
double drand()
{
union
{
double d;
unsigned char c[8];
} r;
int i;
for( i = 0 ; i < 7; ++i )
{
r.c[i] = rand() & 0xff;
}
r.c[6] |= 0xf0;
r.c[7] = 0x3f;
return r.d - 1.;
}
////TEpoLogBuf
TEpoLogBuf::TEpoLogBuf() {
BufInUse=false; BufEpo=NULL; BufVal=NULL; BufMin=NULL; BufMax=NULL;
}
TEpoLogBuf::~TEpoLogBuf()
{
if((!BufEpo || !BufVal) && BufInUse) {
cerr << "NULL buffer to delete." << endl; exit(1);
} else { delete[] BufEpo; delete[] BufVal; }
if(BufMin) delete[] BufMin; if(BufMax) delete[] BufMax;
}
void TEpoLogBuf::Init( unsigned int MaxBuf,
unsigned int aAverageBuf,
char* aBufName)
{
BufInUse=true;
AverageBuf = aAverageBuf; strcpy(BufName, aBufName);
if(AverageBuf>0) Max = (int)ceil((double)MaxBuf/AverageBuf);
else { cerr << "AverageBuf=0." << endl; exit(1); }
BufEpo = new unsigned int[Max]; BufVal = new double[Max];
if(!BufEpo || !BufVal) {cerr<<"NULL buffer after new."<<endl; exit(1);}
// Inti the Min-Max buffers.
if(AverageBuf>1) {
BufMin = new double[Max]; BufMax = new double[Max];
if(!BufMin || !BufMax){cerr<<"NULL buffer after new."<<endl; exit(1);}
}
Reset();
}
void TEpoLogBuf::Reset() {
NbVal = 0; AverageCount=0;
for(unsigned int i=0;i<Max;i++) { BufEpo[i]=0; BufVal[i]=0; }
}
void TEpoLogBuf::AddValue(unsigned int aEpo, double aVal) {
// Here index shift Epo = 1,...MaxEpochs -> 0,...MaxEpochs-1
if(AverageBuf>1) { // Update the min and max of averaged values.
if(!AverageCount) { ValMin=aVal; ValMax=aVal; // First Val.
} else { if(aVal<ValMin) ValMin=aVal; if(aVal>ValMax) ValMax=aVal; }
}
BufEpo[NbVal] = aEpo;
BufVal[NbVal] += aVal;
AverageCount++;
if(AverageCount==AverageBuf) {
BufVal[NbVal]/=AverageBuf;
if(AverageBuf>1) { BufMin[NbVal]=ValMin; BufMax[NbVal]=ValMax; }
NbVal++; AverageCount=0;
}
if(NbVal>Max) {
cerr <<BufName<<": "
<<"Epo:"<<aEpo<<"("<<aVal<<") "
<<"NbVal("<<NbVal<<")>=Max("<<Max<<") in Buffer."
<<"AverageCount:"<<AverageCount<<" "
<<"AverageBuf:"<<AverageBuf<<" "
<<endl; exit(1); }
}
////TNeuralNetBase
TNeuralNetBase::TNeuralNetBase()
{
// Remove files and clear screen.
if(DirContainsFile(true, ERRORLOGFILE)) remove(ERRORLOGFILE);
if(DirContainsFile(true, TEST_ERRORLOGFILE))
remove(TEST_ERRORLOGFILE);
if(DirContainsFile(true, TEST_MSELOGFILE)) remove(TEST_ERRORLOGFILE);
if(DirContainsFile(true, MSELOGFILE)) remove(MSELOGFILE);
if(DirContainsFile(true, TEST_STATUS_LOGFILE))
remove(TEST_STATUS_LOGFILE);
if(DirContainsFile(true, GROWLOGFILE)) remove(GROWLOGFILE);
if(DirContainsFile(true, DUMP_FILE)) remove(DUMP_FILE);
if(DirContainsFile(true, WEIGHTMEAN_LOGFILE))
remove(WEIGHTMEAN_LOGFILE);
if(DirContainsFile(true, ALPHAMEAN_LOGFILE))
remove(ALPHAMEAN_LOGFILE);
if(DirContainsFile(true, OUT_LOGFILE))
remove(OUT_LOGFILE);
// system("clear"); // !!Causes stop in bg job!!
//printf("\033[0;H\007"); // position curser (0,0) (row,colm)
//printf("\033[0J\007"); // Clear Below
// Init user interaction.
cKey = ' ';
// pF.precision(PRECISION);
one=1;
// Init debug and watch variables.
OutputDebug=false;
}
TNeuralNetBase::~TNeuralNetBase() {}
char TNeuralNetBase::Run() { if( Init() ) return 1; return 0; }
char TNeuralNetBase::Init()
{
#ifdef DEBUG
cout << "TNeuralNetBase::Init........." << endl;
#endif
// See how fast we are in sec.
start_time= time(NULL);
// Read first part of par file already here to know NbTrials.
if(TNeuralNetBase::LoadPar()) {
cerr<<"Error in NeuralNetBase::Init : LoadPar."<<endl; return 1; }
// Init random generator
if(RandomSeed==0) { time_t t; RandomSeed = (long) time(&t); }
// srand48(RandomSeed);
// Init EpoLogBuf
#ifdef BUFFER_EPO_LOG
TrainMSEEpoLogBuf.Init(MaxEpochs+EpochsAfterLearned, AverageTrainBuf,
"TrainMSEEpoLogBuf");
if(!NoClassesOnlyPredict)
TrainErrEpoLogBuf.Init(MaxEpochs+EpochsAfterLearned, AverageTrainBuf,
"TrainErrEpoLogBuf");
unsigned int TME; // Test buffer one longer for the final test.
if(TestEach_Epo) TME=TestEach_Epo; else TME=TestMaxEach_Epo;
if(!NoClassesOnlyPredict)
TestErrEpoLogBuf.
Init((int)
ceil((double)(MaxEpochs+EpochsAfterLearned)/TME)+1,1,
"TestErrEpoLogBuf");
TestMSEEpoLogBuf.
Init((int) ceil((double)(MaxEpochs+EpochsAfterLearned)/TME)+1,1,
"TestMSEEpoLogBuf");
#endif
// Init Pattern.
TrainData.Generalize=0;
TestData.Generalize=Test_Generalize;
FreezeSeqLoop=false;
#if !defined(DO_ONLINE_PAT_PRODUCTION)
FreezeSeqLoop=false;
if(Generate_Pat) {
// Test.
Set_RefData(&TestDataOrg,false,false,true);
Set_LoopAllSeqs(Generate_Pat_NbLoopAllSeqs_Test);
GeneratePattern(TestData, Pat_FuncName);
// Train.
Set_RefData(&TrainDataOrg,true,true,true);
Set_LoopAllSeqs(Generate_Pat_NbLoopAllSeqs_Train); // Stays set.
GeneratePattern(TrainData, Pat_FuncName);
} else {
if(LoadTrainPattern()) return 1; // from PatternFile
if(LoadTestPattern()) return 1; // from PatternFile
if(PredictionOffset>0)
//For prediction task:f*dy(t-1),y(t),f*dy(t),y(t+T)
// start with y(t).
//->y(t),y(t+T)
TransPat2StepByStepPredict(
NbIn,NbOut,
1, //NbPredictInputs, task dependent.
PredictionOffset,
PredictAllUntilOffset);
if(PredictDiff) {
//->y(t),y(t+T),dy(t-1)
Add_IODiff(1);
//->y(t),y(t+T),f*dy(t-1)
PredictDiffFactor = Scale_IODIff(PredictDiff,2);
//->f*dy(t-1),y(t),y(t+T),f*dy(t-1)
//Add_IODiff2Input();// Then: FlipO1O2(2,3);
//->f*dy(t-1),y(t),f*dy(t),y(t+T)
FlipO1O2(1,2);
//if(PredictOnlyDiff)
//Trans2IODiff(PredictDiff);
//else Add_IODiff(PredictDiff);
}
// Split the series into PredictionOffset sequences dep. on offset.
if((PredictionOffset>1) && !TimeWindowSize) {
SplitPredictionOffset(PredictionOffset);
}
if(TimeWindowSize) {
// Add_IODiff(1);
//PredictDiffFactor = Scale_IODIff(PredictDiff,2);
Add_TimeWindow(NbIn/TimeWindowSize,
TimeWindowSize,TimeWindowStepSize);
// //ddd
// for(unsigned int seq=0;seq<TrainData.NbSeq;seq++) {
// for(unsigned int pat=0;pat<TrainData.NbPat[seq];pat++) {
// cout<<pat<<" ";
// for(unsigned int val=0;val<TrainData.NbVal;val++) {
// cout<<((TrainData.SeqList[seq])[pat])[val]<<" "; }
// cout<<"\n"; }
// cout<<"\n"; }
// exit(0);//ddd
//->y(t),...,dy(t-1),y(t+T)
//FlipO1O2(NbIn,NbIn+1);
}
// Modify the NbIn not to include the Diff outputs.
unsigned int NbOutMSE=NbOut;
// Detemine which units contribute to the MSE:
if(PredictDiff && !PredictOnlyDiff) NbOutMSE/=2;
#ifndef STAT_OUT
CalcPatStatisticsAll(NbIn,NbOutMSE);
#else
// Considder only the stat outs.
CalcPatStatisticsAll(NbIn+NbOut,NbOutMSE);
#endif
}
// exit(0);//ddd
#else
if(!SetStepTarget) FreezeSeqLoop=true;
#ifdef SETSTEPTARGET_BUT_COUNT_SEQUENCEWISE
FreezeSeqLoop=true;
#endif
#endif
//SaveTrainPattern(); exit(0); // For debug.
// Init general network stuff.
ClampOut=false;
#ifdef UPDATE_WEIGHTS_AFTER_SEQ
update_weights_after_seq=UPDATE_WEIGHTS_AFTER_SEQ;
#endif
// Init Done.
#ifdef DEBUG
cout << "TNeuralNetBase::Init done." << endl;
#endif
return 0;
}
char TNeuralNetBase::LoadPar()
{
#ifdef DEBUG
cout<<"TNeuralNetBase::LoadPar......."<<endl;//ddd
#endif
int errStatus = 0;
fstream pF;// = new ifstream();
sprintf(cBuf,PARFILE);
if (OpenFile(&pF,cBuf,ios::in)) return 1;
if (ReadComment(&pF)) return 1;
errStatus = loadOnePara( "NbTrials:", pF, NbTrials );
errStatus = loadOnePara( "RandomSeed:", pF, RandomSeed );
errStatus = loadOnePara( "MaxEpochs:", pF, MaxEpochs );
errStatus = loadOnePara( "AverageTrainBuf:", pF, AverageTrainBuf );
errStatus = loadOnePara( "MaxOnlineStreamLengthTrain:", pF, MaxOnlineStreamLengthTrain );
errStatus = loadOnePara( "MaxOnlineStreamLengthTest:", pF, MaxOnlineStreamLengthTest );
errStatus = loadOnePara( "EpochsAfterLearned:", pF, EpochsAfterLearned );
errStatus = loadOnePara( "MaxMSE:", pF, MaxMSE );
errStatus = loadOnePara( "MaxMSEGenTest:", pF, MaxMSEGenTest );
errStatus = loadOnePara( "MSEStop:", pF, MSEStop );
errStatus = loadOnePara( "WinnerTakesAll:", pF, WinnerTakesAll );
errStatus = loadOnePara( "TestEach_Epo:", pF, TestEach_Epo );
errStatus = loadOnePara( "TestMaxEach_Epo:", pF, TestMaxEach_Epo );
errStatus = loadOnePara( "TestMinEach_Epo:", pF, TestMinEach_Epo );
errStatus = loadOnePara( "TestEpochs:", pF, TestEpochs );
errStatus = loadOnePara( "DumpBestNotLastTest:", pF, DumpBestNotLastTest );
errStatus = loadOnePara( "AlphaBase:", pF, AlphaBase );
errStatus = loadOnePara( "Alpha_ROH:", pF, Alpha_ROH );
errStatus = loadOnePara( "Alpha_MUE:", pF, Alpha_MUE );
errStatus = loadOnePara( "AlphaError:", pF, AlphaError );
errStatus = loadOnePara( "SetStepTarget:", pF, SetStepTarget );
errStatus = loadOnePara( "AllTimeTarget:", pF, AllTimeTarget );
errStatus = loadOnePara( "NoClassesOnlyPredict:", pF, NoClassesOnlyPredict );
errStatus = loadOnePara( "PredictionOffset:", pF, PredictionOffset );
errStatus = loadOnePara( "PredictAllUntilOffset:", pF, PredictAllUntilOffset );
errStatus = loadOnePara( "PredictDiff:", pF, PredictDiff );
errStatus = loadOnePara( "PredictOnlyDiff:", pF, PredictOnlyDiff );
errStatus = loadOnePara( "RandomPrediction:", pF, RandomPrediction );
errStatus = loadOnePara( "Reverse_Input:", pF, Reverse_Input );
errStatus = loadOnePara( "ClampOutPredictSteps:", pF, ClampOutPredictSteps );
errStatus = loadOnePara( "ClampOutTrainPredictSteps:", pF, ClampOutTrainPredictSteps );
errStatus = loadOnePara( "TimeWindowSize:", pF, TimeWindowSize );
errStatus = loadOnePara( "TimeWindowStepSize:", pF, TimeWindowStepSize );
errStatus = loadOnePara( "NoResetBeforeTest:", pF, NoResetBeforeTest );
errStatus = loadOnePara( "GrowNet:", pF, GrowNet );
errStatus = loadOnePara( "FreezeAndGrow:", pF, FreezeAndGrow );
errStatus = loadOnePara( "GrowFullyNotCascade:", pF, GrowFullyNotCascade );
errStatus = loadOnePara( "GrowFirstOrder:", pF, GrowFirstOrder );
errStatus = loadOnePara( "LogErrRecSize:", pF, LogErrRecSize );
errStatus = loadOnePara( "PartLogErrRecSize:", pF, PartLogErrRecSize );
errStatus = loadOnePara( "TRAINPATFILE:", pF, cTrainPatFilename );
errStatus = loadOnePara( "TESTPATFILE:", pF, cTestPatFilename );
errStatus = loadOnePara( "MixTrainSeqs:", pF, MixTrainSeqs );
errStatus = loadOnePara( "Generate_Pat:", pF, Generate_Pat );
errStatus = loadOnePara( "Generate_Pat_Each_Epoch:", pF, Generate_Pat_Each_Epoch );
errStatus = loadOnePara( "Generate_Pat_NbLoopAllSeqs_Test:", pF, Generate_Pat_NbLoopAllSeqs_Test );
errStatus = loadOnePara( "Generate_Pat_NbLoopAllSeqs_Train:", pF, Generate_Pat_NbLoopAllSeqs_Train );
errStatus = loadOnePara( "Test_Generalize:", pF, Test_Generalize );
errStatus = loadOnePara( "Pat_FuncName:", pF, Pat_FuncName );
errStatus = loadOnePara( "NbIn:", pF, NbIn );
errStatus = loadOnePara( "NbOut:", pF, NbOut );
errStatus = loadOnePara( "NbStatOut:", pF, NbStatOut );
errStatus = loadOnePara( "NbHidden:", pF, NbHidden );
errStatus = loadOnePara( "InitWeightRange:", pF, InitWeightRange );
errStatus = loadOnePara( "OutUnitBiasInitWeight:", pF, OutUnitBiasInitWeight );
errStatus = loadOnePara( "InOutBiasForMatchingUnits:", pF, InOutBiasForMatchingUnits );
errStatus = loadOnePara( "HiddenUnitBiasInitWeight:", pF, HiddenUnitBiasInitWeight );
// cout<<"HiddenUnitBiasInitWeight:"<<HiddenUnitBiasInitWeight<<endl;//ddd
// cout<<"NbOut:"<<NbOut<<endl;//ddd
// cout<<"NbStatOut:"<<NbStatOut<<endl;//ddd
// cout<<"TNeuralNetBase::LoadPar done.\n"<<endl;//ddd
CloseFile(&pF);
return errStatus;
}
char TNeuralNetBase::WriteLogfileEpo(char *FileName, double val) {
fstream pF;
if (OpenFile(&pF,FileName, ios::app)) return 1;
pF << Epo << " " << val << "\n";
return CloseFile(&pF);
}
char TNeuralNetBase::WriteLogfileEpo(char *FileName,
double val0, double val1) {
fstream pF;
if (OpenFile(&pF,FileName, ios::app)) return 1;
pF << Epo << " " << val0 << " " << val1 << "\n";
return CloseFile(&pF);
}
char TNeuralNetBase::FlushEpoLogBuf(char *FileName, TEpoLogBuf &EpoLogBuf) {
fstream pF;
if (OpenFile(&pF,FileName, ios::app)) return 1;
// Get the last (maybe incomplete) average right.
if(EpoLogBuf.AverageCount>0) {
EpoLogBuf.BufVal[EpoLogBuf.NbVal] /= EpoLogBuf.AverageCount;
if(EpoLogBuf.AverageBuf>1) {
EpoLogBuf.BufMin[EpoLogBuf.NbVal]=EpoLogBuf.ValMin;
EpoLogBuf.BufMax[EpoLogBuf.NbVal]=EpoLogBuf.ValMax; }
EpoLogBuf.NbVal++;
}
for(unsigned int i=0;i<EpoLogBuf.NbVal;i++){
pF << EpoLogBuf.BufEpo[i] << " " << EpoLogBuf.BufVal[i] << "\n";
if(EpoLogBuf.AverageBuf>1) {
pF << EpoLogBuf.BufEpo[i] << " " << EpoLogBuf.BufMin[i] << "\n";
pF << EpoLogBuf.BufEpo[i] << " " << EpoLogBuf.BufMax[i] << "\n";
// Again for gnuplots linespoints.
pF << EpoLogBuf.BufEpo[i] << " " << EpoLogBuf.BufVal[i] << "\n";
}
}
return CloseFile(&pF);
}
char TNeuralNetBase::WriteOnlinePatTicks(char *FileName, double val) {
fstream pF;
if (OpenFile(&pF,FileName, ios::app)) return 1;
pF << Pat << " " << val << "\n";
return CloseFile(&pF);
}
void TNeuralNetBase::NewWeight(TWeight *&pW, unsigned int size) {
pW = new TWeight[size];
for(unsigned int i=0;i<size;i++) {
for(unsigned int o=0;o<ORDER_WEIGHT;o++) {
pW[i].w[o] = InitWeightRange*(drand48()*2-1);
#ifdef UPDATE_WEIGHTS_AFTER_SEQ
pW[i].Dw[o] = 0;
#endif
#ifdef MOMENTUM
pW[i].Dw_t1[o] = 0;
#endif
#ifdef LOCAL_ALPHA
pW[i].alpha[o] = AlphaBase;
//pW[i].h = 0;
#endif
}
}
}
void TNeuralNetBase::NewWeight(TWeight *&pW, unsigned int size,
double InitWeight) {
NewWeight(pW,size);
if(InitWeight) for(unsigned int i=0;i<size;i++)
for(unsigned int o=0;o<ORDER_WEIGHT;o++)
pW[i].w[o] = InitWeight;
}
void TNeuralNetBase::NewWeight(TWeight &W, double InitWeight) {
// For bias weights.
TWeight *pWtmp; NewWeight(pWtmp,1);
for(unsigned int o=0;o<ORDER_WEIGHT;o++) {
W.w[o] = pWtmp[0].w[o];
#ifdef UPDATE_WEIGHTS_AFTER_SEQ
W.Dw[o] = pWtmp[0].Dw[o];
#endif
#ifdef MOMENTUM
W.Dw_t1[o] = 0;
#endif
#ifdef LOCAL_ALPHA
W.alpha = pWtmp[0].alpha;
//W.h = pWtmp[0].h;
#endif
if(InitWeight)
W.w[o] = InitWeight; // else stay random.
}
delete[] pWtmp;
}
void TNeuralNetBase::NewWeight(double *&pW, unsigned int size) {
pW = new double [size];
for(unsigned int i=0;i<size;i++) pW[i]= InitWeightRange*(drand48()*2-1);
}
| [
"perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671"
] | perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671 |
6c4fbb4605a96beed69fbf5c229f19a8cf7118f7 | 0e33f73f57cf55b30bfec119a408508df4d8d7cd | /rozproszone2/rozproszone2/rozproszone2.cpp | e3e4cf078034ff12d6943bde343975450d0e47d2 | [] | no_license | Darooks/ProjectsBackup | 4a0bfadd713427437b9ebf74b629cf4885267f1e | 32e4e786533735175ce252c8df3a7951efbda851 | refs/heads/master | 2021-05-29T21:40:38.273567 | 2015-04-22T10:46:43 | 2015-04-22T10:46:43 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 2,529 | cpp | #include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <mutex>
//---------------------------------------------------------------------------
#pragma argsused
struct dane_dla_watku // tablica zawiera dane, ktore otrzymaja wątki
{
char nazwa[50];
int parametr;
int id;
} dane[3] = { { "[1]", 5, 1 }, { "[2]", 8, 2 },
{ "[3]", 12, 3 } };
// priorytety wątków
int priorytety[3] = { THREAD_PRIORITY_BELOW_NORMAL,
THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL };
HANDLE watki[3]; // dojścia (uchwyty) wątków
// deklaracja funkcji wątku
DWORD WINAPI funkcja_watku(void *argumenty);
std::mutex gateKeeper;
//---------------------------------------------------------------------------
int main(int argc, char **argv)
{
//gateKeeper.lock();
//gateKeeper.lock();
int i;
DWORD id; // identyfikator wątku
system("cls");
printf("Uruchomienie programu\n");
// tworzenie wątków
for (i = 0; i < 3; i++)
{
watki[i] = CreateThread(
NULL, // atrybuty bezpieczeństwa
0, // inicjalna wielkość stosu
funkcja_watku, // funkcja wątku
(void *)&dane[i],// dane dla funkcji wątku
0, // flagi utworzenia
&id);
if (watki[i] != INVALID_HANDLE_VALUE)
{
printf("Utworzylem watek %s o identyfikatorze %x\n",
dane[i].nazwa, id);
// ustawienie priorytetu
SetThreadPriority(watki[i], priorytety[i]);
}
}
//gateKeeper.unlock();
//gateKeeper.lock();
Sleep(20000); // uśpienie wątku głównego na 20 s
for (int i = 0; i < 3; i++)
{
CloseHandle(watki[i]);
}
//ExitThread(funkcja_watku);
return 0;
}
void gotoxy(int x, int y)
{
COORD c;
c.X = x - 1;
c.Y = y - 1;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
//---------------------------------------------------------------------------
// trzy takie funkcje pracują współbieżnie w programie
DWORD WINAPI funkcja_watku(void *argumenty)
{
unsigned int licznik = 0;
unsigned int licznik2 = 0;
// rzutowanie struktury na własny wskaźnik
struct dane_dla_watku *moje_dane = (struct dane_dla_watku *)argumenty;
// wyświetlenie informacji o uruchomieniu
gateKeeper.lock();
gotoxy(1, moje_dane->parametr);
printf("%s", moje_dane->nazwa);
gateKeeper.unlock();
Sleep(10);
// praca, wątki sa terminowane przez zakończenie programu
// - funkcji main
while (1)
{
gateKeeper.lock();
gotoxy(licznik++ / 5000 + 5, moje_dane->parametr);
printf("%d", moje_dane->id);
gateKeeper.unlock();
}
//for (int i = 0; i < 3; i++)
//ExitThread(watki[i]);
return 0;
}
// | [
"karol.jurczenia@gmail.com"
] | karol.jurczenia@gmail.com |
e8e2205ae083c0ac2250a06d57bd10cf42c39241 | 331b63e262e8ac515328f22f97efd0cc3ebb11af | /src/AnalogButtons.h | bbd1442c37431afbae23332e367bab3b58bd8ca1 | [] | no_license | per1234/ArduinoButtons | a465f637825bcf194ca3913905705144e28f702a | 0fcfec65219e8443c32b3769880b2c96e274b55c | refs/heads/master | 2020-03-20T12:06:44.752014 | 2017-02-27T21:26:11 | 2017-02-27T21:26:11 | 137,420,967 | 0 | 0 | null | 2018-06-15T00:02:05 | 2018-06-15T00:02:04 | null | UTF-8 | C++ | false | false | 1,064 | h | /*
class for hookup of up to 8 buttons to one analog pin
using resistors as voltage dividers using this schematics
only one button can be pressed at a time
VCC <---+-[ R0 ]-+-[ R1 ]-+-[ R1 ]- ... +-[ Rn-1 ]-+--> GND
| | | | |
[B0] [B1] [B2] [Bn-1] [Rx]
A <---+--------+--------+----- .... --+----------+
the following should be observed
Ri = Rj for i, j from (0..n-1)
Sum (Ri) for i from (0..n-1) = 10kOhm
Rx = 10kOhm
*/
#ifndef ANALOGBUTTONS_H
#define ANALOGBUTTONS_H
#include "Arduino.h"
#include "Buttons.h"
class AnalogButtons: public Buttons {
public:
uint8_t pin;
uint16_t t[8];
AnalogButtons(uint8_t apin, uint16_t t0, uint16_t t1, uint16_t t2, uint16_t t3, uint16_t t4); // constructor for 5 buttons
void init(uint16_t t0, uint16_t t1, uint16_t t2, uint16_t t3, uint16_t t4, uint16_t t5, uint16_t t6, uint16_t t7);
uint8_t getState();
private:
}; //end of class Buttons
#endif
| [
"gitcow@cano.sk"
] | gitcow@cano.sk |
c0fac074b6b21e93230e533ed232cfcf6f273e83 | a07ef0f62eaa875ac69fc267908bd1169bbf9bfd | /src/data_util.cpp | 58c432238b1d8d6495b8b413330cc49cb3f5ecc1 | [
"MIT"
] | permissive | YitongFeng/OPQ_MultiIndex | c7826e7fea19603ce82e301b7701dd524440daa8 | 565f2ab7e860dda66cede700ae7564a9a86854fb | refs/heads/master | 2021-01-11T23:31:02.550055 | 2017-02-14T07:19:07 | 2017-02-14T07:19:07 | 78,592,501 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,686 | cpp | // Copyright 2012 Yandex Artem Babenko
#include "stdafx.h"
#include "data_util.h"
void splitString(string inString, vector<string> &sp){
inString += " ";
int size = inString.size();
int st = 0;
int pos = inString.find(" ", 0);
while (pos<size && pos != inString.npos){
string tmp = inString.substr(st, pos - st);
st = pos + 1;
//最后一个是空格
if (st<size){
pos = inString.find(" ", st);
}
else{
break;
}
//防止最后有很多空格
if (tmp != " " && tmp != ":"){
sp.push_back(tmp);
}
}
}
void loadGt(const string gt_file, string imgFold, unordered_map<string, vector<pair<string, int>>>& gtOrder){
// 加载 gt
ifstream gtFile(gt_file);
vector<string> gtList;
int gtNum = 0;
string tmpTline;
while (getline(gtFile, tmpTline)){
//gtFile >> tmpTline;
if (tmpTline == "\n" || tmpTline == ""){ continue; }
tmpTline += " ";
vector<string > tmp;
splitString(tmpTline, tmp);
if (tmp.empty()) continue;
/*for (int k = 0; k < tmp.size(); k++){
tmp[k] = imgFold + "\\" + tmp[k];
}*/
string gtName = tmp[0];
gtList.push_back(gtName);
vector<pair<string, int>> tmpQ;
for (int i = 0; i < tmp.size() - 1; i++){
pair<string, int> tmpP;
// 此gtfile含有原图 需要去除原图
if (tmp[i + 1] != tmp[0]){
tmpP = make_pair(tmp[i + 1], 1);
tmpQ.push_back(tmpP);
}
}
gtOrder[gtName] = tmpQ;
gtNum++;
//cout << "gen gt num: " << gtNum << " : " << gtName << endl;
//cout << gtOrder[gtName][0].first << endl;
}
//fclose(gtFile);
}
void loadDbOrQuery(const string data_file, const string pathfile, vector<pair<string, Point>>& data, PointType query_point_type){
if (data.size() == 0)
cerr << "DB size is 0, didn't initialize!" << endl;
Points data_feas;
if (query_point_type == BVEC) {
ReadPoints<unsigned char, Coord>(data_file, &data_feas, data.size());
}
else if (query_point_type == FVEC) {
ReadPoints<float, Coord>(data_file, &data_feas, data.size());
}
vector<string> paths;
paths.resize(data.size());
ifstream path_file(pathfile);
for (int i = 0; i < paths.size(); i++)
path_file >> paths[i];
data.resize(paths.size());
for (int i = 0; i < data.size(); i++){
data[i] = make_pair(paths[i], data_feas[i]);
}
cout << "Data are read ...\n";
}
Distance Eucldistance(const Point& x, const Point& y) {
Distance result = 0;
Distance current_coord_diff;
for (Dimensions d = 0; d < x.size(); ++d){
current_coord_diff = x[d] - y[d];
result += current_coord_diff * current_coord_diff;
}
return result;
}
Distance Eucldistance(const Point& x, const Point& y,
const Dimensions start, const Dimensions finish) {
Distance result = 0;
Distance current_coord_diff;
for (Dimensions d = start; d < finish; ++d){
current_coord_diff = x[d] - y[d - start];
result += current_coord_diff * current_coord_diff;
}
return result;
}
void GetSubpoints(const Points& points,
const Dimensions start_dim,
const Dimensions final_dim,
Points* subpoints) {
if (final_dim < start_dim) {
throw std::logic_error("Final dim < Start dim");
}
subpoints->resize(points.size());
for (PointId pid = 0; pid < points.size(); ++pid) {
subpoints->at(pid).resize(final_dim - start_dim);
for (Dimensions dim = start_dim; dim < final_dim; ++dim) {
subpoints->at(pid)[dim] = points[pid][start_dim + dim];
}
}
}
ClusterId GetNearestClusterId(const Point& point,
const Centroids& centroids,
const Dimensions start_dim,
const Dimensions final_dim) {
if (final_dim < start_dim) {
throw std::logic_error("Final dim < Start dim");
}
ClusterId nearest = 0;
Distance min_distance = Eucldistance(point, centroids[0], start_dim, final_dim);
for (PointId pid = 1; pid < centroids.size(); ++pid) {
Distance current_distance = 0;
current_distance = Eucldistance(point, centroids[pid], start_dim, final_dim);
if (current_distance < min_distance) {
min_distance = current_distance;
nearest = pid;
}
}
return nearest;
}
void GetResidual(const Point& point, const CoarseQuantization& coarse_quantizations,
const vector<Centroids>& centroids, Point* residual)
{
residual->resize(point.size());
Dimensions subvector_dimension = point.size() / centroids.size();
cblas_saxpy(point.size(), 1, &(point[0]), 1, &(residual->at(0)), 1);
for (int subvector_index = 0; subvector_index < centroids.size(); ++subvector_index) {
Dimensions start_dim = subvector_index * subvector_dimension;
const Point& current_coarse_centroid = centroids[subvector_index][coarse_quantizations[subvector_index]];
cblas_saxpy(subvector_dimension, -1, &(current_coarse_centroid[0]), 1, &(residual->at(start_dim)), 1);
}
}
void GetResidual(const Point& point, const CoarseQuantization& coarse_quantizations,
const vector<Centroids>& centroids, Coord* residual) {
Dimensions subvector_dimension = point.size() / centroids.size();
cblas_scopy(point.size(), &(point[0]), 1, residual, 1);
for (int subvector_index = 0; subvector_index < centroids.size(); ++subvector_index) {
Dimensions start_dim = subvector_index * subvector_dimension;
const Point& current_coarse_centroid = centroids[subvector_index][coarse_quantizations[subvector_index]];
cblas_saxpy(subvector_dimension, -1, &(current_coarse_centroid[0]), 1, &(residual[start_dim]), 1);
}
}
void GetNearestClusterIdsForPointSubset(const Points& points, const Centroids& centroids,
const PointId start_pid, const PointId final_pid,
vector<ClusterId>* nearest) {
if (final_pid < start_pid) {
throw std::logic_error("Final pid < Start pid");
}
cout << start_pid << " point processing started\n";
for (PointId pid = start_pid; pid < final_pid; ++pid) {
if (pid % 10000 == 0) {
cout << pid << endl;
}
nearest->at(pid) = GetNearestClusterId(points[pid], centroids, 0, points[0].size());
}
cout << final_pid << " point processing finished\n";
}
void GetNearestClusterIdsForSubpoints(const Points& points, const Centroids& centroids,
const Dimensions start_dim, const Dimensions final_dim,
int threads_count, vector<ClusterId>* nearest) {
if (final_dim < start_dim) {
throw std::logic_error("Final dim < Start dim");
}
cout << "Start getting nearest Cluster Ids..." << endl;
Points subpoints;
GetSubpoints(points, start_dim, final_dim, &subpoints);
boost::thread_group threads;
int subpoints_count = points.size() / threads_count;
for (int thread_id = 0; thread_id < threads_count; ++thread_id) {
PointId start_pid = subpoints_count * thread_id;
PointId final_pid = start_pid + subpoints_count;
threads.create_thread(boost::bind(&GetNearestClusterIdsForPointSubset, subpoints, centroids,
start_pid, final_pid, nearest));
}
threads.join_all();
cout << "Finish getting nearest Cluster Ids..." << endl;
}
void GetPointsCoarseQuaintizations(const Points& points,
const vector<Centroids>& centroids,
const int threads_count,
vector<CoarseQuantization>* coarse_quantizations) {
int number_of_subvectors = centroids.size();
coarse_quantizations->resize(points.size(), CoarseQuantization(number_of_subvectors));
Dimensions subvector_dimension = points[0].size() / number_of_subvectors;
for (int centroids_index = 0; centroids_index < number_of_subvectors; ++centroids_index) {
vector<ClusterId> cluster_labels;
cluster_labels.resize(points.size());
Dimensions start_dim = centroids_index * subvector_dimension;
Dimensions final_dim = min((Dimensions)points[0].size(), start_dim + subvector_dimension);
GetNearestClusterIdsForSubpoints(points, centroids[centroids_index],
start_dim, final_dim, threads_count, &cluster_labels);
for (PointId pid = 0; pid < points.size(); ++pid) {
coarse_quantizations->at(pid)[centroids_index] = cluster_labels[pid];
}
}
} | [
"imfengyitong@hotmail.com"
] | imfengyitong@hotmail.com |
fe23746cc5ab592e757d61c3e610a850e262d107 | b974f048890d26044d05f87e7dee2fdacf9417e8 | /humancontroll.h | a8b0310349f4c2d8997ac5822818a3df0cf20188 | [] | no_license | jkpawlowski96/Mouse | 60a26edd806e299c6039cd691b8d9c8bcd1578d7 | e9ade090bcef600a5220e0a12210b30f0b469d65 | refs/heads/master | 2023-04-08T01:45:11.129678 | 2021-04-13T16:43:01 | 2021-04-13T16:43:01 | 343,504,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 710 | h | #ifndef HUMANCONTROLL_H
#define HUMANCONTROLL_H
#include "geometry.h"
#include "expander.h"
/**
* @brief Human controlled si
*
*/
class HumanControll: public SI
{
public:
/**
* @brief Construct a new Human Controll object
*
* @param initDirection
*/
HumanControll(Direction initDirection);
~HumanControll(){};
/**
* @brief Login implementation
*
* @param sensorData
* @return Task
*/
Task Logic(SensorData sensorData);
/**
* @brief Set the Direction of mouse
*
* @param d
*/
void SetDirection(Direction d);
private:
Direction mouseDirection;
Direction nextDirection;
};
#endif // HUMANCONTROLL_H
| [
"jkpawlowski96@gmail.com"
] | jkpawlowski96@gmail.com |
cffb443ec93b8ca5dbc7a09db6b4e71df95fcdb2 | f5458509ffd96ea19f4868b935864a80d13e39d8 | /SteinerRadzik_simulatedAnnealing/Grafo.h | 6044045eb4e81d38d88ecf7a2b559aeed79fc3ac | [] | no_license | islamifelipe/BiST_hybrid_algorithms2 | e11dd4a0c7eb76f8e452bd11b9a09ff48deaa24b | 8ef3c34dd20e23a9df74a3070b9f082c9641b235 | refs/heads/master | 2021-01-22T02:04:29.847556 | 2018-05-24T16:46:55 | 2018-05-24T16:46:55 | 92,323,917 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 1,288 | h | #ifndef _GRAFO_H_
#define _GRAFO_H_
#include "Vertice.h"
#include <map>
#include <vector>
class Grafo{
private:
int n;
Vertice **lista_vertices; /*Lista (fixa) de vértice. É um vetor de ponteiros. Cada vértice possui uma lista de arestas adjacentes.*/
map <int, Aresta *> arestasByIndex; /*lista de todas as arestas do Grafo.*/
map <int, int> status;
// se 0, é opcional
// se 1, é obrigatoria
// nao há aresta proibida (todas sao excluida a priori)
Aresta *** matrixArestas; // matrixArestas[i][j] = ponteiro para objeto aresta
public:
Grafo(int n1);
Grafo();
void addVertice(int id); // lista_vertices[id] = vertice de identificador id (entre 0 e n-1)
Vertice *getVertice(int id);
Aresta *addAresta(int id, int origem, int destino, float peso1, float peso2);
Aresta * getArestas(int i);
map <int, Aresta *> get_allArestas();
Aresta ** getAllArestasPtr();
void gerarArestasPtr();
int getQuantArestas();
int getQuantVertices();
int getStatus(int i);
void updateIndex(); // deve ser chamada depois de chamar o método de excluir proibidas.
//O método updateIndex pegas as arestas obrigatorias ou opcionais e reajusta os indices
void excluiProibidas();
void marcaObrigatorias();
};
#endif | [
"islame-felipe.da-costa-fernandes@etu.unice.fr"
] | islame-felipe.da-costa-fernandes@etu.unice.fr |
1285ea4c6e656e9691fa86e41bcacf48baaca616 | 95ab8a21dda989fde5b0796d1488c30128a01391 | /CodeForces/C++/1166C.cpp | 1c9a97dcfc1746cc9caa2687d7230c9da6afe729 | [] | no_license | neelaryan2/CompetitiveProgramming | caa20ffcdee57fb2e15ceac0e7ebbe4e7277dc34 | 959c3092942751f833b489cc91744fc68f8c65d2 | refs/heads/master | 2021-06-28T14:10:50.545527 | 2021-02-15T17:34:03 | 2021-02-15T17:34:03 | 216,887,910 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 780 | cpp | #include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "trace.h"
#else
#define trace(args...)
#endif
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using vi = vector<int>;
#define mp make_pair
#define ub upper_bound
#define lb lower_bound
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define all(v) (v).begin(), (v).end()
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
vector<int> a(n);
for (int& e : a) {
cin >> e;
e = abs(e);
}
sort(all(a));
ll ans = 0;
for (int i = 0; i < n; i++) {
int j = ub(all(a), 2 * a[i]) - a.begin();
ans += j - i - 1;
}
cout << ans << '\n';
}
| [
"neelaryan2@gmail.com"
] | neelaryan2@gmail.com |
6c5ef3851dc981026a13c6fd5acdd606a7f06c09 | 627ddc63ba0ef8978f7cbae23cb0a1f1cb979e9a | /System/GUI/Widgets/Menu/MenuRenderView.h | b3ce589e7cadc3830cada4f776be77eedab03700 | [] | no_license | kavionic/PadOS | 4190ef764b146de6b756e97d3859d6d0fec3e2ec | 64acab418038ddcf7306c77ffbabc1c6880591d4 | refs/heads/master | 2023-07-04T09:58:57.316342 | 2023-06-26T23:46:39 | 2023-06-26T23:46:39 | 125,652,980 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,141 | h | // This file is part of PadOS.
//
// Copyright (C) 1999-2020 Kurt Skauen <http://kavionic.com/>
//
// PadOS 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.
//
// PadOS 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 PadOS. If not, see <http://www.gnu.org/licenses/>.
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include <GUI/View.h>
#include <GUI/Widgets/Menu.h>
namespace os
{
class MenuRenderView : public View
{
public:
MenuRenderView(Menu* menu) : View("menu_content", ptr_tmp_cast(menu), ViewFlags::WillDraw), m_Menu(menu) {}
virtual Point GetContentSize() const override;
virtual void Paint(const Rect& updateRect) override;
virtual bool OnTouchDown(MouseButton_e pointID, const Point& position, const MotionEvent& event) override;
virtual bool OnTouchUp(MouseButton_e pointID, const Point& position, const MotionEvent& event) override;
virtual bool OnTouchMove(MouseButton_e pointID, const Point& position, const MotionEvent& event) override;
virtual bool OnLongPress(MouseButton_e pointID, const Point& position, const MotionEvent& event) override;
virtual bool OnMouseDown(MouseButton_e button, const Point& position, const MotionEvent& event) override;
virtual bool OnMouseUp(MouseButton_e button, const Point& position, const MotionEvent& event) override;
virtual bool OnMouseMove(MouseButton_e button, const Point& position, const MotionEvent& event) override;
private:
Menu* m_Menu;
MouseButton_e m_HitButton = MouseButton_e::None;
Point m_HitPos;
bool m_MouseMoved = false;
};
} // namespace os;
| [
"kurt.skauen@gmail.com"
] | kurt.skauen@gmail.com |
4fa946fa711ef218a542f90421007935902ebe21 | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /third_party/android_ndk/toolchains/llvm/prebuilt/linux-x86_64/prebuilt_include/llvm/lib/Fuzzer/FuzzerInternal.h | c26615631ecd013856d574f7516e6f66c17d9012 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"NCSA",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-arm-llvm-sga",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 4,835 | h | //===- FuzzerInternal.h - Internal header for the Fuzzer --------*- C++ -* ===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Define the main class fuzzer::Fuzzer and most functions.
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_INTERNAL_H
#define LLVM_FUZZER_INTERNAL_H
#include "FuzzerDefs.h"
#include "FuzzerExtFunctions.h"
#include "FuzzerInterface.h"
#include "FuzzerOptions.h"
#include "FuzzerSHA1.h"
#include "FuzzerValueBitMap.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <climits>
#include <cstdlib>
#include <string.h>
namespace fuzzer {
using namespace std::chrono;
class Fuzzer {
public:
Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
FuzzingOptions Options);
~Fuzzer();
void Loop();
void MinimizeCrashLoop(const Unit &U);
void ShuffleAndMinimize(UnitVector *V);
void InitializeTraceState();
void RereadOutputCorpus(size_t MaxSize);
size_t secondsSinceProcessStartUp() {
return duration_cast<seconds>(system_clock::now() - ProcessStartTime)
.count();
}
bool TimedOut() {
return Options.MaxTotalTimeSec > 0 &&
secondsSinceProcessStartUp() >
static_cast<size_t>(Options.MaxTotalTimeSec);
}
size_t execPerSec() {
size_t Seconds = secondsSinceProcessStartUp();
return Seconds ? TotalNumberOfRuns / Seconds : 0;
}
size_t getTotalNumberOfRuns() { return TotalNumberOfRuns; }
static void StaticAlarmCallback();
static void StaticCrashSignalCallback();
static void StaticInterruptCallback();
static void StaticFileSizeExceedCallback();
void ExecuteCallback(const uint8_t *Data, size_t Size);
size_t RunOne(const uint8_t *Data, size_t Size);
// Merge Corpora[1:] into Corpora[0].
void Merge(const std::vector<std::string> &Corpora);
void CrashResistantMerge(const std::vector<std::string> &Args,
const std::vector<std::string> &Corpora,
const char *CoverageSummaryInputPathOrNull,
const char *CoverageSummaryOutputPathOrNull);
void CrashResistantMergeInternalStep(const std::string &ControlFilePath);
MutationDispatcher &GetMD() { return MD; }
void PrintFinalStats();
void SetMaxInputLen(size_t MaxInputLen);
void SetMaxMutationLen(size_t MaxMutationLen);
void RssLimitCallback();
bool InFuzzingThread() const { return IsMyThread; }
size_t GetCurrentUnitInFuzzingThead(const uint8_t **Data) const;
void TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
bool DuringInitialCorpusExecution);
void HandleMalloc(size_t Size);
void AnnounceOutput(const uint8_t *Data, size_t Size);
private:
void AlarmCallback();
void CrashCallback();
void InterruptCallback();
void MutateAndTestOne();
void ReportNewCoverage(InputInfo *II, const Unit &U);
size_t RunOne(const Unit &U) { return RunOne(U.data(), U.size()); }
void WriteToOutputCorpus(const Unit &U);
void WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix);
void PrintStats(const char *Where, const char *End = "\n", size_t Units = 0);
void PrintStatusForNewUnit(const Unit &U);
void ShuffleCorpus(UnitVector *V);
void AddToCorpus(const Unit &U);
void CheckExitOnSrcPosOrItem();
// Trace-based fuzzing: we run a unit with some kind of tracing
// enabled and record potentially useful mutations. Then
// We apply these mutations one by one to the unit and run it again.
// Start tracing; forget all previously proposed mutations.
void StartTraceRecording();
// Stop tracing.
void StopTraceRecording();
static void StaticDeathCallback();
void DumpCurrentUnit(const char *Prefix);
void DeathCallback();
void AllocateCurrentUnitData();
uint8_t *CurrentUnitData = nullptr;
std::atomic<size_t> CurrentUnitSize;
uint8_t BaseSha1[kSHA1NumBytes]; // Checksum of the base unit.
bool RunningCB = false;
size_t TotalNumberOfRuns = 0;
size_t NumberOfNewUnitsAdded = 0;
bool HasMoreMallocsThanFrees = false;
size_t NumberOfLeakDetectionAttempts = 0;
UserCallback CB;
InputCorpus &Corpus;
MutationDispatcher &MD;
FuzzingOptions Options;
system_clock::time_point ProcessStartTime = system_clock::now();
system_clock::time_point UnitStartTime, UnitStopTime;
long TimeOfLongestUnitInSeconds = 0;
long EpochOfLastReadOfOutputCorpus = 0;
size_t MaxInputLen = 0;
size_t MaxMutationLen = 0;
// Need to know our own thread.
static thread_local bool IsMyThread;
};
}; // namespace fuzzer
#endif // LLVM_FUZZER_INTERNAL_H
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
c57d15120f622edd0fcc700148eb00d71c1a6e3e | a5630a7862ab386439f7b1b678162c178cae2d1d | /toolkits/graphical_models/deprecated/gibbs_sampling/factorized_model.hpp | 0694c67ade422db5be613386fc28f615d5ead1d0 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | xiechenny/powerswitch | 813b74ede6ca1fdc4c475c41552b0207d73f1c3e | 8fc0cca6fa3085924209d13f32661aec69339d98 | refs/heads/master | 2021-01-19T00:13:08.981155 | 2013-12-23T08:05:10 | 2013-12-23T08:05:10 | 14,947,923 | 15 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 3,531 | hpp | /**
* Copyright (c) 2009 Carnegie Mellon University.
* 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.
*
* For more about this software visit:
*
* http://www.graphlab.ml.cmu.edu
*
*/
#ifndef PGIBBS_FACTORIZED_MODEL_HPP
#define PGIBBS_FACTORIZED_MODEL_HPP
/**
*
* Represents a factorized model in alchemy format
*
* \author Joseph Gonzalez
*/
// INCLUDES ===================================================================>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cassert>
#include <graphlab.hpp>
// The maximum number of dimensions in a factor table
const size_t MAX_TREEWIDTH = 32;
const size_t MAX_DIM = MAX_TREEWIDTH + 1;
// Basic graphical model typedefs
typedef uint32_t factor_id_t;
typedef graphlab::discrete_variable variable_t;
typedef graphlab::table_factor<MAX_DIM> factor_t;
typedef factor_t::domain_type domain_t;
typedef factor_t::assignment_type assignment_t;
// A class which represents a factorized distribution as a collection
// of factors.
class factorized_model {
private:
std::set<variable_t> _variables;
std::vector<factor_t> _factors;
std::map< variable_t, std::set<factor_id_t> > _var_to_factor;
std::vector<std::string> _var_name;
/**
* same as the stl string get line but this also increments a line
* counter which is useful for debugging purposes
*/
inline bool getline(std::ifstream& fin,
std::string& line,
size_t line_number) {
return std::getline(fin, line).good();
}
/**
* Removes trailing and leading white space from a string
*/
inline std::string trim(const std::string& str) {
std::string::size_type pos1 = str.find_first_not_of(" \t\r");
std::string::size_type pos2 = str.find_last_not_of(" \t\r");
return str.substr(pos1 == std::string::npos ? 0 : pos1,
pos2 == std::string::npos ? str.size()-1 : pos2-pos1+1);
}
public:
typedef std::vector<factor_t> factor_map_t;
void reserve(const size_t num_factors);
//! add a factor to the factorized model
factor_t& add_factor(const factor_t& factor);
//! add a factor to the factorized model
factor_t& add_factor(const domain_t& dom);
const factor_map_t& factors() const { return _factors; }
const std::set<variable_t>& variables() const { return _variables; }
const std::set<factor_id_t>& factor_ids(const variable_t& var) const;
const std::string& var_name(size_t id) const {
ASSERT_LT(id, _var_name.size());
return _var_name[id];
}
void load_alchemy(const std::string& filename);
//! Save the factor to a file
void save(graphlab::oarchive &arc) const;
//! Load the factor from a file
void load(graphlab::iarchive &arc);
//! save the alchemy file
void save_alchemy(const std::string& filename) const;
}; //end of factorized model
#endif
| [
"joseph.e.gonzalez@gmail.com"
] | joseph.e.gonzalez@gmail.com |
b574707e534d5dc6c40c56619d5b5b983d28632d | 72aca11f973b7c337012475ad3111cd20a5dd589 | /others/2020.08/2020.08.31-Exam/a.cpp | d1ae71433c727ddb6188d6e80e2776b860c6b725 | [] | no_license | aplqo/exercises | a4cee1acbef91e64aee2bd096cd7e0bb834926a4 | e28f14eaf89481c34bc1a27206e8cea2d2d94869 | refs/heads/master | 2021-06-25T06:34:09.535835 | 2021-04-08T13:52:39 | 2021-04-08T13:52:39 | 217,698,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,327 | cpp | #ifdef APTEST
#include "debug_tools/program.h"
#endif
#include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
using namespace std;
const unsigned int maxn = 2e5;
multiset<int> pos, neg;
int a[maxn + 1], acc;
long long sum;
inline void insert(const int v)
{
if (v + acc < 0)
neg.insert(v);
else
pos.insert(v);
sum += abs(v + acc);
}
inline void remove(const int v)
{
if (v + acc < 0)
neg.erase(neg.find(v));
else
pos.erase(pos.find(v));
sum -= abs(v + acc);
}
void increase()
{
multiset<int>::iterator it = neg.upper_bound(-acc);
pos.insert(it, neg.end());
neg.erase(it, neg.end());
sum = sum + pos.size() - neg.size();
}
void rotate(const unsigned int n, const unsigned int i)
{
++acc;
increase();
remove(a[i]);
a[i] -= n;
insert(a[i]);
}
long long findMin(const unsigned int n)
{
long long ret = sum;
for (unsigned int i = 1; i < n; ++i) {
rotate(n, i);
ret = min(ret, sum);
}
return ret;
}
int main()
{
#if !defined APTEST && !defined APDEBUG
ios_base::sync_with_stdio(false);
ifstream in("a.in");
ofstream out("a.out");
#else
istream& in = cin;
ostream& out = cout;
#endif
unsigned int n;
in >> n;
for (int i = 1; i <= n; ++i) {
in >> a[i];
a[i] -= i;
insert(a[i]);
}
out << findMin(n) << "\n";
return 0;
} | [
"aplqo@outlook.com"
] | aplqo@outlook.com |
fee6d58d12f8436f86d331285b6e26b84a37bafd | 16e90b3fb905350bdfe012f786ed24d83ee7d00c | /server/Ca.hh | 4a51765d8cd00764bf6d58a25f840214d6c01f0c | [] | no_license | lcls-daq/ami | b216fac06164d4e860d8bf385b381d01a15719da | 4b46b80970fec84979be24eedea8639bd90a9748 | refs/heads/master | 2023-08-03T00:30:36.833126 | 2023-07-29T09:28:36 | 2023-07-29T09:28:36 | 87,128,480 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 192 | hh | #ifndef Ami_Ca
#define Ami_Ca
namespace Ami {
class Ca {
public:
Ca(const char*);
~Ca();
public:
const char* name () const;
double value() const;
};
};
#endif
| [
"none@example.com"
] | none@example.com |
3f725bcd2aa7d1cf9c949c63cfd2ee2300c72de3 | 0ed735acc601e494b5dee529200d6383779c1d39 | /node_modules/face-recognition/cc/Rect.h | a3fdaa367b356f073eade2df79ae821f0197731b | [
"MIT",
"Apache-2.0"
] | permissive | osman-demirci/digital-guard-app-ipcamera | 69d35e9bf8632e514e01b75b8b296cb1c4b572a5 | 397a105d34194e2ce1ab7a31f34d03631a316b44 | refs/heads/master | 2022-12-15T17:56:55.346494 | 2020-09-06T21:41:47 | 2020-09-06T21:41:47 | 293,359,459 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,119 | h | #include "Converters.h"
#include "dlib/geometry/rectangle.h"
#ifndef __FACEREC_RECT_H__
#define __FACEREC_RECT_H__
class Rect : public Nan::ObjectWrap {
public:
dlib::rectangle rect;
static NAN_MODULE_INIT(Init);
static NAN_METHOD(New);
static NAN_GETTER(GetLeft) {
info.GetReturnValue().Set((int)Converter::unwrap(info.This()).left());
}
static NAN_GETTER(GetRight) {
info.GetReturnValue().Set((int)Converter::unwrap(info.This()).right());
}
static NAN_GETTER(GetTop) {
info.GetReturnValue().Set((int)Converter::unwrap(info.This()).top());
}
static NAN_GETTER(GetBottom) {
info.GetReturnValue().Set((int)Converter::unwrap(info.This()).bottom());
}
static NAN_GETTER(GetArea) {
info.GetReturnValue().Set((int)Converter::unwrap(info.This()).area());
}
static Nan::Persistent<v8::FunctionTemplate> constructor;
dlib::rectangle* getNativeObjectPtr() { return ▭ }
dlib::rectangle getNativeObject() { return rect; }
typedef InstanceConverter<Rect, dlib::rectangle> Converter;
static const char* getClassName() {
return "Rect";
}
};
#endif | [
"osman.demirci@basarimobile.com"
] | osman.demirci@basarimobile.com |
6a25f632adc353af8ab10d79c0728f2812c1dd46 | a1f96abe0b24c8d758a432aee6a86bcbf1ac839d | /inference-engine/tests/functional/inference_engine/ngraph_reader/softmax_tests.cpp | 91bb47a8d7d32ad06a20af481e3af72444faf89a | [
"Apache-2.0"
] | permissive | fujunwei/dldt | 4cd605af85003c4df688f569d7e36deec9a6fd4b | 09497b7724de4be92629f7799b8538b483d809a2 | refs/heads/webml | 2021-08-15T03:10:32.527006 | 2020-07-31T05:17:56 | 2020-07-31T05:17:56 | 210,724,923 | 0 | 0 | Apache-2.0 | 2020-06-17T00:42:45 | 2019-09-25T00:54:25 | C++ | UTF-8 | C++ | false | false | 2,502 | cpp | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <string>
#include "ngraph_reader_tests.hpp"
TEST_F(NGraphReaderTests, ReadSoftMaxNetwork) {
std::string model = R"V0G0N(
<net name="Activation" version="10">
<layers>
<layer name="in1" type="Parameter" id="0" version="opset1">
<data element_type="f32" shape="1,1000"/>
<output>
<port id="0" precision="FP32">
<dim>1</dim>
<dim>1000</dim>
</port>
</output>
</layer>
<layer name="softmax" id="1" type="SoftMax" version="opset1">
<data axis="1"/>
<input>
<port id="1" precision="FP32">
<dim>1</dim>
<dim>1000</dim>
</port>
</input>
<output>
<port id="2" precision="FP32">
<dim>1</dim>
<dim>1000</dim>
</port>
</output>
</layer>
<layer name="output" type="Result" id="2" version="opset1">
<input>
<port id="0" precision="FP32">
<dim>1</dim>
<dim>1000</dim>
</port>
</input>
</layer>
</layers>
<edges>
<edge from-layer="0" from-port="0" to-layer="1" to-port="1"/>
<edge from-layer="1" from-port="2" to-layer="2" to-port="0"/>
</edges>
</net>
)V0G0N";
std::string modelV5 = R"V0G0N(
<net name="Activation" version="5" precision="FP32" batch="1">
<layers>
<layer name="in1" type="Input" precision="FP32" id="0">
<output>
<port id="0">
<dim>1</dim>
<dim>1000</dim>
</port>
</output>
</layer>
<layer name="softmax" id="1" type="SoftMax" precision="FP32">
<data axis="1"/>
<input>
<port id="1">
<dim>1</dim>
<dim>1000</dim>
</port>
</input>
<output>
<port id="2">
<dim>1</dim>
<dim>1000</dim>
</port>
</output>
</layer>
</layers>
<edges>
<edge from-layer="0" from-port="0" to-layer="1" to-port="1"/>
</edges>
</net>
)V0G0N";
compareIRs(model, modelV5, 0);
}
| [
"alexey.suhov@intel.com"
] | alexey.suhov@intel.com |
f9f8458b5c29b5eed608c29c5a3965d8884263fc | 1c29f24ac64e818c1cf28b1ce84fb7a49f974770 | /FPGA/conv_test.cpp | e8bd18fc9e8a51daa8dce79ee9c3d1093910e368 | [] | no_license | missionfission/FPGA-CNN-Acceleration | 12686568587444ef27aeefd7a60a84c12592b3f5 | 5fffccf0e106a76248785cdbab896b5c919b55ad | refs/heads/master | 2022-12-26T15:16:10.964358 | 2020-10-18T10:35:41 | 2020-10-18T10:35:41 | 138,384,926 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,317 | cpp | #include <stdio.h>
#include "conv.hpp"
#include <cmath>
#include <ctime>
void conv_test() {
int i; int j; int c;
int num_weights = 3 * 3 * 3 * 2 + 3;
data_t A[3 * 3 * 3 * 2 + 3 + 50 + 27];
// Hard-coded answer
data_t C[27] = {0.660000, 1.485000, 1.320000, 1.485000, 2.970000, 2.475000, 1.320000, 2.475000, 1.980000,
12.000000, 27.000000, 24.000000, 27.000000, 54.000000, 45.000000, 24.000000, 45.000000, 36.000000,
0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000};
data_t* w = A;
data_t* img = &A[num_weights];
data_t* B = &A[num_weights + 50];
int num_weights_2 = 2 * 1 * 1 * 2 + 2;
data_t A_2[2 * 1 * 1 * 2 + 2 + 50 + 18] = {2,0,-1,0, 1, 2};
data_t* img_2 = &A_2[num_weights_2];
data_t image[50] = {-5,4,3,2,1,1,2,3,4,5,1,2,3,4,5,4,4,4,4,4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
data_t* B_2 = &A_2[num_weights_2 + 50];
// Hard-coded answer
//
data_t C_2[18] = {0,7,3,3,7,11,3,3,3,7,0,1,1,0,0,1,1,1};
//Put data into A
for (i=0; i < 5; i++){
for (j=0; j < 5; j++) {
img[i * 5 + j] = i+1;
}
}
for (i=0; i < 5; i++){
for (j=0; j < 5; j++) {
img[25 + i * 5 + j] = j+1;
}
}
for (i=0; i < 27; i++) {
B[i] = -1;
}
for (j = 0; j < 3; j++) {
for (i = 0; i < 3 * 3 * 2; i++) {
if (j == 0) {
w[j * (3 * 3 * 2) + i] = 0.055;
} else if (j == 1) {
w[j * (3 * 3 * 2) + i] = 1;
} else {
w[j * (3 * 3 * 2) + i] = 0;
}
}
}
// bias weights
for (i = 0; i < 3; i++) {
w[3 * 3 * 3 * 2 + i] = 0;
}
for (i = 0; i < 50; i++) {
img_2[i] = image[i];
}
// for (j = 0; j < 3; j++) {
// for (i = 0; i < 3 * 3 * 2; i++) {
// printf("%f ", w[j * (3 * 3 * 2) + i]);
// }
// printf("\n");
// }
// printf("\n");
offset_t weight_offset = 0;
offset_t img_offset = num_weights;
offset_t img_offset_2 = num_weights_2;
offset_t output_offset = img_offset + 50;
offset_t output_offset_2 = img_offset_2 + 50;
offset_t scratch_offset = output_offset + 27;
offset_t scratch_offset_2 = output_offset_2 + 18;
// Call the hardware function
layer_t l = layer_t(5, 5, 2, 3, 3, 2, 0, true, true, false, fire_t(), false, pooling_t(), false, weight_offset, num_weights, img_offset, output_offset, scratch_offset);
std::clock_t start;
long double duration;
start = std::clock();
compute(A,l);
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
printf("time taken: %Lf\n", duration);
layer_t l_2 = layer_t(5, 5, 2, 2, 1, 2, 0, true, true, false, fire_t(), false, pooling_t(), false, weight_offset, num_weights_2, img_offset_2, output_offset_2, scratch_offset_2);
compute(A_2,l_2);
// Compare results
for(i=0; i<27; i++){
if (std::abs(B[i] - C[i]) > 0.00001) {
printf("ERROR A value mismatch at: %d found: %f expected: %f\n", i, B[i], C[i]);
// return;
// } else {
// printf("SUCCESS A value matches at: %d found: %f expected: %f\n", i, B[i], C[i]);
}
}
// printf("\n\n");
for(i=0; i<18; i++){
if (std::abs(B_2[i] - C_2[i]) > 0.00001) {
printf("ERROR A_2 value mismatch at: %d found: %f expected: %f\n", i, B_2[i], C_2[i]);
// return;
// } else {
// printf("SUCCESS A_2 value matches at: %d found: %f expected: %f\n", i, B_2[i], C_2[i]);
}
}
// printf("\n\n");
printf("SUCCESS: conv results match\n");
printf("\n\n");
return;
}
| [
"iaskhushal@gmail.com"
] | iaskhushal@gmail.com |
23bb04e51a8e15a406da4c0eaecad63f99720a10 | 248baea990108d445b554908ec70f6df680f0dd8 | /src/counterflow1d/CounterFlow1DFlameExperiment.h | e553cb97ea1db757f5f36a0fcb838af4fa6c8d01 | [] | no_license | olarrh/OpenSMOKEpp_KineticOptimizer | 7dbf5776441f5c22f30439ac550d58cd5d0ab7b7 | a90468b3583629c4ef3d50c3012f5b40f74c9bcc | refs/heads/master | 2020-06-23T11:37:39.476575 | 2018-07-22T21:43:48 | 2018-07-22T21:43:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,944 | h | /*-----------------------------------------------------------------------*\
| ___ ____ __ __ ___ _ _______ |
| / _ \ _ __ ___ _ __ / ___|| \/ |/ _ \| |/ / ____| _ _ |
| | | | | '_ \ / _ \ '_ \\___ \| |\/| | | | | ' /| _| _| |_ _| |_ |
| | |_| | |_) | __/ | | |___) | | | | |_| | . \| |__|_ _|_ _| |
| \___/| .__/ \___|_| |_|____/|_| |_|\___/|_|\_\_____||_| |_| |
| |_| |
| |
| Author: Alberto Cuoci <alberto.cuoci@polimi.it> |
| CRECK Modeling Group <http://creckmodeling.chem.polimi.it> |
| Department of Chemistry, Materials and Chemical Engineering |
| Politecnico di Milano |
| P.zza Leonardo da Vinci 32, 20133 Milano |
| |
|-------------------------------------------------------------------------|
| |
| This file is part of OpenSMOKE++ framework. |
| |
| License |
| |
| Copyright(C) 2018 Alberto Cuoci |
| OpenSMOKE++ 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. |
| |
| OpenSMOKE++ 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 OpenSMOKE++. If not, see <http://www.gnu.org/licenses/>. |
| |
\*-----------------------------------------------------------------------*/
#ifndef OpenSMOKE_CounterFlow1DFlameExperiment_H
#define OpenSMOKE_CounterFlow1DFlameExperiment_H
// Utilities
#include "idealreactors/utilities/Utilities"
#include "utilities/ropa/OnTheFlyROPA.h"
#include "utilities/ontheflypostprocessing/OnTheFlyPostProcessing.h"
#include "utilities/Utilities.h"
#include "idealreactors/utilities/Grammar_LewisNumbers.h"
// 1D grid
#include "utilities/grids/adaptive/Grid1D.h"
#include "utilities/grids/adaptive/Grammar_Grid1D.h"
#include "utilities/grids/adaptive/Adapter_Grid1D.h"
// Hybrid Method of Moments
#include "utilities/soot/hmom/HMOM.h"
#include "OptimizationRules_CounterFlow1DFlameExperiment.h"
#include "Grammar_CounterFlow1DFlameExperiment.h"
#include "OpenSMOKE_CounterFlowFlame1D.h"
namespace OpenSMOKE
{
class CounterFlow1DFlameExperiment
{
public:
void Setup(const std::string input_file_name,
OpenSMOKE::ThermodynamicsMap_CHEMKIN* thermodynamicsMapXML,
OpenSMOKE::KineticsMap_CHEMKIN* kineticsMapXML,
OpenSMOKE::TransportPropertiesMap_CHEMKIN* transportMapXML);
void Solve(const bool verbose = false);
double norm2_abs_error() const { return norm2_abs_error_; }
double norm2_rel_error() const { return norm2_rel_error_; }
const OpenSMOKE::OptimizationRules_CounterFlow1DFlameExperiment* optimization() const { return optimization_; }
private:
// Read thermodynamics and kinetics maps
OpenSMOKE::ThermodynamicsMap_CHEMKIN* thermodynamicsMapXML_;
OpenSMOKE::KineticsMap_CHEMKIN* kineticsMapXML_;
OpenSMOKE::TransportPropertiesMap_CHEMKIN* transportMapXML_;
OpenSMOKE::OptimizationRules_CounterFlow1DFlameExperiment* optimization_;
DaeSMOKE::DaeSolver_Parameters* dae_parameters;
NlsSMOKE::NonLinearSolver_Parameters* nls_parameters;
NlsSMOKE::FalseTransientSolver_Parameters* false_transient_parameters;
OpenSMOKE::SensitivityAnalysis_Options* sensitivity_options;
OpenSMOKE::Grid1D* grid;
OpenSMOKE::PolimiSoot_Analyzer* polimi_soot;
OpenSMOKE::OnTheFlyPostProcessing* on_the_fly_post_processing;
OpenSMOKE::HMOM* hmom;
OpenSMOKE::DynamicBoundaries* dynamic_boundaries;
double end_value_;
double norm2_abs_error_;
double norm2_rel_error_;
};
}
#include "CounterFlow1DFlameExperiment.hpp"
#endif // OpenSMOKE_CounterFlow1DFlameExperiment_H | [
"alberto.cuoci@polimi.it"
] | alberto.cuoci@polimi.it |
6779259e7383383c67135dd7555c542f49308b30 | 5ff791c9d373f4403905078fe8624940044b6e38 | /src/pol/logic2/DragDropManager.h | 065440cdd0233526e89e8f873a7a944c2bba606b | [] | no_license | rocking-around/PoL1.62.002 | 029eb63f341b9b88bc574ae430c7eaba9f943026 | 919abd5afa7eef92dc52d4e1d1e858b906cc577f | refs/heads/master | 2023-03-21T00:20:25.192498 | 2020-03-19T08:46:56 | 2020-03-19T08:46:56 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 7,830 | h | //
// сервер для работы с механизмом drag & drop'a
//
#ifndef _PUNCH_DRAGDROPMANAGER_H_
#define _PUNCH_DRAGDROPMANAGER_H_
#include "entityaux.h"
#include <undercover/interface/SlotsEngine.h>
class SlotEnv;
class HumanEntity;
class SlotsEngine;
class AbstractBin;
class AbstractGround;
typedef unsigned slid_t; //идентификатор слота
//
// стратегия на слот
//
class SlotStrategy
{
public:
virtual ~SlotStrategy();
enum slot_type
{
ST_NONE,
ST_HEAD,
ST_BODY,
ST_HANDS,
ST_LKNEE,
ST_RKNEE,
ST_GROUND,
ST_MARKET,
ST_IMPLANTS,
ST_BACKPACK,
};
//узнать тип слота
virtual slot_type GetType() const = 0;
//закрытие слота (необх. сохранить позицию предметов)
virtual void Clear() = 0;
//открытие слота (необх. заполнить слот)
virtual void Fill(SESlot* slot, SlotEnv* env) = 0;
//подсветить предметы в слоте
virtual void Illuminate(slot_type slot, BaseThing* thing) = 0;
//обработка стаскивания предмета
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// возврат:
// true - стаскивание было
// false - стаскивания не было
//
virtual bool DoDrag(SEItem* item) = 0;
//обработка бросания предмета
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// возврат:
// true - бросание было
// false - бросания не было
//
virtual bool DoDrop(SEItem *item, const ipnt2_t& to) = 0;
virtual bool DoDrop() { return false; }
};
//
// Декоратор для стратегии слота
//
class SlotDecorator : public SlotStrategy
{
public:
SlotDecorator(SlotStrategy* stratetgy);
~SlotDecorator();
//узнать тип слота
slot_type GetType() const;
//узнать тип слота
void Clear();
//открытие слота (необх. заполнить слот)
void Fill(SESlot* slot, SlotEnv* env);
//подсветить предметы в слоте
void Illuminate(slot_type slot, BaseThing* thing);
//обработка стаскивания предмета
bool DoDrag(SEItem* item);
//обработка бросания предмета
bool DoDrop(SEItem* item, const ipnt2_t& to);
bool DoDrop();
private:
SlotStrategy* m_strategy;
};
//
// декоратор разряжающий оружие в руках персонажа
//
class UnloadingDecorator : public SlotDecorator
{
public:
UnloadingDecorator(SlotStrategy* strategy);
//открытие слота (необх. заполнить слот)
void Fill(SESlot* slot, SlotEnv* env);
//разрядить оружие
void Unload();
private:
SlotEnv* m_env;
};
//
// контекст для стратегии слотов
//
class SlotEnv
{
public:
virtual ~SlotEnv() {}
//получить ссылку на активного героя
virtual HumanEntity *GetActor() const = 0;
//получить ссылку на героя, который дает предмет
virtual HumanEntity *GetGiver() const = 0;
//получить доступ к контейнеру слотов
virtual SlotsEngine *GetEngine() const = 0;
//получить ссылку на землю
virtual AbstractGround *GetGround() const = 0;
//
//утилиты для работы в слотах
//
//установить текст на item'e
virtual void UpdateText(SEItem* item) = 0;
//сценарий сбрасывания предмета
virtual void DiscardItem(SEItem* item) = 0;
//создать item для слота
virtual SEItem* CreateItem(BaseThing* thing) = 0;
//установить состояние предмета
virtual void SetState(SEItem* item, BaseThing* thing = 0) = 0;
//откуда пришел предмет
virtual SlotStrategy::slot_type GetLastOwner(SEItem* item) const = 0;
};
//=====================================================================================//
// class SlotFactory //
//=====================================================================================//
// создание стратегий для слотов
class SlotFactory
{
public:
//созать слот соответствующего типа
static SlotStrategy* Create(SlotStrategy::slot_type type);
};
//
// менеджер Drag & Drop'a
//
class DragDropManager : private SlotEnv,
private SEController,
private EntityObserver
{
public:
DragDropManager(SlotsEngine* engine);
~DragDropManager();
//установить нужный слот
void Insert(slid_t slot, SlotStrategy* strategy);
//установить ссылку на абстракцию корзины
void SetBin(AbstractBin* bin);
//установить активного персонажа
void SetActor(HumanEntity* human);
//установить ссылку на абстракцию земли
void SetGround(AbstractGround* ground);
//отменить режим сбрасывания
bool CancelDrop();
//бросить предмет в рюкзак (если нельзя в рюкзак, тогда на землю)
void DropItem(HumanEntity *);
//подсветить все
void Illuminate(SlotStrategy::slot_type slot, BaseThing* thing);
private:
//===============================================
//получить ссылку на активного героя
HumanEntity* GetActor() const;
//получить ссылку на героя, который дает предмет
HumanEntity *GetGiver() const;
//получить доступ к контейнеру слотов
SlotsEngine* GetEngine() const;
//получить ссылку на землю
AbstractGround* GetGround() const;
//установить текст на item'e
void UpdateText(SEItem* item);
//сценарий сбрасывания предмета
void DiscardItem(SEItem* item);
//сценарий для DropItem
void DropItemToBackpack(SEItem *item, HumanEntity *e);
//создать item для слота
SEItem* CreateItem(BaseThing* thing);
//установить состояние предмета
void SetState(SEItem* item, BaseThing* thing);
//откуда пришел предмет
SlotStrategy::slot_type GetLastOwner(SEItem* item) const;
//===============================================
//обработка нажатия правой кнопки мыши
void OnItemClick(SEItem* item);
//обработка стаскивания
void OnDrag(SESlot* slot, SEItem* item);
//обоработка зависания
void OnLighting(SEItem* item,LIGHTING_MODE lm);
//обработка бросания
void OnDrop(SESlot* slot, SEItem* item, const ipnt2_t& pos);
//===============================================
//обработка изменения состояния существа
void Update(BaseEntity* entity, event_t event, info_t info);
private:
HumanEntity *m_actor;
HumanEntity *m_giver;
SlotsEngine *m_engine;
AbstractBin *m_bin;
AbstractGround *m_ground;
typedef std::vector<SlotStrategy*> slot_vec_t;
slot_vec_t m_slots;
};
#endif // _PUNCH_DRAGDROPMANAGER_H_
| [
"43969955+Hyski@users.noreply.github.com"
] | 43969955+Hyski@users.noreply.github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.