hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
488734c888c59e686a0da790371c263afdcbcd0d
2,710
cpp
C++
src/configuration/expr/compute_ternary.cpp
Damdoshi/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
38
2016-07-30T09:35:19.000Z
2022-03-04T10:13:48.000Z
src/configuration/expr/compute_ternary.cpp
Elania-Marvers/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
15
2017-02-12T19:20:52.000Z
2021-06-09T09:30:52.000Z
src/configuration/expr/compute_ternary.cpp
Elania-Marvers/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
12
2016-10-06T09:06:59.000Z
2022-03-04T10:14:00.000Z
// Jason Brillante "Damdoshi" // Hanged Bunny Studio 2014-2018 // // Lapin library #include "lapin_private.h" bool expr_compute_ternary(Expression &exp, bool dry, SmallConf *root, SmallConf *local, SmallConf *artif, SmallConf *param) { if (exp.is_const) return (true); if (exp.operand.size() != 3) scream_error_if (return (false), BE_BAD_ADDRESS, "Incomplete ternary on line %s:%d", "configuration,syntax", exp.file.c_str(), exp.line); if (exp.operand[1]->optor != Expression::BEO_TERNARY) scream_error_if (return (false), BE_BAD_ADDRESS, "First ternary token must be '?' on line %s:%d", "configuration,syntax", exp.file.c_str(),exp.line); if (exp.operand[2]->optor != Expression::BEO_TERNARY_ELSE) scream_error_if (return (false), BE_BAD_ADDRESS, "Second ternary token must be ':' on line %s:%d", "configuration,syntax", exp.file.c_str(), exp.line); if (dry) return (true); Expression &x = *exp.operand[0]; Expression *y; SmallConf *ope; bool cnst; int tmp; cnst = true; if (x.optor_family == -1) {} else if (x.optor_family == Expression::LAST_OPERATOR_FAMILY) { if (expr_compute_function_call(x, dry, root, local, artif, param) == false) return (false); } else if (gl_expr_computation[x.optor_family] (x, dry, root, local, artif, param) == false) return (false); ope = &x.val; if (ope->last_type == SmallConf::RAWSTRING) { cnst = false; if ((ope = expr_get_variable (*ope, dry, root, local, artif, param)) == NULL) scream_error_if (return (false), BE_BAD_ADDRESS, "Undefined variable or unresolvable address %s " "from context %s on line %s:%d", "configuration,syntax", x.val.original_value.c_str(), artif->address.c_str(), exp.file.c_str(), exp.line); } else if (x.is_const == false) cnst = false; if (ope->GetInt(&tmp) == false) scream_error_if (return (false), BE_TYPE_ERROR, "Cannot evaluate the truthness of the main ternary operand on line %s:%d", "configuration,syntax", exp.file.c_str(), exp.line); if (tmp) y = exp.operand[1]; else y = exp.operand[2]; if (y->optor_family == -1) {} else if (y->optor_family == Expression::LAST_OPERATOR_FAMILY) { if (expr_compute_function_call(*y, dry, root, local, artif, param) == false) return (false); } else if (gl_expr_computation[y->optor_family] (*y, dry, root, local, artif, param) == false) return (false); exp.val = y->val; if (cnst) exp.is_const = true; return (true); }
26.31068
82
0.61107
Damdoshi
488a5f636b595d52badc25017d05d9afeee5bdc5
137
hpp
C++
baseclass/headers/testPattern.hpp
HxHexa/quang-advCG-raytracer
605f7dfcc9237f331d456646b7653ad0f26c0cc4
[ "MIT" ]
null
null
null
baseclass/headers/testPattern.hpp
HxHexa/quang-advCG-raytracer
605f7dfcc9237f331d456646b7653ad0f26c0cc4
[ "MIT" ]
null
null
null
baseclass/headers/testPattern.hpp
HxHexa/quang-advCG-raytracer
605f7dfcc9237f331d456646b7653ad0f26c0cc4
[ "MIT" ]
null
null
null
/**/ #include "pattern.hpp" class TestPattern : public Pattern { public: TestPattern(); Color patternAt(Tuple); };
13.7
36
0.59854
HxHexa
488eb4ea9eb47e3e7ad94b15d5a0b24006881669
438
cpp
C++
UVa/10370 - Above Average.cpp
geniustanley/problem-solving
2b83c5c8197fa8fe2277367027b392a2911d4a28
[ "Apache-2.0" ]
1
2018-11-21T07:36:16.000Z
2018-11-21T07:36:16.000Z
UVa/10370 - Above Average.cpp
geniustanley/problem-solving
2b83c5c8197fa8fe2277367027b392a2911d4a28
[ "Apache-2.0" ]
null
null
null
UVa/10370 - Above Average.cpp
geniustanley/problem-solving
2b83c5c8197fa8fe2277367027b392a2911d4a28
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> int main(void) { int T, n, sum, ans; int num[1005]; double average; scanf("%d", &T); while(T--) { scanf("%d", &n); sum = 0; ans = 0; for(int i = 0; i < n; i++) { scanf("%d", &num[i]); sum += num[i]; } average = (double)sum/n; for(int i = 0; i < n; i++) if(average < num[i]) ans++; printf("%.3lf%%\n", (double)ans/n*100); } return 0; }
14.129032
42
0.429224
geniustanley
4890b57d04bd8cde59c176d6584e2822b2f0ae7c
1,497
hpp
C++
lib/luwra/types/pushable.hpp
jonmortiboy/luwra
71264e49103f8633ee5225dab1f4567a7f3672a2
[ "BSD-3-Clause" ]
186
2015-06-20T00:38:04.000Z
2022-02-19T16:08:33.000Z
lib/luwra/types/pushable.hpp
jonmortiboy/luwra
71264e49103f8633ee5225dab1f4567a7f3672a2
[ "BSD-3-Clause" ]
17
2015-07-09T10:23:02.000Z
2022-01-19T17:34:44.000Z
lib/luwra/types/pushable.hpp
jonmortiboy/luwra
71264e49103f8633ee5225dab1f4567a7f3672a2
[ "BSD-3-Clause" ]
21
2015-07-05T12:59:48.000Z
2020-07-20T18:50:43.000Z
/* Luwra * Minimal-overhead Lua wrapper for C++ * * Copyright (C) 2016, Ole Krüger <[email protected]> */ #ifndef LUWRA_TYPES_PUSHABLE_H_ #define LUWRA_TYPES_PUSHABLE_H_ #include "../common.hpp" #include "../values.hpp" #include "../stack.hpp" #include <utility> #include <memory> LUWRA_NS_BEGIN namespace internal { struct PushableI { virtual void push(State* state) const = 0; virtual ~PushableI() {} }; template <typename Type> struct PushableT: virtual PushableI { Type value; template <typename Source> inline PushableT(Source&& value): value(std::forward<Source>(value)) {} virtual void push(State* state) const { luwra::push(state, value); } virtual ~PushableT() {} }; using SharedPushableImpl = std::shared_ptr<PushableI>; } /// Arbitrary pushable value /// /// This class is implicitly constructible using any type. One can use this class with STL /// containers in order to achieve pushable mixed-type containers. struct Pushable { const internal::SharedPushableImpl interface; template <typename Type> inline Pushable(Type&& value): interface(new internal::PushableT<Type>(std::forward<Type>(value))) {} // Used in ordered STL containers inline bool operator <(const Pushable& other) const { return interface < other.interface; } }; /// Enables pushing for `Pushables` template <> struct Value<Pushable> { static inline void push(State* state, const Pushable& value) { value.interface->push(state); } }; LUWRA_NS_END #endif
19.697368
90
0.713427
jonmortiboy
48930bdb106b028921a0afe23bcd10f003b6993c
541
cpp
C++
src/glCompact/threadContextGroup_.cpp
PixelOfDeath/glCompact
68334cc9c3aa20255e8986ad1ee5fa8e23df354d
[ "MIT" ]
null
null
null
src/glCompact/threadContextGroup_.cpp
PixelOfDeath/glCompact
68334cc9c3aa20255e8986ad1ee5fa8e23df354d
[ "MIT" ]
null
null
null
src/glCompact/threadContextGroup_.cpp
PixelOfDeath/glCompact
68334cc9c3aa20255e8986ad1ee5fa8e23df354d
[ "MIT" ]
null
null
null
#include "glCompact/threadContextGroup_.hpp" namespace glCompact { #ifdef GLCOMPACT_MULTIPLE_CONTEXT_GROUP thread_local ContextGroup_* __restrict threadContextGroup_; #else static char contextGroupMem[sizeof(ContextGroup_)] alignas(ContextGroup_); ContextGroup_*const __restrict threadContextGroup_ = reinterpret_cast<ContextGroup_*>(&contextGroupMem); bool threadContextGroupConstructed_ = false; #endif }
45.083333
125
0.64695
PixelOfDeath
4895b449b8a1ea8118e69b15504c731ddae33732
16,163
cpp
C++
src/types/quamodbusrtuserialclient.cpp
juangburgos/QUaModbusClient
e1ac862e723cfdf9e6127d395fb7c614829e2154
[ "MIT" ]
26
2019-08-19T18:18:51.000Z
2022-03-24T12:56:30.000Z
src/types/quamodbusrtuserialclient.cpp
ManfredHerrmann/QUaModbusClient
38a3ec715db0336d4c26398084bef22ab5ca5072
[ "MIT" ]
2
2019-08-25T03:45:59.000Z
2021-01-21T12:06:55.000Z
src/types/quamodbusrtuserialclient.cpp
ManfredHerrmann/QUaModbusClient
38a3ec715db0336d4c26398084bef22ab5ca5072
[ "MIT" ]
9
2019-09-10T14:31:40.000Z
2021-09-28T05:37:54.000Z
#include "quamodbusrtuserialclient.h" #include <QSerialPortInfo> #ifdef QUA_ACCESS_CONTROL #include <QUaPermissions> #endif // QUA_ACCESS_CONTROL QUaModbusRtuSerialClient::QUaModbusRtuSerialClient(QUaServer *server) : QUaModbusClient(server) { // set defaults type ()->setDataTypeEnum(QMetaEnum::fromType<QModbusClientType>()); type ()->setValue(QModbusClientType::Serial); comPort ()->setDataTypeEnum(QUaModbusRtuSerialClient::ComPorts); comPort ()->setValue(0); parity ()->setDataTypeEnum(QMetaEnum::fromType<QParity>()); parity ()->setValue(QSerialPort::EvenParity); baudRate()->setDataTypeEnum(QMetaEnum::fromType<QBaudRate>()); baudRate()->setValue(QSerialPort::Baud19200); dataBits()->setDataTypeEnum(QMetaEnum::fromType<QDataBits>()); dataBits()->setValue(QSerialPort::Data8); stopBits()->setDataTypeEnum(QMetaEnum::fromType<QStopBits>()); stopBits()->setValue(QSerialPort::OneStop); // set initial conditions comPort ()->setWriteAccess(true); parity ()->setWriteAccess(true); baudRate()->setWriteAccess(true); dataBits()->setWriteAccess(true); stopBits()->setWriteAccess(true); // instantiate client this->resetModbusClient(); // handle state changes QObject::connect(comPort (), &QUaBaseVariable::valueChanged, this, &QUaModbusRtuSerialClient::on_comPortChanged , Qt::QueuedConnection); QObject::connect(parity (), &QUaBaseVariable::valueChanged, this, &QUaModbusRtuSerialClient::on_parityChanged , Qt::QueuedConnection); QObject::connect(baudRate(), &QUaBaseVariable::valueChanged, this, &QUaModbusRtuSerialClient::on_baudRateChanged, Qt::QueuedConnection); QObject::connect(dataBits(), &QUaBaseVariable::valueChanged, this, &QUaModbusRtuSerialClient::on_dataBitsChanged, Qt::QueuedConnection); QObject::connect(stopBits(), &QUaBaseVariable::valueChanged, this, &QUaModbusRtuSerialClient::on_stopBitsChanged, Qt::QueuedConnection); // set descriptions /* comPort ()->setDescription("Local serial COM port used to connect to the Modbus server."); parity ()->setDescription("Parity value (for error detection) used to communicate with the Modbus server."); baudRate()->setDescription("Baud Rate value (data rate in bits per second) used to communicate with the Modbus server."); dataBits()->setDescription("Number of Data Bits (in each character) used to communicate with the Modbus server."); stopBits()->setDescription("Number of Stop Bits (sent at the end of every character) used to communicate with the Modbus server."); */ } QUaProperty * QUaModbusRtuSerialClient::comPort() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return const_cast<QUaModbusRtuSerialClient*>(this)->browseChild<QUaProperty>("ComPort"); } QUaProperty * QUaModbusRtuSerialClient::parity() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return const_cast<QUaModbusRtuSerialClient*>(this)->browseChild<QUaProperty>("Parity"); } QUaProperty * QUaModbusRtuSerialClient::baudRate() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return const_cast<QUaModbusRtuSerialClient*>(this)->browseChild<QUaProperty>("BaudRate"); } QUaProperty * QUaModbusRtuSerialClient::dataBits() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return const_cast<QUaModbusRtuSerialClient*>(this)->browseChild<QUaProperty>("DataBits"); } QUaProperty * QUaModbusRtuSerialClient::stopBits() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return const_cast<QUaModbusRtuSerialClient*>(this)->browseChild<QUaProperty>("StopBits"); } QString QUaModbusRtuSerialClient::ComPorts = "QUaModbusRtuSerialClient::ComPorts"; QUaEnumMap QUaModbusRtuSerialClient::EnumComPorts() { QUaEnumMap mapPorts; QList<QSerialPortInfo> list = QSerialPortInfo::availablePorts(); for (int i = 0; i < list.count(); i++) { QSerialPortInfo portInfo = list.at(i); mapPorts.insert(i, { { "", portInfo.portName().toUtf8() }, { "", "" } } ); } return mapPorts; } void QUaModbusRtuSerialClient::resetModbusClient() { m_workerThread.execInThread([this]() { // instantiate in thread so it runs on the thread m_modbusClient.reset(new QModbusRtuSerialMaster(nullptr), [](QObject* client) { client->deleteLater(); }); // defaults m_modbusClient->setConnectionParameter(QModbusDevice::SerialPortNameParameter, this->getComPort ()); m_modbusClient->setConnectionParameter(QModbusDevice::SerialParityParameter , this->getParity ()); m_modbusClient->setConnectionParameter(QModbusDevice::SerialBaudRateParameter, this->getBaudRate()); m_modbusClient->setConnectionParameter(QModbusDevice::SerialDataBitsParameter, this->getDataBits()); m_modbusClient->setConnectionParameter(QModbusDevice::SerialStopBitsParameter, this->getStopBits()); // setup client (call base class method) this->QUaModbusClient::resetModbusClient(); QObject::connect(m_modbusClient.data(), &QModbusClient::stateChanged, this, &QUaModbusRtuSerialClient::on_stateChanged, Qt::QueuedConnection); }); } QDomElement QUaModbusRtuSerialClient::toDomElement(QDomDocument & domDoc) const { // add client list element QDomElement elemSerialClient = domDoc.createElement(QUaModbusRtuSerialClient::staticMetaObject.className()); #ifdef QUA_ACCESS_CONTROL // set parmissions if any if (this->hasPermissionsObject()) { elemSerialClient.setAttribute("Permissions", this->permissionsObject()->nodeId()); } #endif // QUA_ACCESS_CONTROL // set client attributes elemSerialClient.setAttribute("BrowseName" , this->browseName() ); elemSerialClient.setAttribute("ServerAddress" , getServerAddress() ); elemSerialClient.setAttribute("KeepConnecting", getKeepConnecting() ); elemSerialClient.setAttribute("ComPort" , QString(QUaModbusRtuSerialClient::EnumComPorts().value(getComPortKey()).displayName.text())); elemSerialClient.setAttribute("Parity" , QMetaEnum::fromType<QParity> ().valueToKey(getParity() )); elemSerialClient.setAttribute("BaudRate" , QMetaEnum::fromType<QBaudRate>().valueToKey(getBaudRate() )); elemSerialClient.setAttribute("DataBits" , QMetaEnum::fromType<QDataBits>().valueToKey(getDataBits() )); elemSerialClient.setAttribute("StopBits" , QMetaEnum::fromType<QStopBits>().valueToKey(getStopBits() )); // add block list element auto elemBlockList = const_cast<QUaModbusRtuSerialClient*>(this)->dataBlocks()->toDomElement(domDoc); elemSerialClient.appendChild(elemBlockList); // return list element return elemSerialClient; } void QUaModbusRtuSerialClient::fromDomElement(QDomElement & domElem, QQueue<QUaLog>& errorLogs) { // get client attributes (BrowseName must be already set) QString strBrowseName = domElem.attribute("BrowseName", ""); Q_ASSERT(this->browseName() == QUaQualifiedName(strBrowseName)); bool bOK; // ServerAddress auto serverAddress = domElem.attribute("ServerAddress").toUInt(&bOK); #ifdef QUA_ACCESS_CONTROL // load permissions if any if (domElem.hasAttribute("Permissions") && !domElem.attribute("Permissions").isEmpty()) { QString strError = this->setPermissions(domElem.attribute("Permissions")); if (strError.contains("Error")) { errorLogs << QUaLog( strError, QUaLogLevel::Error, QUaLogCategory::Serialization ); } } #endif // QUA_ACCESS_CONTROL if (bOK) { this->setServerAddress(serverAddress); } else { errorLogs << QUaLog( tr("Invalid ServerAddress attribute '%1' in Modbus client %2. Default value set.").arg(serverAddress).arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } // KeepConnecting auto keepConnecting = (bool)domElem.attribute("KeepConnecting").toUInt(&bOK); if (bOK) { this->setKeepConnecting(keepConnecting); } else { errorLogs << QUaLog( tr("Invalid KeepConnecting attribute '%1' in Modbus client %2. Default value set.").arg(keepConnecting).arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } // ComPort auto comPort = domElem.attribute("ComPort"); if (!comPort.isEmpty()) { this->setComPortKey(QUaModbusRtuSerialClient::EnumComPorts().key( { { "", comPort.toUtf8() }, { "", "" } }, 0)); } else { errorLogs << QUaLog( tr("Invalid ComPort attribute '%1' in Modbus client %2. Default value set.").arg(comPort).arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } // Parity auto strParity = domElem.attribute("Parity"); auto parity = (QParity)QMetaEnum::fromType<QParity>().keysToValue(strParity.toUtf8(), &bOK); if (bOK) { this->setParity(parity); } else { errorLogs << QUaLog( tr("Invalid Parity attribute '%1' in Modbus client %2. Default value set.").arg(strParity).arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } // BaudRate auto strBaudRate = domElem.attribute("BaudRate"); auto baudRate = (QBaudRate)QMetaEnum::fromType<QBaudRate>().keysToValue(strBaudRate.toUtf8(), &bOK); if (bOK) { this->setBaudRate(baudRate); } else { errorLogs << QUaLog( tr("Invalid BaudRate attribute '%1' in Modbus client %2. Default value set.").arg(strBaudRate).arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } // DataBits auto strDataBits = domElem.attribute("DataBits"); auto dataBits = (QDataBits)QMetaEnum::fromType<QDataBits>().keysToValue(strDataBits.toUtf8(), &bOK); if (bOK) { this->setDataBits(dataBits); } else { errorLogs << QUaLog( tr("Invalid DataBits attribute '%1' in Modbus client %2. Default value set.").arg(strDataBits).arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } // StopBits auto strStopBits = domElem.attribute("StopBits"); auto stopBits = (QStopBits)QMetaEnum::fromType<QStopBits>().keysToValue(strStopBits.toUtf8(), &bOK); if (bOK) { this->setStopBits(stopBits); } else { errorLogs << QUaLog( tr("Invalid StopBits attribute '%1' in Modbus client %2. Default value set.").arg(strStopBits).arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } // get block list QDomElement elemBlockList = domElem.firstChildElement(QUaModbusDataBlockList::staticMetaObject.className()); if (!elemBlockList.isNull()) { dataBlocks()->fromDomElement(elemBlockList, errorLogs); } else { errorLogs << QUaLog( tr("Modbus client %2 does not have a QUaModbusDataBlockList child. No blocks will be loaded.").arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } } void QUaModbusRtuSerialClient::on_stateChanged(const QModbusDevice::State &state) { // only allow to write connection params if not connected if (state == QModbusDevice::State::UnconnectedState) { comPort ()->setWriteAccess(true); parity ()->setWriteAccess(true); baudRate()->setWriteAccess(true); dataBits()->setWriteAccess(true); stopBits()->setWriteAccess(true); } else { comPort ()->setWriteAccess(false); parity ()->setWriteAccess(false); baudRate()->setWriteAccess(false); dataBits()->setWriteAccess(false); stopBits()->setWriteAccess(false); } } void QUaModbusRtuSerialClient::on_comPortChanged(const QVariant & value) { // NOTE : if connected, will not change until reconnect QString strComPort = QUaModbusRtuSerialClient::EnumComPorts().value(value.toInt()).displayName.text(); // set in thread, for thread-safety m_workerThread.execInThread([this, strComPort]() { m_modbusClient->setConnectionParameter(QModbusDevice::SerialPortNameParameter, strComPort); }); // emit emit this->comPortChanged(strComPort); } void QUaModbusRtuSerialClient::on_parityChanged(const QVariant & value) { // NOTE : if connected, will not change until reconnect QParity parity = value.value<QParity>(); // set in thread, for thread-safety m_workerThread.execInThread([this, parity]() { m_modbusClient->setConnectionParameter(QModbusDevice::SerialParityParameter, parity); }); // emit emit this->parityChanged(parity); } void QUaModbusRtuSerialClient::on_baudRateChanged(const QVariant & value) { // NOTE : if connected, will not change until reconnect QBaudRate baudRate = value.value<QBaudRate>(); // set in thread, for thread-safety m_workerThread.execInThread([this, baudRate]() { m_modbusClient->setConnectionParameter(QModbusDevice::SerialBaudRateParameter, baudRate); }); // emit emit this->baudRateChanged(baudRate); } void QUaModbusRtuSerialClient::on_dataBitsChanged(const QVariant & value) { // NOTE : if connected, will not change until reconnect QDataBits dataBits = value.value<QDataBits>(); // set in thread, for thread-safety m_workerThread.execInThread([this, dataBits]() { m_modbusClient->setConnectionParameter(QModbusDevice::SerialDataBitsParameter, dataBits); }); // emit emit this->dataBitsChanged(dataBits); } void QUaModbusRtuSerialClient::on_stopBitsChanged(const QVariant & value) { // NOTE : if connected, will not change until reconnect QStopBits stopBits = value.value<QStopBits>(); // set in thread, for thread-safety m_workerThread.execInThread([this, stopBits]() { m_modbusClient->setConnectionParameter(QModbusDevice::SerialStopBitsParameter, stopBits); }); // emit emit this->stopBitsChanged(stopBits); } QString QUaModbusRtuSerialClient::getComPort() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); auto key = this->comPort()->value().toInt(); return QUaModbusRtuSerialClient::EnumComPorts().value(key).displayName.text(); } void QUaModbusRtuSerialClient::setComPort(const QString & strComPort) { QMutexLocker locker(&m_mutex); auto comPort = QUaModbusRtuSerialClient::EnumComPorts().key( { { "", strComPort.toUtf8() }, { "", "" } }, 0); this->comPort()->setValue(comPort); this->on_comPortChanged(comPort); } int QUaModbusRtuSerialClient::getComPortKey() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return this->comPort()->value().toInt(); } void QUaModbusRtuSerialClient::setComPortKey(const int & comPort) { QMutexLocker locker(&m_mutex); this->comPort()->setValue(comPort); this->on_comPortChanged(comPort); } QParity QUaModbusRtuSerialClient::getParity() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return this->parity()->value().value<QParity>(); } void QUaModbusRtuSerialClient::setParity(const QParity & parity) { QMutexLocker locker(&m_mutex); this->parity()->setValue(parity); this->on_parityChanged(parity); } QBaudRate QUaModbusRtuSerialClient::getBaudRate() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return this->baudRate()->value().value<QBaudRate>(); } void QUaModbusRtuSerialClient::setBaudRate(const QBaudRate & baudRate) { QMutexLocker locker(&m_mutex); this->baudRate()->setValue(baudRate); this->on_baudRateChanged(baudRate); } QDataBits QUaModbusRtuSerialClient::getDataBits() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return this->dataBits()->value().value<QDataBits>(); } void QUaModbusRtuSerialClient::setDataBits(const QDataBits & dataBits) { QMutexLocker locker(&m_mutex); this->dataBits()->setValue(dataBits); this->on_dataBitsChanged(dataBits); } QStopBits QUaModbusRtuSerialClient::getStopBits() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return this->stopBits()->value().value<QStopBits>(); } void QUaModbusRtuSerialClient::setStopBits(const QStopBits & stopBits) { QMutexLocker locker(&m_mutex); this->stopBits()->setValue(stopBits); this->on_stopBitsChanged(stopBits); }
35.838137
145
0.7313
juangburgos
489eea62bd2b9e266f41e6b0e4b9477aa9a1ad0a
6,023
cpp
C++
qt_project/MainWindow.cpp
hejiangda/DaDaXiuXiu
ed2aeba3517065ed552d17acd43c66863143a867
[ "MIT" ]
1
2020-03-18T02:34:32.000Z
2020-03-18T02:34:32.000Z
qt_project/MainWindow.cpp
hejiangda/DaDaXiuXiu
ed2aeba3517065ed552d17acd43c66863143a867
[ "MIT" ]
null
null
null
qt_project/MainWindow.cpp
hejiangda/DaDaXiuXiu
ed2aeba3517065ed552d17acd43c66863143a867
[ "MIT" ]
null
null
null
#include "MainWindow.h" #include "ui_MainWindow.h" #include <QFileInfo> #include <QDir> MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow), addFlg(0), t1ok(false), t2ok(false), t3ok(false) { ui->setupUi(this); connect(&MT1, SIGNAL(WhiteDisplay(QPixmap)), ui->WhiteImg, SLOT(setPixmap(QPixmap))); connect(&MT1, SIGNAL(TransDisplay(QPixmap)), ui->TransImg, SLOT(setPixmap(QPixmap))); connect(&MT2, SIGNAL(WhiteDisplay(QPixmap)), ui->WhiteImg, SLOT(setPixmap(QPixmap))); connect(&MT2, SIGNAL(TransDisplay(QPixmap)), ui->TransImg, SLOT(setPixmap(QPixmap))); connect(&MT3, SIGNAL(WhiteDisplay(QPixmap)), ui->WhiteImg, SLOT(setPixmap(QPixmap))); connect(&MT3, SIGNAL(TransDisplay(QPixmap)), ui->TransImg, SLOT(setPixmap(QPixmap))); connect(&MT1, SIGNAL(jobFinish(int)), this, SLOT(setflgAndReOpen(int))); connect(&MT2, SIGNAL(jobFinish(int)), this, SLOT(setflgAndReOpen(int))); connect(&MT3, SIGNAL(jobFinish(int)), this, SLOT(setflgAndReOpen(int))); MT1.setNo(1); MT2.setNo(2); MT3.setNo(3); } MainWindow::~MainWindow() { MT1.quit(); MT2.quit(); MT3.quit(); delete ui; } void MainWindow::dragEnterEvent(QDragEnterEvent* e) { if (e->mimeData()->hasUrls()) //判断数据类型 { e->acceptProposedAction();//接收该数据类型拖拽事件 } else { e->ignore();//忽略 } } void MainWindow::dropEvent(QDropEvent* event) { //窗口部件放下一个对象时,调用该函数 QList<QUrl> urls = event->mimeData()->urls(); if (urls.isEmpty()) { event->ignore(); return; } QStringList acceptedFileTypes; acceptedFileTypes.append("jpg"); acceptedFileTypes.append("png"); acceptedFileTypes.append("bmp"); QList<QUrl>::iterator it; for (it = urls.begin(); it != urls.end(); it++) { QUrl url = *it; QFileInfo fileInfo(it->toLocalFile()); if (fileInfo.isFile()) { if (acceptedFileTypes.contains(fileInfo.suffix().toLower())) { //是文件就直接加进来 ui->imgListWidget->addItem(fileInfo.filePath()); if (addFlg == 0) l1.push_back(fileInfo.filePath().toStdString()); else if (addFlg == 1) l2.push_back(fileInfo.filePath().toStdString()); else if (addFlg == 2) l3.push_back(fileInfo.filePath().toStdString()); addFlg = (addFlg + 1) % 3; } } else if (fileInfo.isDir()) { //文件路径就循环读取 QFileInfoList fileInfoList = GetAllFileList(fileInfo.filePath()); for (QFileInfo fileInfo1 : fileInfoList) { if (acceptedFileTypes.contains(fileInfo1.suffix().toLower())) { ui->imgListWidget->addItem(fileInfo1.filePath()); if (addFlg == 0) l1.push_back(fileInfo1.filePath().toStdString()); else if (addFlg == 1) l2.push_back(fileInfo1.filePath().toStdString()); else if (addFlg == 2) l3.push_back(fileInfo1.filePath().toStdString()); addFlg = (addFlg + 1) % 3; } } } } MT1.setFileLists(l1); MT2.setFileLists(l2); MT3.setFileLists(l3); if (ui->comboBox->currentIndex() == 0) { MT1.setSz(Size(800, 800)); MT2.setSz(Size(800, 800)); MT3.setSz(Size(800, 800)); } else { MT1.setSz(Size(800, 1200)); MT2.setSz(Size(800, 1200)); MT3.setSz(Size(800, 1200)); } } //只取得该目录下的子文件不考虑子文件夹 QFileInfoList MainWindow::GetAllFileList(QString path) { QDir dir(path); QFileInfoList file_list = dir.entryInfoList(QDir::Files | QDir::Hidden | QDir::NoSymLinks); return file_list; } void MainWindow::resizeEvent(QResizeEvent* event) { Q_UNUSED(event); if (!WhiteShow.isNull()) { ui->WhiteImg->setPixmap(WhiteShow.scaled(ui->WhiteImg->width() - 5, ui->WhiteImg->height() - 5, Qt::KeepAspectRatio, Qt::SmoothTransformation)); } if (!TransShow.isNull()) { ui->TransImg->setPixmap(TransShow.scaled(ui->TransImg->width() - 5, ui->TransImg->height() - 5, Qt::KeepAspectRatio, Qt::SmoothTransformation)); } } void MainWindow::on_imgListWidget_itemClicked(QListWidgetItem* item) { } void MainWindow::on_pushButton_clicked() { MT1.start(); t1ok = false; MT2.start(); t2ok = false; MT3.start(); t3ok = false; ui->pushButton->setDisabled(true); } #include <QMessageBox> void MainWindow::setflgAndReOpen(int flg) { // cout << "flg Ok:" << t1ok << " " << t2ok << " " << t3ok << endl; switch (flg) { case 1: t1ok = true; break; case 2: t2ok = true; break; case 3: t3ok = true; break; } if (t1ok and t2ok and t3ok) { t1ok = t2ok = t3ok = false; ui->pushButton->setDisabled(false); l1.clear(); l2.clear(); l3.clear(); ui->imgListWidget->clear(); cout << endl << "finished" << endl; QApplication::beep(); QMessageBox box; box.setWindowTitle("电商图片自动处理"); box.setText("所有图片已经处理完成,请添加新图片!"); box.exec(); } }
27.377273
95
0.506724
hejiangda
48a271564b47fbb9c429f0585ab527e5c81a5a93
15,795
hpp
C++
include/kip/elements.hpp
kei10in/kip
23d83ffa4f40431ef8bd6983e928ae889bfc3872
[ "MIT" ]
null
null
null
include/kip/elements.hpp
kei10in/kip
23d83ffa4f40431ef8bd6983e928ae889bfc3872
[ "MIT" ]
null
null
null
include/kip/elements.hpp
kei10in/kip
23d83ffa4f40431ef8bd6983e928ae889bfc3872
[ "MIT" ]
null
null
null
#ifndef KIP_ELEMENTS_HPP_ #define KIP_ELEMENTS_HPP_ #include <string> #include <unordered_map> #include <vector> #include "kip/xml-ns.hpp" namespace kip { struct static_object { std::string const empty_string; xml::qname const empty_qname; static_object() {} }; static static_object const& statics() { static static_object const s; return s; } template <class T, class U> class named_element_map { using container_t = std::unordered_map<xml::qname, std::shared_ptr<U>>; container_t container_; public: named_element_map() = default; bool operator==(named_element_map<T, U> const& rhs) const { return container_ == rhs.container_; } T find(xml::qname const& name) const { auto it = container_.find(name); if (it == container_.end()) { return T(); } else { return T(*it); } } std::pair<typename container_t::iterator, bool> insert(std::pair<xml::qname, std::shared_ptr<U>> const& v) { return container_.insert(v); } size_t size() const { return container_.size(); } template <class F> void traverse(F& f) const { for (auto const& it : container_) { T(it).traverse(f); } } }; struct property_impl; struct scored_property_impl; struct option_impl; struct feature_impl; struct parameter_def_impl; class property; class scored_property; class option; class feature_def; class parameter_def; using property_collection = named_element_map<property, property_impl>; using scored_property_collection = named_element_map<scored_property, scored_property_impl>; // todo: rename to feature_def_collection using feature_collection = named_element_map<feature_def, feature_impl>; using parameter_def_collection = named_element_map<parameter_def, parameter_def_impl>; enum class value_type { empty, string, qname, integer, decimal, }; class value_holder { public: virtual ~value_holder() {} virtual value_type type() const = 0; virtual std::string const& string_value() const = 0; virtual xml::qname const& qname_value() const = 0; virtual int integer_value() const = 0; virtual float decimal_value() const = 0; virtual bool equals(value_holder const& rhs) const = 0; virtual bool equals(std::string const& rhs) const = 0; virtual bool equals(xml::qname const& rhs) const = 0; virtual bool equals(int rhs) const = 0; virtual bool equals(float rhs) const = 0; }; template <value_type tag> class base_value_holder : public value_holder { protected: value_type type() const override { return tag; } std::string const& string_value() const override { return statics().empty_string; } xml::qname const& qname_value() const override { return statics().empty_qname; } int integer_value() const override { return 0; } float decimal_value() const override { return 0.0; } // can't define basics // bool equals(value_holder) const = 0; bool equals(std::string const& rhs) const override { return false; } bool equals(xml::qname const& rhs) const override { return false; } bool equals(int rhs) const override { return false; } bool equals(float rhs) const override { return false; } }; class empty_value_holder final : public base_value_holder<value_type::empty> { protected: bool equals(value_holder const& rhs) const override { return type() == rhs.type(); } }; template <value_type tag, class T> class assigned_value_holder : public base_value_holder<tag> { protected: T const value_; explicit assigned_value_holder(T const& v) : value_(v) {} bool equals(value_holder const& rhs) const override { if (type() != rhs.type()) return false; else return rhs.equals(value_); } }; class string_value_holder final : public assigned_value_holder<value_type::string, std::string> { public: explicit string_value_holder(std::string const& v) : assigned_value_holder(v) {} std::string const& string_value() const override { return value_; } bool equals(std::string const& rhs) const override { return value_ == rhs; } }; class qname_value_holder final : public assigned_value_holder<value_type::qname, xml::qname> { public: explicit qname_value_holder(xml::qname const& v) : assigned_value_holder(v) {} xml::qname const& qname_value() const override { return value_; } bool equals(xml::qname const& rhs) const override { return value_ == rhs; } }; class integer_value_holder final : public assigned_value_holder<value_type::integer, int> { public: explicit integer_value_holder(int v) : assigned_value_holder(v) {} int integer_value() const override { return value_; } bool equals(int rhs) const override { return value_ == rhs; } }; class decimal_value_holder final : public assigned_value_holder<value_type::decimal, float> { public: explicit decimal_value_holder(float v) : assigned_value_holder(v) {} float decimal_value() const override { return value_; } bool equals(float rhs) const override { return value_ == rhs; } }; class value { std::shared_ptr<value_holder> holder; public: value() : holder(std::make_shared<empty_value_holder>()) {} value(std::string const& v) : holder(std::make_shared<string_value_holder>(v)) {} value(xml::qname const& v) : holder(std::make_shared<qname_value_holder>(v)) {} value(int v) : holder(std::make_shared<integer_value_holder>(v)) {} value(float v) : holder(std::make_shared<decimal_value_holder>(v)) {} bool empty() const { return type() == value_type::empty; } value_type type() const { return holder->type(); } std::string const& string_value() const { return holder->string_value(); } xml::qname const& qname_value() const { return holder->qname_value(); } int integer_value() const { return holder->integer_value() ;} float decimal_value() const { return holder->decimal_value(); } bool operator==(value const& rhs) const { return holder->equals(*rhs.holder); } template <class T> bool operator==(T const& rhs) const { return holder->equals(rhs); } template <class F> void traverse(F& f) const { if (empty()) return; f.start(*this); f.end(*this); } }; struct parameter_ref { xml::qname name; }; inline bool operator==(parameter_ref const& lhs, parameter_ref const& rhs) { return lhs.name == rhs.name; } inline bool operator!=(parameter_ref const& lhs, parameter_ref const& rhs) { return !(lhs == rhs); } struct property_impl { kip::value value; property_collection properties; }; inline bool operator==(property_impl const& lhs, property_impl const& rhs) { return lhs.value == rhs.value && lhs.properties == rhs.properties; } inline bool operator!=(property_impl const& lhs, property_impl const& rhs) { return !(lhs == rhs); } class property { xml::qname name_; std::shared_ptr<property_impl> pimpl; public: property() {} property(std::pair<xml::qname, std::shared_ptr<property_impl>> const& v) : name_(v.first) , pimpl(v.second) {} property(xml::qname const& n, std::shared_ptr<property_impl> p) : name_(n) , pimpl(p) {} xml::qname const& name() const { return name_; } bool empty() { return pimpl == nullptr; } kip::value const& value() const { return pimpl->value; } property const& operator=(xml::qname const& v) { pimpl->value = v; return *this; } property const& operator=(std::string const& v) { pimpl->value = v; return *this; } template <class F> void traverse(F& f) const { f.start(*this); pimpl->value.traverse(f); pimpl->properties.traverse(f); f.end(*this); } }; struct scored_property_impl { parameter_ref reference; kip::value value; scored_property_collection scored_properties; property_collection properties; }; inline bool operator==(scored_property_impl const& lhs, scored_property_impl const& rhs) { return lhs.value == rhs.value && lhs.scored_properties == rhs.scored_properties && lhs.properties == rhs.properties; } inline bool operator!=(scored_property_impl const& lhs, scored_property_impl const& rhs) { return !(lhs == rhs); } class scored_property { xml::qname name_; std::shared_ptr<scored_property_impl> pimpl; public: scored_property() {} scored_property(std::pair<xml::qname, std::shared_ptr<scored_property_impl>> const& v) : name_(v.first) , pimpl(v.second) {} scored_property(xml::qname n, std::shared_ptr<scored_property_impl> p) : name_(n) , pimpl(p) {} bool empty() const { return pimpl == nullptr; } xml::qname const& name() const { return name_; } kip::value const& value() const { return pimpl->value; } template <class F> void traverse(F& f) const { f.start(*this); pimpl->value.traverse(f); pimpl->properties.traverse(f); pimpl->scored_properties.traverse(f); f.end(*this); } }; struct option_impl { xml::qname const name; xml::qname const constrained; scored_property_collection scored_properties; property_collection properties; option_impl(xml::qname const& name) : name(name) {} option_impl( xml::qname const& name, xml::qname const& constrained) : name(name) , constrained(constrained) {} }; inline bool operator==(option_impl const& lhs, option_impl const& rhs) { return lhs.name == rhs.name && lhs.constrained == rhs.constrained && lhs.scored_properties == rhs.scored_properties && lhs.properties == rhs.properties; } inline bool operator!=(option_impl const& lhs, option_impl const& rhs) { return !(lhs == rhs); } class option { std::shared_ptr<option_impl> pimpl; public: option() {} option(std::shared_ptr<option_impl> op) : pimpl(op) {} bool operator==(option const& rhs) const { return *pimpl == *rhs.pimpl; } bool empty() const { return pimpl == nullptr; } xml::qname const& name() const { return pimpl->name; } xml::qname const& constrained() const { return pimpl->constrained; } property property(xml::qname const& n) { return pimpl->properties.find(n); } scored_property scored_property(xml::qname const& n) { return pimpl->scored_properties.find(n); } // TODO: delete property_collection const& properties() const { return pimpl->properties; } // TODO: delete scored_property_collection const& scored_properties() const { return pimpl->scored_properties; } template <class F> void traverse(F& f) const { f.start(*this); pimpl->properties.traverse(f); pimpl->scored_properties.traverse(f); f.end(*this); } }; struct feature_impl { std::vector<option> options; property_collection properties; feature_collection sub_features; }; inline bool operator==(feature_impl const& lhs, feature_impl const& rhs) { return lhs.options == rhs.options && lhs.properties == rhs.properties && lhs.sub_features == rhs.sub_features; } inline bool operator!=(feature_impl const& lhs, feature_impl const& rhs) { return !(lhs == rhs); } class feature_def { xml::qname name_; std::shared_ptr<feature_impl> pimpl; public: feature_def() {} feature_def(std::pair<xml::qname, std::shared_ptr<feature_impl>> const& ft) : name_(ft.first) , pimpl(ft.second) {} feature_def(xml::qname const& n, std::shared_ptr<feature_impl> pimpl) : name_(n) , pimpl(pimpl) {} bool empty() const { return pimpl == nullptr; } xml::qname const& name() const { return name_; } std::vector<option> const& options() const { return pimpl->options; } property property(xml::qname const& n) { return pimpl->properties.find(n); } feature_def sub_feature(xml::qname const& n) { return pimpl->sub_features.find(n); } // TODO: delete property_collection const& properties() const { return pimpl->properties; } // TODO: delete feature_collection const& sub_features() const { return pimpl->sub_features; } template <class F> void traverse(F& f) const { f.start(*this); for (auto const& o : pimpl->options) { o.traverse(f); } pimpl->properties.traverse(f); f.end(*this); } }; struct parameter_init { kip::value value; }; inline bool operator==(parameter_init const& lhs, parameter_init const& rhs) { return lhs.value == rhs.value; } inline bool operator!=(parameter_init const& lhs, parameter_init const& rhs) { return !(lhs == rhs); } struct parameter_def_impl { property_collection properties; }; inline bool operator==(parameter_def_impl const& lhs, parameter_def_impl const& rhs) { return lhs.properties == rhs.properties; } inline bool operator!=(parameter_def_impl const& lhs, parameter_def_impl const& rhs) { return !(lhs == rhs); } class parameter_def { xml::qname name_; std::shared_ptr<parameter_def_impl> pimpl; public: parameter_def() {} parameter_def(std::pair<xml::qname, std::shared_ptr<parameter_def_impl>> pd) : name_(pd.first) , pimpl(pd.second) {} parameter_def(xml::qname const& n, std::shared_ptr<parameter_def_impl> p) : name_(n) , pimpl(p) {} bool empty() const { return pimpl == nullptr; } xml::qname const& name() const { return name_; } property property(xml::qname const& n) { return pimpl->properties.find(n); } template <class F> void traverse(F& f) const { f.start(*this); pimpl->properties.traverse(f); f.end(*this); } }; struct print_capabilities_impl { int version; std::string device_namespace; std::string device_namespace_prefix; feature_collection features; property_collection properties; parameter_def_collection parameters; print_capabilities_impl( int v, std::string const& dn, std::string const& pref ) : version(v) , device_namespace(dn) , device_namespace_prefix(pref) {} }; inline bool operator==(print_capabilities_impl const& lhs, print_capabilities_impl const& rhs) { return lhs.version == rhs.version && lhs.device_namespace == rhs.device_namespace && lhs.features == rhs.features && lhs.properties == rhs.properties && lhs.parameters == rhs.parameters; } inline bool operator!=(print_capabilities_impl const& lhs, print_capabilities_impl const& rhs) { return !(lhs == rhs); } class print_capabilities { bool empty_; std::shared_ptr<print_capabilities_impl> pimpl; public: print_capabilities() : empty_(true) , pimpl(std::shared_ptr<print_capabilities_impl>()) {} print_capabilities(std::shared_ptr<print_capabilities_impl> pimpl) : empty_(false) , pimpl(pimpl) {} bool empty() const { return empty_; } int version() const { return pimpl->version; } std::string const& device_namespace() const { return pimpl->device_namespace; } std::string const& device_namespace_prefix() const { return pimpl->device_namespace_prefix; } feature_def feature(xml::qname const& n) { return pimpl->features.find(n); } parameter_def parameter(xml::qname const& n) { return pimpl->parameters.find(n); } feature_collection const& features() const { return pimpl->features; } property_collection const& properties() const { return pimpl->properties; } parameter_def_collection const& parameters() const { return pimpl->parameters; } template <class F> void traverse(F& f) const { f.start(*this); pimpl->features.traverse(f); pimpl->parameters.traverse(f); pimpl->properties.traverse(f); f.end(*this); } }; struct print_ticket_document { int version; feature_collection features; std::unordered_map<xml::qname, property_impl> properties; std::unordered_map<xml::qname, parameter_init> parameters; }; } // namespace kip #endif // KIP_ELEMENTS_HPP_
22.090909
92
0.686103
kei10in
48a5561aa1275dd9a3126832a3e1371e13c8d865
247
hpp
C++
src/util.hpp
torque-project/rev
245561f9028d65c88029e4a4bc705f6a0a18da4c
[ "MIT" ]
1
2016-03-01T14:22:31.000Z
2016-03-01T14:22:31.000Z
src/util.hpp
torque-project/rev
245561f9028d65c88029e4a4bc705f6a0a18da4c
[ "MIT" ]
null
null
null
src/util.hpp
torque-project/rev
245561f9028d65c88029e4a4bc705f6a0a18da4c
[ "MIT" ]
null
null
null
#pragma once namespace rev { inline std::string replace(const std::string& s, char a, char b) { std::string out(s); int pos = 0; while ((pos = out.find(a)) != std::string::npos) { out[pos] = b; } return out; } }
14.529412
68
0.54251
torque-project
48a6b33d998c26470ff236c60ab2f19627b5f541
1,563
cpp
C++
src/c/rfc822/CMessageParser.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
3
2019-07-16T13:19:50.000Z
2020-01-06T10:42:23.000Z
src/c/rfc822/CMessageParser.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
15
2018-12-11T14:00:48.000Z
2021-12-21T17:42:42.000Z
src/c/rfc822/CMessageParser.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
2
2015-05-26T18:07:22.000Z
2017-04-04T10:01:17.000Z
#include "CMessageParser.h" #include "CBase+Private.h" #include <MailCore/MCCore.h> #include <MailCore/MCDefines.h> #include <MailCore/MCAttachment.h> #include <MailCore/MCMessageHeader.h> #include <MailCore/MCHTMLRenderer.h> #include <MailCore/MCHTMLBodyRendererTemplateCallback.h> #include "CData.h" #include "CAbstractMessageRendererCallback.h" #include "CAbstractMessageRendererCallbackWrapper.h" #define nativeType mailcore::MessageParser #define structName CMessageParser C_SYNTHESIZE_CONSTRUCTOR() C_SYNTHESIZE_COBJECT_CAST() CMessageParser CMessageParser_init(CData data) { return CMessageParser_new(new mailcore::MessageParser(data.instance)); } C_SYNTHESIZE_FUNC_WITH_OBJ(CAbstractPart, mainPart) C_SYNTHESIZE_FUNC_WITH_OBJ(CData, data) C_SYNTHESIZE_FUNC_WITH_OBJ(MailCoreString, htmlBodyRendering) C_SYNTHESIZE_FUNC_WITH_OBJ(MailCoreString, plainTextRendering) C_SYNTHESIZE_FUNC_WITH_OBJ(CDictionary, serializable) MailCoreString CMessageParser_plainTextBodyRenderingAndStripWhitespace(struct CMessageParser self, bool stripWhitespace) { return MailCoreString_new(self.instance->plainTextBodyRendering(stripWhitespace)); } MailCoreString CMessageParser_htmlRendering(struct CMessageParser self, struct CAbstractMessageRendererCallback htmlCallback) { return MailCoreString_new(self.instance->htmlRendering(static_cast<mailcore::HTMLRendererTemplateCallback*>(htmlCallback.callbackBridge))); } void CMessageParser_saveToFile(struct CMessageParser self, MailCoreString fileName) { self.instance->saveToFile(fileName.instance); }
36.348837
143
0.849648
readdle
48a8472b0de1d1e4264a77a96151090f3bc491c7
193
cpp
C++
kattis/zoo/zoo.cpp
pi-guy-in-the-sky/competitive-programming
e079f6caf07b5de061ea4f56218f9b577e49a965
[ "MIT" ]
null
null
null
kattis/zoo/zoo.cpp
pi-guy-in-the-sky/competitive-programming
e079f6caf07b5de061ea4f56218f9b577e49a965
[ "MIT" ]
null
null
null
kattis/zoo/zoo.cpp
pi-guy-in-the-sky/competitive-programming
e079f6caf07b5de061ea4f56218f9b577e49a965
[ "MIT" ]
1
2020-10-25T05:46:57.000Z
2020-10-25T05:46:57.000Z
#include <iostream> #include <string> using namespace std; int main() { int n; string cin >> n; while (n > 0) { for (int i = 0; i < n; i++) cin >> n; } }
12.866667
35
0.455959
pi-guy-in-the-sky
48aa101eddb97f962211341a51bb8ad0a307b828
2,787
cpp
C++
test/net/test_address_manager.cpp
EPI-ONE/epic
c314cab526641c00d49e51e08ec0793f1a6c171b
[ "MIT" ]
24
2019-10-14T14:35:32.000Z
2021-11-28T02:06:26.000Z
test/net/test_address_manager.cpp
EPI-ONE/epic
c314cab526641c00d49e51e08ec0793f1a6c171b
[ "MIT" ]
3
2019-10-14T14:29:07.000Z
2020-01-21T14:48:49.000Z
test/net/test_address_manager.cpp
EPI-ONE/epic
c314cab526641c00d49e51e08ec0793f1a6c171b
[ "MIT" ]
4
2020-04-09T09:12:50.000Z
2021-06-15T13:41:42.000Z
// Copyright (c) 2019 EPI-ONE Core Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <gtest/gtest.h> #include "address_manager.h" class TestAddressManager : public testing::Test { public: AddressManager addressManager; std::string addressFilePath = "test_address.toml"; NetAddress ip1 = *NetAddress::GetByIP("127.0.0.1:7877"); NetAddress ip2 = *NetAddress::GetByIP("192.168.0.1:7877"); NetAddress ip3 = *NetAddress::GetByIP("100.0.0.4:7877"); NetAddress ip4 = *NetAddress::GetByIP("172.4.2.111:7877"); void SetUp() { addressManager.AddNewAddress(ip1); addressManager.AddNewAddress(ip2); addressManager.AddNewAddress(ip3); addressManager.AddNewAddress(ip4); } void TearDown() { addressManager.Clear(); } }; TEST_F(TestAddressManager, BasicOp) { EXPECT_TRUE(addressManager.IsNew(ip1)); EXPECT_TRUE(addressManager.IsNew(ip2)); EXPECT_TRUE(addressManager.IsNew(ip3)); EXPECT_TRUE(addressManager.IsNew(ip4)); addressManager.MarkOld(ip1); addressManager.MarkOld(ip2); EXPECT_TRUE(addressManager.IsOld(ip1)); EXPECT_TRUE(addressManager.IsOld(ip2)); EXPECT_FALSE(addressManager.IsNew(ip1)); EXPECT_FALSE(addressManager.IsNew(ip2)); EXPECT_TRUE(addressManager.ContainAddress(ip1)); EXPECT_TRUE(addressManager.ContainAddress(ip2)); EXPECT_TRUE(addressManager.ContainAddress(ip3)); EXPECT_TRUE(addressManager.ContainAddress(ip4)); } TEST_F(TestAddressManager, GetAddr) { auto addresses = addressManager.GetAddresses(); EXPECT_EQ(addresses.size(), 4); addressManager.MarkOld(ip1); addressManager.MarkOld(ip2); auto res = addressManager.GetOneAddress(true); EXPECT_TRUE(addressManager.IsNew(*res)); } TEST_F(TestAddressManager, SaveAndLoad) { addressManager.SaveAddress("./", addressFilePath); addressManager.Clear(); addressManager.LoadAddress("./", addressFilePath); std::remove(addressFilePath.c_str()); EXPECT_EQ(addressManager.SizeOfAllAddr(), 4); } TEST_F(TestAddressManager, LocalAddr) { addressManager.LoadLocalAddresses(); EXPECT_TRUE(addressManager.IsLocal(ip1)); } TEST_F(TestAddressManager, DeleteInactiveAddr) { CONFIG = std::make_unique<Config>(); addressManager.SaveAddress("./", addressFilePath); for (int i = 0; i < CONFIG->GetMaxFailedAttempts() + 1; i++) { addressManager.SetLastTry(ip4, time(nullptr)); } addressManager.SaveAddress("./", addressFilePath); addressManager.Clear(); addressManager.LoadAddress("./", addressFilePath); std::remove(addressFilePath.c_str()); EXPECT_FALSE(addressManager.ContainAddress(ip4)); }
31.314607
70
0.717976
EPI-ONE
48abc277e66474d520ca9e1938c3ea96b918c2eb
1,484
cpp
C++
cpp/segment_trees/segtree2d_min.cpp
petuhovskiy/Templates-CP
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
[ "MIT" ]
8
2016-06-05T19:19:27.000Z
2019-05-14T10:33:37.000Z
cpp/segment_trees/segtree2d_min.cpp
petuhovskiy/Templates-CP
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
[ "MIT" ]
2
2017-02-21T12:38:27.000Z
2018-01-28T20:05:00.000Z
cpp/segment_trees/segtree2d_min.cpp
petuhovskiy/Templates-CP
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
[ "MIT" ]
6
2015-12-26T21:12:17.000Z
2022-03-26T21:40:17.000Z
class segtree{ public: int n; // array size vector<int> t; void build(vector<int> &v) { // build the tree for (int i = n; i < 2 * n; i++) t[i] = v[i - n]; for (int i = n - 1; i > 0; --i) t[i] = min(t[i<<1], t[i<<1|1]); } void build(segtree &t1, segtree &t2) { // build the tree for (int i = 1; i < 2 * n; i++) t[i] = min(t1.t[i], t2.t[i]); } int query(int l, int r) { // sum on interval [l, r) int res = 2e9; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l&1) res = min(res, t[l++]); if (r&1) res = min(res, t[--r]); } return res; } segtree(int n):n(n),t(){ t.resize(n << 1); } }; class segtree2{ public: int n, m; // array size vector<segtree> t; void build(vector<vector<int> > &v) { // build the tree for (int i = 0; i < n; i++) { t[n + i].build(v[i]); } for (int i = n - 1; i > 0; i--) { t[i].build(t[i * 2], t[i * 2 + 1]); } } int query(int d, int l, int u, int r) { // sum on interval [l, r) int res = 2e9; for (d += n, u += n; d < u; d >>= 1, u >>= 1) { if (d&1) res = min(res, t[d++].query(l, r)); if (u&1) res = min(res, t[--u].query(l, r)); } return res; } segtree2(int n, int m, vector<vector<int> > &v):n(n),m(m),t(){ t.assign(n << 1, segtree(m)); build(v); } };
26.035088
71
0.402291
petuhovskiy
48ac16a9362fecb2a66229ae8ae4449c8816d748
1,002
cpp
C++
Benchmarks/UnorderedMap/UMapAllocBench.cpp
adamhutchings/HackySTL
624a0cdc92b297f52588190d3a693d6923b7a4e7
[ "MIT" ]
33
2020-11-20T14:58:25.000Z
2022-03-04T10:04:08.000Z
Benchmarks/UnorderedMap/UMapAllocBench.cpp
adamhutchings/HackySTL
624a0cdc92b297f52588190d3a693d6923b7a4e7
[ "MIT" ]
8
2021-01-05T23:18:32.000Z
2022-02-22T18:25:37.000Z
Benchmarks/UnorderedMap/UMapAllocBench.cpp
HackyTeam/HackySTL
2496c7e110a218d09c73005b5a39d15b380ce354
[ "MIT" ]
6
2021-01-05T22:02:57.000Z
2022-02-22T18:34:22.000Z
#include <benchmark/benchmark.h> #include "../../cpp/UnorderedMap.hpp" static void MapBufAlloc(benchmark::State& state) { hsd::uchar buf[4096]{}; for(auto _ : state) { hsd::buffered_allocator<hsd::uchar> alloc{buf, 4096}; hsd::unordered_map<size_t, size_t, hsd::hash<size_t, size_t>, hsd::buffered_allocator> map{alloc}; [&]<size_t... Ints>(hsd::index_sequence<Ints...>) { (map.emplace(Ints, Ints), ...); }(hsd::make_index_sequence<14>{}); benchmark::DoNotOptimize(map.begin()); } } static void MapHeapAlloc(benchmark::State& state) { for(auto _ : state) { hsd::unordered_map<size_t, size_t, hsd::hash<size_t, size_t>> map; [&]<size_t... Ints>(hsd::index_sequence<Ints...>) { (map.emplace(Ints, Ints), ...); }(hsd::make_index_sequence<14>{}); benchmark::DoNotOptimize(map.begin()); } } BENCHMARK(MapBufAlloc); BENCHMARK(MapHeapAlloc); BENCHMARK_MAIN();
24.439024
106
0.5998
adamhutchings
48b1be830bec6aabb243a2c8faf705c2ee737be9
3,784
cpp
C++
src/reconstruct/weno5.cpp
luminoctum/athena-crm
525ad5d1c442f9f6d66f2307eed88cd6fb723810
[ "BSD-3-Clause" ]
null
null
null
src/reconstruct/weno5.cpp
luminoctum/athena-crm
525ad5d1c442f9f6d66f2307eed88cd6fb723810
[ "BSD-3-Clause" ]
null
null
null
src/reconstruct/weno5.cpp
luminoctum/athena-crm
525ad5d1c442f9f6d66f2307eed88cd6fb723810
[ "BSD-3-Clause" ]
null
null
null
//======================================================================================== // Athena++ astrophysical MHD code // Copyright(C) 2014 James M. Stone <[email protected]> and other code contributors // Licensed under the 3-clause BSD License, see LICENSE file for details //======================================================================================== //! \file plm.cpp // \brief piecewise linear reconstruction // Athena++ headers #include "reconstruction.hpp" #include "../athena.hpp" #include "../athena_arrays.hpp" #include "../hydro/hydro.hpp" #include "../mesh/mesh.hpp" #include "../coordinates/coordinates.hpp" // WENO 5 interpolation inline Real interp_weno5(Real phim2, Real phim1, Real phi, Real phip1, Real phip2) { Real p0 = (1.0/3.0)*phim2 - (7.0/6.0)*phim1 + (11.0/6.0)*phi; Real p1 = (-1.0/6.0) * phim1 + (5.0/6.0)*phi + (1.0/3.0)*phip1; Real p2 = (1.0/3.0) * phi + (5.0/6.0)*phip1 - (1.0/6.0)*phip2; Real beta2 = (13.0/12.0 * (phi - 2.0 * phip1 + phip2)*(phi - 2.0 * phip1 + phip2) + 0.25 * (3.0 * phi - 4.0 * phip1 + phip2)*(3.0 * phi - 4.0 * phip1 + phip2)); Real beta1 = (13.0/12.0 * (phim1 - 2.0 * phi + phip1)*(phim1 - 2.0 * phi + phip1) + 0.25 * (phim1 - phip1)*(phim1 - phip1)); Real beta0 = (13.0/12.0 * (phim2 - 2.0 * phim1 + phi)*(phim2 - 2.0 * phim1 + phi) + 0.25 * (phim2 - 4.0 * phim1 + 3.0 * phi)*(phim2 - 4.0 * phim1 + 3.0 * phi)); Real alpha0 = 0.1/((beta0 + 1e-10) * (beta0 + 1e-10)); Real alpha1 = 0.6/((beta1 + 1e-10) * (beta1 + 1e-10)); Real alpha2 = 0.3/((beta2 + 1e-10) * (beta2 + 1e-10)); Real alpha_sum_inv = 1.0/(alpha0 + alpha1 + alpha2); Real w0 = alpha0 * alpha_sum_inv; Real w1 = alpha1 * alpha_sum_inv; Real w2 = alpha2 * alpha_sum_inv; return w0 * p0 + w1 * p1 + w2 * p2; }; //---------------------------------------------------------------------------------------- //! \fn Reconstruction::ReconstructionFuncX1() // \brief void Reconstruction::HighResFuncX1(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &q, const AthenaArray<Real> &bcc, AthenaArray<Real> &ql, AthenaArray<Real> &qr) { for (int n=0; n<NHYDRO; ++n) { #pragma simd for (int i=il; i<=iu; ++i){ ql(n,i) = interp_weno5(q(n,k,j,i-3),q(n,k,j,i-2),q(n,k,j,i-1),q(n,k,j,i),q(n,k,j,i+1)); qr(n,i) = interp_weno5(q(n,k,j,i+2),q(n,k,j,i+1),q(n,k,j,i),q(n,k,j,i-1),q(n,k,j,i-2)); } } return; } //---------------------------------------------------------------------------------------- //! \fn Reconstruction::ReconstructionFuncX2() // \brief void Reconstruction::HighResFuncX2(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &q, const AthenaArray<Real> &bcc, AthenaArray<Real> &ql, AthenaArray<Real> &qr) { for (int n=0; n<NHYDRO; ++n) { #pragma simd for (int i=il; i<=iu; ++i){ ql(n,i) = interp_weno5(q(n,k,j-3,i),q(n,k,j-2,i),q(n,k,j-1,i),q(n,k,j,i),q(n,k,j+1,i)); qr(n,i) = interp_weno5(q(n,k,j+2,i),q(n,k,j+1,i),q(n,k,j,i),q(n,k,j-1,i),q(n,k,j-2,i)); } } return; } //---------------------------------------------------------------------------------------- //! \fn Reconstruction::ReconstructionFuncX3() // \brief void Reconstruction::HighResFuncX3(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &q, const AthenaArray<Real> &bcc, AthenaArray<Real> &ql, AthenaArray<Real> &qr) { for (int n=0; n<NHYDRO; ++n) { #pragma simd for (int i=il; i<=iu; ++i){ ql(n,i) = interp_weno5(q(n,k-3,j,i),q(n,k-2,j,i),q(n,k-1,j,i),q(n,k,j,i),q(n,k,j,i+1)); qr(n,i) = interp_weno5(q(n,k+2,j,i),q(n,k+1,j,i),q(n,k,j,i),q(n,k-1,j,i),q(n,k-2,j,i)); } } return; }
37.098039
102
0.512421
luminoctum
48b5fbbb2924f7f6f143de57bc188593f3db3097
432
cpp
C++
linear-list/array/climbing_stairs.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
1
2015-07-15T07:31:42.000Z
2015-07-15T07:31:42.000Z
linear-list/array/climbing_stairs.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
null
null
null
linear-list/array/climbing_stairs.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
null
null
null
/** *You are climbing a stair case. It takes n steps to reach to the top. *Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? * */ class Solution { public: int climbStairs(int n) { int prev = 0; int cur = 1; for(int i = 1; i <= n; i++) { int tmp = prev; cur += prev; prev = tmp; } return cur; } };
22.736842
98
0.513889
zhangxin23
48b7d4bd1fafc82dd2fd9a8c0364ea416fb66cda
164
cpp
C++
atcoder/abc86_a.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
3
2018-01-08T02:52:51.000Z
2021-03-03T01:08:44.000Z
atcoder/abc86_a.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
null
null
null
atcoder/abc86_a.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
1
2020-08-13T18:07:35.000Z
2020-08-13T18:07:35.000Z
#include <bits/stdc++.h> using namespace std; int main(){ int a, b; cin >> a >> b; printf("%s\n", (a % 2 != 0 && b % 2 != 0) ? "Odd" : "Even"); return 0; }
18.222222
62
0.47561
cosmicray001
48bfd7aa35f34e02e3032c71d380f1497af2dfc3
744
cpp
C++
src/lib/word_loader.cpp
michielgoethals/word-blaster-solution
58720caeeda16356b32ade501add2e018a3b755d
[ "MIT" ]
null
null
null
src/lib/word_loader.cpp
michielgoethals/word-blaster-solution
58720caeeda16356b32ade501add2e018a3b755d
[ "MIT" ]
null
null
null
src/lib/word_loader.cpp
michielgoethals/word-blaster-solution
58720caeeda16356b32ade501add2e018a3b755d
[ "MIT" ]
3
2020-06-03T10:01:22.000Z
2020-10-02T11:26:18.000Z
#include "word_loader.h" #include <fstream> #include <iostream> namespace WordBlasterTheGame { void WordLoader::load(WordList * words, std::string filename) { // Load from file - see https://oop-cpp.netlify.app/09-file-streams/#reading-from-a-file // File stream object std::ifstream file; file.open(filename); // Make sure operation did not fail if (!file) { std::cerr << "Could not open the file " << filename << " in reading mode" << std::endl; return; // Let's do nothing anymore } // Read the words from the file and store them in the wordlist std::string line; while (getline(file, line)) { words->add(line); } // Close the file file.close(); } };
24
92
0.620968
michielgoethals
48c1139d6b2aef6f5c0145f943bc1d3c135b6c10
2,751
cpp
C++
lib/primesieve/src/PreSieve.cpp
KrishnaPrasath/primecount
16e6f70643c45aaac8a96aa127f21b1ed1a51063
[ "BSD-2-Clause" ]
1
2019-11-10T18:45:48.000Z
2019-11-10T18:45:48.000Z
lib/primesieve/src/PreSieve.cpp
KrishnaPrasath/primecount
16e6f70643c45aaac8a96aa127f21b1ed1a51063
[ "BSD-2-Clause" ]
null
null
null
lib/primesieve/src/PreSieve.cpp
KrishnaPrasath/primecount
16e6f70643c45aaac8a96aa127f21b1ed1a51063
[ "BSD-2-Clause" ]
null
null
null
/// /// @file PreSieve.cpp /// @brief Pre-sieve multiples of small primes to speed up /// the sieve of Eratosthenes. /// /// Copyright (C) 2018 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/PreSieve.hpp> #include <primesieve/EratSmall.hpp> #include <primesieve/pmath.hpp> #include <primesieve/types.hpp> #include <stdint.h> #include <algorithm> #include <array> #include <iterator> #include <memory> using namespace std; namespace { // small primes >= 7 const array<uint64_t, 5> primes = { 7, 11, 13, 17, 19 }; // prime products of primes >= 7 const array<uint64_t, 5> primeProducts = { 210, 2310, 30030, 510510, 9699690 }; } // namespace namespace primesieve { void PreSieve::init(uint64_t start, uint64_t stop) { // the pre-sieve buffer should be at least 10 // times smaller than the sieving distance // in order to reduce initialization overhead uint64_t dist = stop - start; uint64_t threshold = max(dist, isqrt(stop)) / 100; auto last = primeProducts.end() - 1; auto iter = lower_bound(primeProducts.begin(), last, threshold); auto i = distance(primeProducts.begin(), iter); if (primes.at(i) > maxPrime_) initBuffer(primes[i], primeProducts[i]); } /// Initialize the buffer by removing the /// multiples of primes <= maxPrime. /// void PreSieve::initBuffer(uint64_t maxPrime, uint64_t primeProduct) { maxPrime_ = maxPrime; primeProduct_ = primeProduct; size_ = primeProduct_ / 30; buffer_ = new byte_t[size_]; deleter_.reset(buffer_); fill_n(buffer_, size_, (byte_t) 0xff); EratSmall eratSmall; uint64_t stop = primeProduct_ * 2; eratSmall.init(stop, size_, maxPrime_); for (uint64_t prime : primes) if (prime <= maxPrime_) eratSmall.addSievingPrime(prime, primeProduct_); eratSmall.crossOff(buffer_, size_); } /// Copy pre-sieved buffer to sieve array void PreSieve::copy(byte_t* sieve, uint64_t sieveSize, uint64_t segmentLow) const { // find segmentLow index uint64_t remainder = segmentLow % primeProduct_; uint64_t i = remainder / 30; uint64_t sizeLeft = size_ - i; if (sieveSize <= sizeLeft) copy_n(&buffer_[i], sieveSize, sieve); else { // copy the last remaining bytes of buffer // to the beginning of the sieve array copy_n(&buffer_[i], sizeLeft, sieve); // restart copying at the beginning of buffer for (i = sizeLeft; i + size_ < sieveSize; i += size_) copy_n(buffer_, size_, &sieve[i]); // copy the last remaining bytes copy_n(buffer_, sieveSize - i, &sieve[i]); } } } // namespace
25.95283
79
0.671029
KrishnaPrasath
48c3ff7071457459aaa9ff43e137fcb2f82e27f3
517
hpp
C++
include/sigma/graphics/cubemap.hpp
siegelaaron94/engine
e09985b37de8d3d671878b9e0385e8d73cd0f441
[ "MIT" ]
3
2017-03-30T03:08:48.000Z
2018-07-27T17:48:41.000Z
include/sigma/graphics/cubemap.hpp
siegelaaron94/engine
e09985b37de8d3d671878b9e0385e8d73cd0f441
[ "MIT" ]
34
2016-12-28T18:04:22.000Z
2017-06-01T07:32:48.000Z
include/sigma/graphics/cubemap.hpp
siegelaaron94/engine
e09985b37de8d3d671878b9e0385e8d73cd0f441
[ "MIT" ]
1
2017-05-13T05:45:01.000Z
2017-05-13T05:45:01.000Z
#ifndef SIGMA_GRAPHICS_CUBEMAP_HPP #define SIGMA_GRAPHICS_CUBEMAP_HPP #include <sigma/config.hpp> #include <sigma/graphics/texture.hpp> #include <array> namespace sigma { namespace graphics { struct cubemap { enum class face : unsigned int { POSITIVE_X, NEGATIVE_X, POSITIVE_Y, NEGATIVE_Y, POSITIVE_Z, NEGATIVE_Z }; std::array<std::shared_ptr<texture>, 6> faces; }; } } #endif // SIGMA_GRAPHICS_CUBEMAP_HPP
18.464286
54
0.618956
siegelaaron94
48c67e2ad26fdc3c2748e7b63e2b0b6d4dc41aa2
3,287
cpp
C++
src/HumdrumFileContent-timesig.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
19
2016-06-18T02:03:56.000Z
2022-02-23T17:26:32.000Z
src/HumdrumFileContent-timesig.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
43
2017-03-09T07:32:12.000Z
2022-03-23T20:18:35.000Z
src/HumdrumFileContent-timesig.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
5
2019-11-14T22:24:02.000Z
2021-09-07T18:27:21.000Z
// // Programmer: Craig Stuart Sapp <[email protected]> // Creation Date: Wed Nov 30 22:27:57 PST 2016 // Last Modified: Wed Nov 30 22:28:03 PST 2016 // Filename: HumdrumFileContent-timesig.cpp // URL: https://github.com/craigsapp/humlib/blob/master/src/HumdrumFileContent-timesig.cpp // Syntax: C++11; humlib // vim: syntax=cpp ts=3 noexpandtab nowrap // // Description: // Extracts time signature top and bottoms for a specific part. // #include "HumdrumFileContent.h" #include "Convert.h" #include <algorithm> #include <string.h> using namespace std; namespace hum { // START_MERGE ////////////////////////////// // // HumdrumFileStructure::getTimeSigs -- Return the prevailing time signature // top and bottom for a particular spine for each line in the HumdrumFile. // This version does not handle mulimeters such as 2+3/4 or 3/4+6/8. // Only checks the primary strand of a spine/track for time signatures. // // default value: track = 0: 0 means use the time signature // of the first **kern spine in the file; otherwise, use the // time signatures found in the given track (indexed from 1 // for the first spine on a line). A value of <0, 0> is used for // unassigned time signature lines. // void HumdrumFileContent::getTimeSigs(vector<pair<int, HumNum> >& output, int track) { HumdrumFileStructure& infile = *this; int lineCount = infile.getLineCount(); output.resize(lineCount); pair<int, HumNum> current(0, 0); fill(output.begin(), output.end(), current); if (track == 0) { vector<HTp> kernspines = infile.getKernSpineStartList(); if (kernspines.size() > 0) { track = kernspines[0]->getTrack(); } } if (track == 0) { track = 1; } int top = 0; // top number of time signature (0 for no meter) int bot = 0; // bottom number of time signature int bot2 = 0; // such as the 2 in 3%2. int firstsig = -1; int firstdata = -1; HTp token = getTrackStart(track); while (token) { if (token->isData()) { if (firstdata < 0) { firstdata = token->getLineIndex(); } token = token->getNextToken(); continue; } if (!token->isInterpretation()) { token = token->getNextToken(); continue; } // check for time signature: if (sscanf(token->c_str(), "*M%d/%d%%%d", &top, &bot, &bot2) == 3) { current.first = top; current.second.setValue(bot, bot2); if (firstsig < 0) { firstsig = token->getLineIndex(); } } else if (sscanf(token->c_str(), "*M%d/%d", &top, &bot) == 2) { current.first = top; current.second = bot; if (firstsig < 0) { firstsig = token->getLineIndex(); } } output[token->getLineIndex()] = current; token = token->getNextToken(); } // Back-fill the list if the first time signature occurs before // the start of the data: if ((firstsig > 0) && (firstdata >= firstsig)) { current = output[firstsig]; for (int i=0; i<firstsig; i++) { output[i] = current; } } // In-fill the list: int starti = firstsig; if (starti < 0) { starti = 0; } current = output[starti]; for (int i=starti+1; i<(int)output.size(); i++) { if (output[i].first == 0) { output[i] = current; } else { current = output[i]; } } } // END_MERGE } // end namespace hum
26.087302
100
0.628841
johnnymac647
48c8cc9758779b2a17818786c04154910b6436d0
204
cpp
C++
CodeForces/StonesontheTable.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
CodeForces/StonesontheTable.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
CodeForces/StonesontheTable.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; string str; cin>>str; int count = 0; for(int i = 1; i < n; i++){ if(str[i] == str[i-1]){ count++; } } cout<<count; }
12.75
28
0.529412
mysterio0801
48c9d6686ef4c99b92b07ded20964e49ad020417
2,372
cpp
C++
src/maze.cpp
carolinafsilva/Pacman
e7c5c1c448d4888bdf1c6e72e9a542bdebe65720
[ "MIT" ]
null
null
null
src/maze.cpp
carolinafsilva/Pacman
e7c5c1c448d4888bdf1c6e72e9a542bdebe65720
[ "MIT" ]
null
null
null
src/maze.cpp
carolinafsilva/Pacman
e7c5c1c448d4888bdf1c6e72e9a542bdebe65720
[ "MIT" ]
null
null
null
#include "maze.hpp" glm::vec2 Maze::getCenter(glm::vec3 position) { return glm::vec2(position.x + position.z / 2, position.y + position.z / 2); } int Maze::getDotsRemaining() { return this->dotsRemaining; } void Maze::decrementDotsRemaining() { this->dotsRemaining -= 1; } glm::ivec2 Maze::pixelToBlock(glm::vec2 center) { int c = floor(center.x / 8); int l = floor(center.y / 8); return glm::ivec2(l, c); } glm::vec2 Maze::blockToPixel(glm::ivec2 block) { int x = block.y * 8 + 4; int y = block.x * 8 + 4; return glm::vec2(x, y); } glm::ivec2 Maze::blockNext(glm::ivec2 block, orientation direction) { int c, l; switch (direction) { case up: l = block.x - 1; c = block.y; break; case left: l = block.x; c = block.y - 1; break; case down: l = block.x + 1; c = block.y; break; case right: l = block.x; c = block.y + 1; break; } return glm::ivec2(l, c); } bool Maze::valid(glm::ivec2 block, bool door) { if (block.x >= 0 && block.x < BLOCK_L && block.y >= 0 && block.y < BLOCK_C) { return (door && this->isDoor(block)) || this->matrix[block.x][block.y] >= 0; } return false; } bool Maze::isDoor(glm::ivec2 block) { return this->matrix[block.x][block.y] == -2; } int Maze::eat(glm::ivec2 block) { int points = 0; if (valid(block, false)) { points = matrix[block.x][block.y]; matrix[block.x][block.y] = 0; } return points; } int Maze::value(glm::ivec2 block) { int points = 0; if (valid(block, false)) { points = matrix[block.x][block.y]; } return points; } float Maze::euclidianDist(glm::vec2 position1, glm::vec2 position2) { return sqrtf(powf(position1.x - position2.x, 2) + powf(position1.y - position2.y, 2)); } glm::vec2 Maze::getTunnelLeft() { return this->tunnelLeft; } glm::vec2 Maze::getTunnelRight() { return this->tunnelRight; }; void Maze::reset() { this->dotsRemaining = 244; for (int i = 0; i < BLOCK_L; i++) { for (int j = 0; j < BLOCK_C; j++) { this->matrix[i][j] = this->backup[i][j]; } } } Maze::Maze() { this->dotsRemaining = 244; this->tunnelLeft = glm::vec2(-16, 108); this->tunnelRight = glm::vec2(224, 108); for (int i = 0; i < BLOCK_L; i++) { for (int j = 0; j < BLOCK_C; j++) { this->backup[i][j] = this->matrix[i][j]; } } }
23.485149
80
0.580523
carolinafsilva
48d8f8775f3a096dcde034aee4c13a4a099db4cd
115
cpp
C++
source/qt_Kviewer/s4KlogicItem.cpp
chinsaiki/s4-gui
c8a11aad28150da71127b89370bea9b7e2530fee
[ "MIT" ]
null
null
null
source/qt_Kviewer/s4KlogicItem.cpp
chinsaiki/s4-gui
c8a11aad28150da71127b89370bea9b7e2530fee
[ "MIT" ]
null
null
null
source/qt_Kviewer/s4KlogicItem.cpp
chinsaiki/s4-gui
c8a11aad28150da71127b89370bea9b7e2530fee
[ "MIT" ]
null
null
null
#include "qt_Kviewer/s4KlogicItem.h" #include "qt_Kviewer/s4Kinstrument_scene.h" namespace S4{ namespace QT{ } }
12.777778
43
0.773913
chinsaiki
48d9dfad5c420c628d213b122d110468a011f4dc
5,937
cpp
C++
test/psim/core/state_field_test.cpp
kylekrol/psim
a4817117189f0f5597452076e6e138f70f51d4e8
[ "MIT" ]
5
2020-04-11T06:53:46.000Z
2022-01-05T05:39:11.000Z
test/psim/core/state_field_test.cpp
kylekrol/psim
a4817117189f0f5597452076e6e138f70f51d4e8
[ "MIT" ]
201
2019-09-05T03:46:21.000Z
2022-01-08T04:44:16.000Z
test/psim/core/state_field_test.cpp
kylekrol/psim
a4817117189f0f5597452076e6e138f70f51d4e8
[ "MIT" ]
10
2019-10-12T17:24:34.000Z
2022-02-25T01:20:14.000Z
/** @file test/psim/core/state_field_test.cpp * @author Kyle Krol */ #include <gtest/gtest.h> #include <psim/core/state_field.hpp> #include <psim/core/state_field_lazy.hpp> #include <psim/core/state_field_valued.hpp> #include <psim/core/types.hpp> #include <stdexcept> TEST(StateField, TestCast) { psim::StateFieldValued<psim::Real> field("default"); // Test for `StateFieldBase` { psim::StateFieldBase &base_field = field; ASSERT_EQ(&(base_field.template cast<psim::Real>()), &field); EXPECT_THROW(base_field.template cast<psim::Integer>(), std::runtime_error); } // Test for `StateFieldBase const` { psim::StateFieldBase const &base_field = field; ASSERT_EQ(&(base_field.template cast<psim::Real>()), &field); EXPECT_THROW(base_field.template cast<psim::Integer>(), std::runtime_error); } // Test for `StateField` { psim::StateField<psim::Real> &base_field = field; ASSERT_EQ(&(base_field.template cast<psim::Real>()), &field); // EXPECT_THROW(base_field.cast<psim::Integer>(), std::runtime_error); // ^ throws a state assertion error } // Test for `StateField const` { psim::StateField<psim::Real> const &base_field = field; ASSERT_EQ(&(base_field.template cast<psim::Real>()), &field); // EXPECT_THROW(base_field.cast<psim::Integer>(), std::runtime_error); // ^ throws a state assertion error } } TEST(StateField, TestCastWritable) { // Test for non-writable state fields { psim::StateFieldLazy<psim::Real> field( "default", []() { return psim::Real(); }); // Test for `StateFieldBase` { psim::StateFieldBase &base_field = field; EXPECT_THROW( base_field.template cast_writable<psim::Real>(), std::runtime_error); } // Test for `StateFieldBase const` { psim::StateFieldBase const &base_field = field; EXPECT_THROW( base_field.template cast_writable<psim::Real>(), std::runtime_error); } // Test for `StateField` { psim::StateField<psim::Real> *field_ptr = &field; EXPECT_THROW( field_ptr->template cast_writable<psim::Real>(), std::runtime_error); } // Test for `StateField const` { psim::StateField<psim::Real> const &base_field = field; EXPECT_THROW( base_field.template cast_writable<psim::Real>(), std::runtime_error); } } // Test for writable state fields { psim::StateFieldValued<psim::Real> field("default"); // Test for `StateFieldBase` { psim::StateFieldBase &base_field = field; ASSERT_EQ(&(base_field.cast<psim::Real>()), &field); EXPECT_THROW(base_field.cast<psim::Integer>(), std::runtime_error); } // Test for `StateFieldBase const` { psim::StateFieldBase const &base_field = field; ASSERT_EQ(&(base_field.template cast<psim::Real>()), &field); EXPECT_THROW( base_field.template cast<psim::Integer>(), std::runtime_error); } // Test for `StateField` { psim::StateField<psim::Real> &base_field = field; ASSERT_EQ(&(base_field.template cast<psim::Real>()), &field); // EXPECT_THROW(base_field.cast<psim::Integer>(), std::runtime_error); // ^ throws a state assertion error } // Test for `StateField const` { psim::StateField<psim::Real> const &base_field = field; ASSERT_EQ(&(base_field.cast<psim::Real>()), &field); // EXPECT_THROW(base_field.cast<psim::Integer>(), std::runtime_error); // ^ throws a state assertion error } } } TEST(StateField, TestGet) { psim::StateFieldValued<psim::Real> field("default", 2.0); // Test for `StateFieldBase` { psim::StateFieldBase &base_field = field; ASSERT_EQ(base_field.template get<psim::Real>(), 2.0); EXPECT_THROW(base_field.template get<psim::Integer>(), std::runtime_error); } // Test for `StateFieldBase const` { psim::StateFieldBase const &base_field = field; ASSERT_EQ(base_field.template get<psim::Real>(), 2.0); EXPECT_THROW(base_field.template get<psim::Integer>(), std::runtime_error); } // Test for `StateField` { psim::StateField<psim::Real> &base_field = field; ASSERT_EQ(base_field.template get<psim::Real>(), 2.0); // EXPECT_THROW(base_field.get<psim::Integer>(), std::runtime_error); // ^ throws a static assertion error } // Test for `StateField const` { psim::StateField<psim::Real> const &base_field = field; ASSERT_EQ(base_field.template get<psim::Real>(), 2.0); // EXPECT_THROW(base_field.get<psim::Integer>(), std::runtime_error); // ^ throws a static assertion error } } TEST(StateField, TestGetWritable) { // Test for non-writable state fields { psim::StateFieldLazy<psim::Real> field( "default", []() { return psim::Real(); }); // Test for `StateFieldBase` { psim::StateFieldBase &base_field = field; EXPECT_THROW( base_field.template get_writable<psim::Real>(), std::runtime_error); } // Test for `StateField` { psim::StateField<psim::Real> &base_field = field; EXPECT_THROW( base_field.template get_writable<psim::Real>(), std::runtime_error); } } // Test for writable state fields { psim::StateFieldValued<psim::Real> field("default", 2.0); // Test for `StateFieldBase` { psim::StateFieldBase &base_field = field; ASSERT_EQ(base_field.template get_writable<psim::Real>(), 2.0); EXPECT_THROW(base_field.template get_writable<psim::Integer>(), std::runtime_error); } // Test for `StateField` { psim::StateField<psim::Real> &base_field = field; ASSERT_EQ(base_field.template get_writable<psim::Real>(), 2.0); // EXPECT_THROW(base_field.get_writable<psim::Integer>(), // std::runtime_error); // ^ throws a static assertion error } } }
27.359447
80
0.644096
kylekrol
48ddb84cca2894ad7aecd0a9483cae2a49f8e7c8
422
cpp
C++
999_Practice_Set_2/Day_004/041_decimal_to_binary.cpp
Gandham-Srinithya/Data-Structure-and-Algorithms
177d03105188c83a157947ca9870bf8037e92528
[ "MIT" ]
126
2019-12-22T17:49:08.000Z
2021-12-14T18:45:51.000Z
999_Practice_Set_2/Day_004/041_decimal_to_binary.cpp
Gandham-Srinithya/Data-Structure-and-Algorithms
177d03105188c83a157947ca9870bf8037e92528
[ "MIT" ]
7
2019-12-25T18:03:41.000Z
2021-02-20T06:25:27.000Z
999_Practice_Set_2/Day_004/041_decimal_to_binary.cpp
Gandham-Srinithya/Data-Structure-and-Algorithms
177d03105188c83a157947ca9870bf8037e92528
[ "MIT" ]
54
2019-12-26T06:28:39.000Z
2022-02-01T05:04:43.000Z
#include <iostream> using namespace std; int decimalToBinary(int decimal) { int x = 1; int binary=0; while(x <= decimal) { x*=2; } x/=2; while(x>0) { int last = decimal/x; decimal-=last*x; x/=2; binary*=10; binary+=last; } return binary; } int main() { int n; cin>>n; cout<<decimalToBinary(n)<<endl; return 0; }
12.057143
35
0.483412
Gandham-Srinithya
48e402a279e54f54ab56e5d057de0f3300f6cece
9,435
cpp
C++
src/project/SEProjectProj.cpp
ysbing/voo
329d6a72ede6dd5903ca4d824bb3c49a5502f5c3
[ "Apache-2.0" ]
56
2022-01-29T04:52:27.000Z
2022-03-31T06:52:15.000Z
src/project/SEProjectProj.cpp
jumpingfrog0/VOO
af191ece986f997cf98f85016aa7288c323210c3
[ "Apache-2.0" ]
null
null
null
src/project/SEProjectProj.cpp
jumpingfrog0/VOO
af191ece986f997cf98f85016aa7288c323210c3
[ "Apache-2.0" ]
16
2022-01-29T04:52:39.000Z
2022-03-31T07:48:53.000Z
#include "SEProjectProj.h" #include <QDebug> #include <QDir> #include <QFile> #include <QFileInfo> #include <QJsonDocument> #include <QJsonObject> #include <QTextStream> #include <QTimer> #include <QUrl> #include <QUuid> #include <QtGlobal> #include "SEProject.h" #include "base/http/SEHttpClient.h" #include "base/utils/AppConstance.h" #include "src/base/utils/fileutils.h" #include "user/Login.h" ProjType SEProjectProj::projTypeWithString(QString c) { if (c.toLower() == "timeline") { return Timeline; } else if (c.toLower() == "effect") { return Effect; } else if (c.toLower() == "file") { return File; } else { return UnKnow; } } QString SEProjectProj::stringWithProjType(ProjType projType) { switch (projType) { case Timeline: return "Timeline"; case Effect: return "Effect"; case File: return "File"; default: return ""; } } QString SEProjectProj::id() const { return m_id; } QString SEProjectProj::title() const { return m_title; } QString SEProjectProj::remoteId() const { return m_remoteId; } QString SEProjectProj::version() const { return m_version; } QString SEProjectProj::anchor() const { return m_anchor; } QString SEProjectProj::summary() const { return m_summary; } ProjType SEProjectProj::type() const { return m_type; } QString SEProjectProj::thumb() const { return FileUtils::getFileAbsolutePath(m_rootPath, m_thumb); } QString SEProjectProj::inputList() const { return FileUtils::getFileAbsolutePath(m_rootPath, m_inputList); } QString SEProjectProj::inputConfig() const { return m_inputConfig; } QDateTime SEProjectProj::createTimestamp() const { return m_createTimestamp; } QDateTime SEProjectProj::lastChangedTimestamp() const { return m_lastChangedTimestamp; } QString SEProjectProj::projectDir() const { return m_rootPath; } bool SEProjectProj::isDebug() const { return m_isDebug; } bool SEProjectProj::isTemp() const { return m_isTemp; } void SEProjectProj::setTitle(QString title) { m_title = title; } void SEProjectProj::updateCreateTimestamp() { m_createTimestamp = QDateTime::currentDateTime(); } void SEProjectProj::setAnchor(QString s) { m_anchor = s; } void SEProjectProj::setSummary(QString s) { m_summary = s; } void SEProjectProj::setType(ProjType t) { m_type = t; } void SEProjectProj::setThumb(QString s) { m_thumb = s; } void SEProjectProj::setFile(QString filePath) { QFileInfo info(filePath); switch (m_type) { case Timeline: m_skyFile = "bundle://" + info.fileName(); break; case Effect: m_ofFile = "bundle://" + info.fileName(); break; case File: default: m_resFile = "bundle://" + info.fileName(); break; } } void SEProjectProj::setRemoteId(QString remoteId) { m_remoteId = remoteId; } QString SEProjectProj::entryFile() { switch (m_type) { case Timeline: return FileUtils::realPath(m_rootPath, m_skyFile); case Effect: return FileUtils::realPath(m_rootPath, m_ofFile); case File: default: return FileUtils::realPath(m_rootPath, m_resFile); } } SEProjectProj::SEProjectProj(QString projectFile) { QFileInfo projFile(projectFile); m_rootPath = projFile.absolutePath(); QDir dir(m_rootPath); if (!dir.exists()) { qInfo("open root_dir fail, not found!"); return; } if (projFile.exists()) { QString context = FileUtils::readJson(projFile.filePath()); qDebug() << "projFile json : " << context; auto jsonObject = QJsonDocument::fromJson(context.toUtf8()).object(); m_id = jsonObject.value("id").toString(); m_title = jsonObject.value("title").toString().replace(":", ""); m_remoteId = jsonObject.value("remoteId").toString(); m_version = jsonObject.value("version").toString(); m_anchor = jsonObject.value("anchor").toString(); m_summary = jsonObject.value("summary").toString(); QString t = jsonObject.value("type").toString(); m_type = projTypeWithString(t); m_thumb = jsonObject.value("thumb").toString(); if (m_thumb.isEmpty()) { m_thumb = "cover.jpg"; } m_inputList = jsonObject.value("inputList").toString(); if (m_inputList.isEmpty()) { m_inputList = "inputList.conf"; } m_skyFile = jsonObject.value("skyFile").toString(); if (m_skyFile.isEmpty()) { m_skyFile = "timeline.sky"; } m_ofFile = jsonObject.value("ofFile").toString(); m_resFile = jsonObject.value("resFile").toString(); m_inputConfig = jsonObject.value("inputConfig").toString(); m_createTimestamp = QDateTime::fromTime_t(jsonObject.value("createTimestamp").toDouble()); m_lastChangedTimestamp = QDateTime::fromTime_t(jsonObject.value("lastChangedTimestamp").toDouble()); m_isDebug = jsonObject.value("isDebug").toBool(); m_extraData = jsonObject.value("extra").toObject(); } else { qDebug("SEProjectProj init"); QUuid IID_MyInterface(0x67c8770b, 0x44f1, 0x410a, 0xab, 0x9a, 0xf9, 0xb5, 0x44, 0x6f, 0x13, 0xee); m_id = IID_MyInterface.toString(); m_title = dir.dirName(); m_remoteId = ""; m_version = AppConstance::appVer(); m_anchor = "unknow"; m_summary = ""; m_type = Timeline; m_thumb = "cover.jpg"; m_inputList = "inputList.conf"; m_skyFile = "timeline.sky"; m_ofFile = ""; m_resFile = ""; m_inputConfig = ""; m_createTimestamp = QDateTime::currentDateTime(); m_lastChangedTimestamp = m_createTimestamp; m_isDebug = true; m_isTemp = true; } } QString SEProjectProj::projFilePath(QString root_dir) { QString oldProjFile = findProjectFile(root_dir); if (oldProjFile.length() > 10) { return oldProjFile; } else { return QFileInfo(root_dir, QString("template.") + PROJ_SUFFIX).filePath(); } } QString SEProjectProj::findProjectFile(QString root_dir) { QDir dir(root_dir); if (!dir.exists()) { qInfo("open root_dir fail, not found!"); return ""; } dir.setFilter(QDir::Files); QFileInfoList list = dir.entryInfoList(); if (list.count() == 0) { return ""; } int i = 0; QFileInfo projFile; bool finded = false; do { QFileInfo fileInfo = list.at(i); if (fileInfo.suffix() == PROJ_SUFFIX) { projFile = fileInfo; finded = true; break; } i++; } while (i < list.size()); if (!finded) { return ""; } return QDir::toNativeSeparators(projFile.absoluteFilePath()); } void SEProjectProj::createFile(QString projectFile) { SEProjectProj newProjFile(projectFile); QFileInfo file(projectFile); if (file.exists()) { QFile::remove(projectFile); } // create empty file newProjFile.realSave(file.absoluteDir().absolutePath()); } void SEProjectProj::save(QString root_dir) { if (!SEProject::isQuit() && m_type == Timeline) { QImage image = SEProject::current()->dom()->previewController()->getSkyTimelineView()->snapFrame(); qDebug() << "SEProjectProj::snapFrame " << &image; if (!image.isNull()) { QString imagePath = thumb(); if (QFile::exists(imagePath)) { QFile::remove(imagePath); } image.save(imagePath, "JPG"); } } this->realSave(root_dir); } void SEProjectProj::realSave(QString root_dir) { QString prjFilePath = projFilePath(root_dir); QFile file(prjFilePath); m_lastChangedTimestamp = QDateTime::currentDateTime(); if (file.open(QIODevice::WriteOnly)) { QJsonObject root; root.insert("id", m_id); root.insert("title", m_title); root.insert("remoteId", m_remoteId); root.insert("version", m_version); root.insert("anchor", m_anchor); root.insert("summary", m_summary); root.insert("type", stringWithProjType(m_type)); root.insert("thumb", m_thumb); root.insert("inputList", m_inputList); root.insert("skyFile", m_skyFile); root.insert("ofFile", m_ofFile); root.insert("resFile", m_resFile); root.insert("inputConfig", m_inputConfig); root.insert("createTimestamp", QString::number(m_createTimestamp.toTime_t())); root.insert("lastChangedTimestamp", QString::number(m_lastChangedTimestamp.toTime_t())); root.insert("isDebug", QString::number(m_isDebug)); root.insert("extra", m_extraData); QJsonDocument doc(root); QByteArray jsonData = doc.toJson(QJsonDocument::Compact); file.write(jsonData); file.close(); } else { qInfo("SEProjectProj updateFile fail! File: %s", file.fileName().toStdString().c_str()); } } QJsonValue SEProjectProj::getExtraData(const QString &key) const { return m_extraData.value(key); } void SEProjectProj::setExtraData(const QString &key, const QJsonValue &value) { m_extraData.insert(key, value); } void SEProjectProj::setIsTemp(bool isTemp) { m_isTemp = isTemp; }
30.047771
108
0.630207
ysbing
48e7e68b78f7409dcf2aa8a0d06ed1180f1852ab
3,575
cc
C++
inet/src/inet/networklayer/common/L3Tools.cc
ntanetani/quisp
003f85746266d2eb62c66883e5b965b654672c70
[ "BSD-3-Clause" ]
null
null
null
inet/src/inet/networklayer/common/L3Tools.cc
ntanetani/quisp
003f85746266d2eb62c66883e5b965b654672c70
[ "BSD-3-Clause" ]
null
null
null
inet/src/inet/networklayer/common/L3Tools.cc
ntanetani/quisp
003f85746266d2eb62c66883e5b965b654672c70
[ "BSD-3-Clause" ]
1
2021-07-02T13:32:40.000Z
2021-07-02T13:32:40.000Z
// // Copyright (C) 2017 OpenSim Ltd. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. // #include "inet/networklayer/common/L3Tools.h" #ifdef WITH_IPv4 #include "inet/networklayer/ipv4/Ipv4Header_m.h" #endif #ifdef WITH_IPv6 #include "inet/networklayer/ipv6/Ipv6Header.h" #endif #ifdef WITH_NEXTHOP #include "inet/networklayer/nexthop/NextHopForwardingHeader_m.h" #endif namespace inet { const Protocol *findNetworkProtocol(Packet *packet) { auto networkProtocolInd = packet->findTag<NetworkProtocolInd>(); return networkProtocolInd == nullptr ? nullptr : networkProtocolInd->getProtocol(); } const Protocol& getNetworkProtocol(Packet *packet) { auto protocol = findNetworkProtocol(packet); if (protocol == nullptr) throw cRuntimeError("Network protocol not found"); else return *protocol; } const Ptr<const NetworkHeaderBase> findNetworkProtocolHeader(Packet *packet) { auto networkProtocolInd = packet->findTag<NetworkProtocolInd>(); return networkProtocolInd == nullptr ? nullptr : dynamicPtrCast<const NetworkHeaderBase>(networkProtocolInd->getNetworkProtocolHeader()); } const Ptr<const NetworkHeaderBase> getNetworkProtocolHeader(Packet *packet) { const auto& header = findNetworkProtocolHeader(packet); if (header == nullptr) throw cRuntimeError("Network protocol header not found"); else return header; } const Ptr<const NetworkHeaderBase> peekNetworkProtocolHeader(const Packet *packet, const Protocol& protocol) { #ifdef WITH_IPv4 if (protocol == Protocol::ipv4) return packet->peekAtFront<Ipv4Header>(); #endif #ifdef WITH_IPv6 if (protocol == Protocol::ipv6) return packet->peekAtFront<Ipv6Header>(); #endif #ifdef WITH_NEXTHOP if (protocol == Protocol::nextHopForwarding) return packet->peekAtFront<NextHopForwardingHeader>(); #endif // TODO: add other L3 protocols throw cRuntimeError("Unknown protocol: %s", protocol.getName()); } void insertNetworkProtocolHeader(Packet *packet, const Protocol& protocol, const Ptr<NetworkHeaderBase>& header) { auto networkProtocolInd = packet->addTagIfAbsent<NetworkProtocolInd>(); networkProtocolInd->setProtocol(&protocol); networkProtocolInd->setNetworkProtocolHeader(header); insertProtocolHeader(packet, protocol, header); } const Ptr<NetworkHeaderBase> removeNetworkProtocolHeader(Packet *packet, const Protocol& protocol) { #ifdef WITH_IPv4 if (protocol == Protocol::ipv4) return removeNetworkProtocolHeader<Ipv4Header>(packet); #endif #ifdef WITH_IPv6 if (protocol == Protocol::ipv6) return removeNetworkProtocolHeader<Ipv6Header>(packet); #endif #ifdef WITH_NEXTHOP if (protocol == Protocol::nextHopForwarding) return removeNetworkProtocolHeader<NextHopForwardingHeader>(packet); #endif // TODO: add other L3 protocols throw cRuntimeError("Unknown protocol: %s", protocol.getName()); } } // namespace inet
33.101852
141
0.75049
ntanetani
48ea917edb1ea6085842e06dcf134ff0055369a5
3,951
cpp
C++
src/Audio.cpp
noloitering/NoSFX
0ed636db4c403c7cb8a6ffb1714db2b46d105329
[ "Zlib" ]
null
null
null
src/Audio.cpp
noloitering/NoSFX
0ed636db4c403c7cb8a6ffb1714db2b46d105329
[ "Zlib" ]
null
null
null
src/Audio.cpp
noloitering/NoSFX
0ed636db4c403c7cb8a6ffb1714db2b46d105329
[ "Zlib" ]
null
null
null
#include "Audio.h" using namespace NoSFX; AudioManager::AudioManager(std::shared_ptr< Music > music, float vol, float pitch, bool play) { InitAudioDevice(); if ( vol >= 1 ) { volume.master = 1; } else if ( vol > 0 ) { volume.master = vol; } else { volume.master = 0; } SetMasterVolume(volume.master); if ( music ) { SetMusicPitch(*(music), pitch); track = music; if ( play ) { PlayMusicStream(*(track)); } } } AudioManager::AudioManager(std::shared_ptr< Music > music, const Volume& vol, const Pitch& pitch, bool play) { InitAudioDevice(); SetMasterVolume(vol.master); volume = vol; pitches = pitch; if ( music ) { track = music; SetMusicPitch(*(track), pitch.music); SetMusicVolume(*(track), vol.music); if ( play ) { PlayMusicStream(*(track)); } } } void AudioManager::update() { if ( track ) { UpdateMusicStream(*(track)); float timePlayed = GetMusicTimePlayed(*(track))/GetMusicTimeLength(*(track)); if ( timePlayed > 1 ) { StopMusicStream(*(track)); } } } void AudioManager::play(std::shared_ptr< Sound > sound) { SetSoundVolume(*(sound), volume.sfx); SetSoundPitch(*(sound), pitches.sfx); PlaySoundMulti(*(sound)); } void AudioManager::play(std::shared_ptr< Sound > sound, float vol, float pitch) { SetSoundVolume(*(sound), vol); SetSoundPitch(*(sound), pitch); PlaySoundMulti(*(sound)); } void AudioManager::stream(std::shared_ptr< Music > music, bool loop) { music->looping = loop; SetMusicVolume(*(music), volume.music); SetMusicPitch(*(music), pitches.music); track = music; PlayMusicStream(*(music)); } void AudioManager::stream(std::shared_ptr< Music > music, float vol, float pitch, bool loop) { music->looping = loop; SetMusicVolume(*(music), vol); SetMusicPitch(*(music), pitch); track = music; PlayMusicStream(*(music)); } void AudioManager::adjustVolume(const Volume& vol) { volume = vol; SetMasterVolume(volume.master); if ( track ) { SetMusicVolume(*(track), volume.music); } } void AudioManager::adjustPitch(const Pitch& pitch) { pitches = pitch; if ( track ) { SetMusicVolume(*(track), pitches.music); } } void AudioManager::adjustTrackVolume(float vol) { if ( vol >= 1 ) { vol = 1; } else if ( vol < 0 ) { vol = 0; } if ( track ) { SetMusicVolume(*(track), vol); } } void AudioManager::adjustMusicVolume(float vol) { if ( vol >= 1 ) { vol = 1; } else if ( vol < 0 ) { vol = 0; } volume.music = vol; if ( track ) { SetMusicVolume(*(track), volume.music); } } void AudioManager::adjustSFXVolume(float vol) { if ( vol >= 1 ) { vol = 1; } else if ( vol < 0 ) { vol = 0; } volume.sfx = vol; } void AudioManager::adjustSoundVolume(std::shared_ptr< Sound > sound, float vol) { SetSoundVolume(*(sound), vol); } void AudioManager::adjustMaster(float vol) { if ( vol >= 1 ) { vol = 1; } else if ( vol < 0 ) { vol = 0; } volume.master = vol; SetMasterVolume(volume.master); } void AudioManager::adjustTrackPitch(float pitch) { if ( track ) { SetMusicPitch(*(track), pitch); } } void AudioManager::adjustMusicPitch(float pitch) { pitches.music = pitch; adjustTrackPitch(pitch); } void AudioManager::adjustSFXPitch(float pitch) { pitches.sfx = pitch; } void AudioManager::adjustSoundPitch(std::shared_ptr< Sound > sound, float pitch) { SetSoundPitch(*(sound), pitch); } void AudioManager::pauseTrack() { PauseMusicStream(*(track)); } void AudioManager::resumeTrack() { if ( trackPlayed() >= 1 ) { ResumeMusicStream(*(track)); } else { PlayMusicStream(*(track)); } } void AudioManager::stopTrack() { StopMusicStream(*(track)); } void AudioManager::seekTrack(float pos) { SeekMusicStream(*(track), pos); } bool AudioManager::trackPlaying() { return IsMusicStreamPlaying(*(track)); } float AudioManager::trackLength() { return GetMusicTimeLength(*(track)); } float AudioManager::trackPlayed() { return GetMusicTimePlayed(*(track)); }
16.060976
108
0.660086
noloitering
48f0b52da3268d26c99b9e6a2e3b98518b135c5e
428
cpp
C++
DearPyGui/src/core/PythonUtilities/mvPythonExceptions.cpp
iqxd/DearPyGui
ad6209cb9b7e2a6466a49ce71a438d1d349f0374
[ "MIT" ]
null
null
null
DearPyGui/src/core/PythonUtilities/mvPythonExceptions.cpp
iqxd/DearPyGui
ad6209cb9b7e2a6466a49ce71a438d1d349f0374
[ "MIT" ]
null
null
null
DearPyGui/src/core/PythonUtilities/mvPythonExceptions.cpp
iqxd/DearPyGui
ad6209cb9b7e2a6466a49ce71a438d1d349f0374
[ "MIT" ]
null
null
null
#define PY_SSIZE_T_CLEAN #include <Python.h> #include <frameobject.h> #include <string> #include "mvPythonTranslator.h" #include "mvGlobalIntepreterLock.h" namespace Marvel { void ThrowPythonException(const std::string& message) { std::string fullMessage = "Line: %d \t" + message; int line = PyFrame_GetLineNumber(PyEval_GetFrame()); PyErr_Format(PyExc_Exception, fullMessage.c_str(), line); PyErr_Print(); } }
19.454545
59
0.742991
iqxd
f70b496324744403c23597e19012e584c08a599b
667
cpp
C++
parser/src/Simp.cpp
AnZhuoKaiFaZhe/ctl2snf
935574f871e05068c9931d2444cfd50759fae0bc
[ "MIT" ]
null
null
null
parser/src/Simp.cpp
AnZhuoKaiFaZhe/ctl2snf
935574f871e05068c9931d2444cfd50759fae0bc
[ "MIT" ]
null
null
null
parser/src/Simp.cpp
AnZhuoKaiFaZhe/ctl2snf
935574f871e05068c9931d2444cfd50759fae0bc
[ "MIT" ]
null
null
null
// // Created by mzy on 2021-06-03. // #include "Simp.hpp" Tree<ASTNode>* simp(Tree<ASTNode>* n,Tree<ASTNode>* l,Tree<ASTNode>* r){ switch (n->root.type) { case NodeType_t::LogicAnd: if(l->root.type==NodeType_t::True || r->root.type==NodeType_t::False)return r; if(l->root.type==NodeType_t::False || r->root.type==NodeType_t::True)return l; return n; case NodeType_t::LogicOr: if(l->root.type==NodeType_t::True || r->root.type==NodeType_t::False)return l; if(l->root.type==NodeType_t::False || r->root.type==NodeType_t::True)return r; return n; } }
33.35
91
0.574213
AnZhuoKaiFaZhe
f70f523674c5a3c39d45f96b8253a261d75537c6
1,891
cpp
C++
Engine/WindowInspector.cpp
elliotjb/CulverinEngine-Project3
cc386713dd786e2a52cc9b219a0d701a9398f202
[ "MIT" ]
2
2018-01-20T18:17:22.000Z
2018-01-20T18:17:28.000Z
Engine/WindowInspector.cpp
TempName0/TempMotor3D_P3
cc386713dd786e2a52cc9b219a0d701a9398f202
[ "MIT" ]
null
null
null
Engine/WindowInspector.cpp
TempName0/TempMotor3D_P3
cc386713dd786e2a52cc9b219a0d701a9398f202
[ "MIT" ]
1
2018-06-16T16:12:11.000Z
2018-06-16T16:12:11.000Z
#include "Application.h" #include "WindowInspector.h" #include "ModuleWindow.h" #include "GameObject.h" #include "Component.h" Inspector::Inspector() : WindowManager() { active.push_back(Active()); name = "Inspector"; } Inspector::~Inspector() { active.clear(); selected_object = nullptr; } bool Inspector::Start() { return true; } update_status Inspector::Update(float dt) { if (active[0].active) ShowInspector(); return UPDATE_CONTINUE; } void Inspector::ShowInspector() { static int width; static int height; SDL_GetWindowSize(App->window->window, &width, &height); ImGui::SetNextWindowPos(ImVec2(width - 300, 20)); ImGui::SetNextWindowSize(ImVec2(300, height - 20 - (height - 700))); if (!BeginDock("Inspector", NULL, ImGuiWindowFlags_NoScrollbar)) { EndDock(); return; } ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(12, 3)); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 2)); if (selected_object != nullptr) { selected_object->ShowInspectorInfo(); } ImGui::PopStyleVar(2); EndDock(); } void Inspector::LinkObject(GameObject * obj) { if (obj != nullptr) { selected_object = obj; if (selected_object->GetParent() != nullptr) { GameObject* parent_open = selected_object->GetParent(); while (parent_open != nullptr) { parent_open->set_next_tree_node_open = true; parent_open = parent_open->GetParent(); } } } } void Inspector::SetLinkObjectNull() { selected_object = nullptr; } GameObject* Inspector::GetSelected() const { return selected_object; } void Inspector::SetComponentCopy(Component* copy) { if (copy != nullptr) { copied = copy; } } bool Inspector::AnyComponentCopied() { return (copied != nullptr); } void Inspector::SetLinkComponentNull() { copied = nullptr; } Component * Inspector::GetComponentCopied() { return copied; } bool Inspector::CleanUp() { return true; }
17.190909
69
0.707562
elliotjb
f71847bfbead41a06b5b9259c735f6bbc0405553
575
cpp
C++
Codeforces/1038A - Equality.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/1038A - Equality.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/1038A - Equality.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); #ifndef ONLINE_JUDGE freopen("files/input.txt", "r", stdin); freopen("files/output.txt", "w", stdout); #endif int n, k; cin >> n >> k; string s; cin >> s; map<char, int> freq; for (int i = 0; i < k; ++i) freq['A' + i] = 0; for ( auto ch: s ) freq[ch]++; auto min = min_element(freq.begin(), freq.end(), [](auto a, auto b) { return a.second < b.second; }); cout << min->second * k << endl; return 0; }
21.296296
73
0.518261
naimulcsx
f71c1bb2d46372b72552be3a8b8d3cfb43d3a2bc
11,580
cpp
C++
src/model/test/Blind_GTest.cpp
muehleisen/OpenStudio
3bfe89f6c441d1e61e50b8e94e92e7218b4555a0
[ "blessing" ]
354
2015-01-10T17:46:11.000Z
2022-03-29T10:00:00.000Z
src/model/test/Blind_GTest.cpp
muehleisen/OpenStudio
3bfe89f6c441d1e61e50b8e94e92e7218b4555a0
[ "blessing" ]
3,243
2015-01-02T04:54:45.000Z
2022-03-31T17:22:22.000Z
src/model/test/Blind_GTest.cpp
jmarrec/OpenStudio
5276feff0d8dbd6c8ef4e87eed626bc270a19b14
[ "blessing" ]
157
2015-01-07T15:59:55.000Z
2022-03-30T07:46:09.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ #include <gtest/gtest.h> #include "ModelFixture.hpp" #include "../Blind.hpp" #include "../Blind_Impl.hpp" using namespace openstudio; using namespace openstudio::model; TEST_F(ModelFixture, Blind_GettersSetters) { Model m; Blind blind(m); // Slat Orientation: String // Check Idd default: "Horizontal" EXPECT_EQ("Horizontal", blind.slatOrientation()); // Test a valid choice EXPECT_TRUE(blind.setSlatOrientation("Vertical")); EXPECT_EQ("Vertical", blind.slatOrientation()); // Test an invalid choice EXPECT_FALSE(blind.setSlatOrientation("BadChoice")); EXPECT_EQ("Vertical", blind.slatOrientation()); // Slat Width: Double // Check Idd default: 0.025 EXPECT_EQ(0.025, blind.slatWidth()); EXPECT_TRUE(blind.setSlatWidth(0.01)); EXPECT_EQ(0.01, blind.slatWidth()); // Slat Separation: Double // Check Idd default: 0.01875 EXPECT_EQ(0.01875, blind.slatSeparation()); EXPECT_TRUE(blind.setSlatSeparation(0.01)); EXPECT_EQ(0.01, blind.slatSeparation()); // Slat Thickness: Double // Check Idd default: 0.001 EXPECT_EQ(0.001, blind.slatThickness()); EXPECT_TRUE(blind.setSlatThickness(0.021)); EXPECT_EQ(0.021, blind.slatThickness()); blind.resetSlatThickness(); EXPECT_EQ(0.001, blind.slatThickness()); // Slat Angle: Double // Check Idd default: 45 EXPECT_EQ(45, blind.slatAngle()); EXPECT_TRUE(blind.setSlatAngle(22.5)); EXPECT_EQ(22.5, blind.slatAngle()); blind.resetSlatAngle(); EXPECT_EQ(45, blind.slatAngle()); // Slat Conductivity: Double // Check Idd default: 221.0 EXPECT_EQ(221.0, blind.slatConductivity()); EXPECT_TRUE(blind.setSlatConductivity(110.5)); EXPECT_EQ(110.5, blind.slatConductivity()); blind.resetSlatConductivity(); EXPECT_EQ(221.0, blind.slatConductivity()); // Slat Beam Solar Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatBeamSolarTransmittance()); EXPECT_TRUE(blind.setSlatBeamSolarTransmittance(0.35)); EXPECT_EQ(0.35, blind.slatBeamSolarTransmittance()); blind.resetSlatBeamSolarTransmittance(); EXPECT_EQ(0.0, blind.slatBeamSolarTransmittance()); // Front Side Slat Beam Solar Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.frontSideSlatBeamSolarReflectance()); EXPECT_TRUE(blind.setFrontSideSlatBeamSolarReflectance(0.205)); EXPECT_EQ(0.205, blind.frontSideSlatBeamSolarReflectance()); // Back Side Slat Beam Solar Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.backSideSlatBeamSolarReflectance()); EXPECT_TRUE(blind.setBackSideSlatBeamSolarReflectance(0.105)); EXPECT_EQ(0.105, blind.backSideSlatBeamSolarReflectance()); // Slat Diffuse Solar Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatDiffuseSolarTransmittance()); EXPECT_TRUE(blind.setSlatDiffuseSolarTransmittance(0.31)); EXPECT_EQ(0.31, blind.slatDiffuseSolarTransmittance()); // Front Side Slat Diffuse Solar Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.frontSideSlatDiffuseSolarReflectance()); EXPECT_TRUE(blind.setFrontSideSlatDiffuseSolarReflectance(0.225)); EXPECT_EQ(0.225, blind.frontSideSlatDiffuseSolarReflectance()); // Back Side Slat Diffuse Solar Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.backSideSlatDiffuseSolarReflectance()); EXPECT_TRUE(blind.setBackSideSlatDiffuseSolarReflectance(0.336)); EXPECT_EQ(0.336, blind.backSideSlatDiffuseSolarReflectance()); // Slat Beam Visible Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatBeamVisibleTransmittance()); EXPECT_TRUE(blind.setSlatBeamVisibleTransmittance(0.112)); EXPECT_EQ(0.112, blind.slatBeamVisibleTransmittance()); // Front Side Slat Beam Visible Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.frontSideSlatBeamVisibleReflectance()); EXPECT_TRUE(blind.setFrontSideSlatBeamVisibleReflectance(0.145)); EXPECT_EQ(0.145, blind.frontSideSlatBeamVisibleReflectance()); blind.resetFrontSideSlatBeamVisibleReflectance(); EXPECT_EQ(0.5, blind.frontSideSlatBeamVisibleReflectance()); // Back Side Slat Beam Visible Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.backSideSlatBeamVisibleReflectance()); EXPECT_TRUE(blind.setBackSideSlatBeamVisibleReflectance(0.185)); EXPECT_EQ(0.185, blind.backSideSlatBeamVisibleReflectance()); blind.resetBackSideSlatBeamVisibleReflectance(); EXPECT_EQ(0.5, blind.backSideSlatBeamVisibleReflectance()); // Slat Diffuse Visible Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatDiffuseVisibleTransmittance()); EXPECT_TRUE(blind.setSlatDiffuseVisibleTransmittance(0.015)); EXPECT_EQ(0.015, blind.slatDiffuseVisibleTransmittance()); blind.resetSlatDiffuseVisibleTransmittance(); EXPECT_EQ(0.0, blind.slatDiffuseVisibleTransmittance()); // Front Side Slat Diffuse Visible Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.frontSideSlatDiffuseVisibleReflectance()); EXPECT_TRUE(blind.setFrontSideSlatDiffuseVisibleReflectance(0.055)); EXPECT_EQ(0.055, blind.frontSideSlatDiffuseVisibleReflectance()); blind.resetFrontSideSlatDiffuseVisibleReflectance(); EXPECT_EQ(0.5, blind.frontSideSlatDiffuseVisibleReflectance()); // Back Side Slat Diffuse Visible Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.backSideSlatDiffuseVisibleReflectance()); EXPECT_TRUE(blind.setBackSideSlatDiffuseVisibleReflectance(0.085)); EXPECT_EQ(0.085, blind.backSideSlatDiffuseVisibleReflectance()); blind.resetBackSideSlatDiffuseVisibleReflectance(); EXPECT_EQ(0.5, blind.backSideSlatDiffuseVisibleReflectance()); // Slat Infrared Hemispherical Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatInfraredHemisphericalTransmittance()); EXPECT_TRUE(blind.setSlatInfraredHemisphericalTransmittance(0.095)); EXPECT_EQ(0.095, blind.slatInfraredHemisphericalTransmittance()); blind.resetSlatInfraredHemisphericalTransmittance(); EXPECT_EQ(0.0, blind.slatInfraredHemisphericalTransmittance()); // Front Side Slat Infrared Hemispherical Emissivity: Double // Check Idd default: 0.9 EXPECT_EQ(0.9, blind.frontSideSlatInfraredHemisphericalEmissivity()); EXPECT_TRUE(blind.setFrontSideSlatInfraredHemisphericalEmissivity(0.451)); EXPECT_EQ(0.451, blind.frontSideSlatInfraredHemisphericalEmissivity()); blind.resetFrontSideSlatInfraredHemisphericalEmissivity(); EXPECT_EQ(0.9, blind.frontSideSlatInfraredHemisphericalEmissivity()); // Back Side Slat Infrared Hemispherical Emissivity: Double // Check Idd default: 0.9 EXPECT_EQ(0.9, blind.backSideSlatInfraredHemisphericalEmissivity()); EXPECT_TRUE(blind.setBackSideSlatInfraredHemisphericalEmissivity(0.455)); EXPECT_EQ(0.455, blind.backSideSlatInfraredHemisphericalEmissivity()); blind.resetBackSideSlatInfraredHemisphericalEmissivity(); EXPECT_EQ(0.9, blind.backSideSlatInfraredHemisphericalEmissivity()); // Blind to Glass Distance: Double // Check Idd default: 0.050 EXPECT_EQ(0.050, blind.blindtoGlassDistance()); EXPECT_TRUE(blind.setBlindtoGlassDistance(0.033)); EXPECT_EQ(0.033, blind.blindtoGlassDistance()); blind.resetBlindtoGlassDistance(); EXPECT_EQ(0.050, blind.blindtoGlassDistance()); // Blind Top Opening Multiplier: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.blindTopOpeningMultiplier()); EXPECT_TRUE(blind.setBlindTopOpeningMultiplier(0.259)); EXPECT_EQ(0.259, blind.blindTopOpeningMultiplier()); blind.resetBlindTopOpeningMultiplier(); EXPECT_EQ(0.5, blind.blindTopOpeningMultiplier()); // Blind Bottom Opening Multiplier: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.blindBottomOpeningMultiplier()); EXPECT_TRUE(blind.setBlindBottomOpeningMultiplier(0.278)); EXPECT_EQ(0.278, blind.blindBottomOpeningMultiplier()); blind.resetBlindBottomOpeningMultiplier(); EXPECT_EQ(0.5, blind.blindBottomOpeningMultiplier()); // Blind Left Side Opening Multiplier: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.blindLeftSideOpeningMultiplier()); EXPECT_TRUE(blind.setBlindLeftSideOpeningMultiplier(0.324)); EXPECT_EQ(0.324, blind.blindLeftSideOpeningMultiplier()); blind.resetBlindLeftSideOpeningMultiplier(); EXPECT_EQ(0.5, blind.blindLeftSideOpeningMultiplier()); // Blind Right Side Opening Multiplier: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.blindRightSideOpeningMultiplier()); EXPECT_TRUE(blind.setBlindRightSideOpeningMultiplier(0.165)); EXPECT_EQ(0.165, blind.blindRightSideOpeningMultiplier()); blind.resetBlindRightSideOpeningMultiplier(); EXPECT_EQ(0.5, blind.blindRightSideOpeningMultiplier()); // Minimum Slat Angle: Double // Check Idd default: 0 EXPECT_EQ(0, blind.minimumSlatAngle()); EXPECT_TRUE(blind.setMinimumSlatAngle(13.0)); EXPECT_EQ(13.0, blind.minimumSlatAngle()); blind.resetMinimumSlatAngle(); EXPECT_EQ(0, blind.minimumSlatAngle()); // Maximum Slat Angle: Double // Check Idd default: 180 EXPECT_EQ(180, blind.maximumSlatAngle()); EXPECT_TRUE(blind.setMaximumSlatAngle(74.0)); EXPECT_EQ(74.0, blind.maximumSlatAngle()); blind.resetMaximumSlatAngle(); EXPECT_EQ(180, blind.maximumSlatAngle()); }
45.411765
125
0.75924
muehleisen
f72726336c53431cac227d0e2884a824c6cddd5f
344
cpp
C++
libraries/glua/glua_api_types.cpp
tiaotiao00/HSR00qianbao
a88afebeb98e786389f369447bcf9c3a2a352cfa
[ "MIT" ]
66
2017-09-29T07:09:59.000Z
2020-01-12T06:45:08.000Z
libraries/glua/glua_api_types.cpp
tiaotiao00/HSR00qianbao
a88afebeb98e786389f369447bcf9c3a2a352cfa
[ "MIT" ]
5
2017-12-13T13:12:05.000Z
2018-01-18T10:34:02.000Z
libraries/glua/glua_api_types.cpp
tiaotiao00/HSR00qianbao
a88afebeb98e786389f369447bcf9c3a2a352cfa
[ "MIT" ]
11
2017-12-05T07:02:05.000Z
2018-01-28T02:52:50.000Z
#include <glua/glua_api_types.h> #include <glua/hsrcore_lua_api.h> GluaModuleByteStream::GluaModuleByteStream() { is_bytes = false; contract_level = CONTRACT_LEVEL_TEMP; contract_state = CONTRACT_STATE_VALID; } GluaModuleByteStream::~GluaModuleByteStream() { contract_apis.clear(); offline_apis.clear(); contract_emit_events.clear(); }
20.235294
45
0.793605
tiaotiao00
f729b82eed46a2762653e8db87479c1ff28d01fe
30,395
cpp
C++
src/MuiTextArea.cpp
kritzikratzi/ofxMightyUI
63eaa7fcc8739e019f27500f68c4129a18be5434
[ "MIT" ]
52
2015-02-19T21:22:19.000Z
2022-01-24T07:59:07.000Z
src/MuiTextArea.cpp
kritzikratzi/ofxMightyUI
63eaa7fcc8739e019f27500f68c4129a18be5434
[ "MIT" ]
5
2016-05-22T16:39:57.000Z
2020-09-19T20:29:20.000Z
src/MuiTextArea.cpp
kritzikratzi/ofxMightyUI
63eaa7fcc8739e019f27500f68c4129a18be5434
[ "MIT" ]
14
2015-05-19T10:04:52.000Z
2021-05-12T09:07:22.000Z
/* * TextArea.cpp * * Text TextArea * - Supports vertical and horizontal alignments * - Call commit() after changing text, fontSize, fontName or any of the other variables (except bounds!). * - fg variable affects text color (no commit needed) * - Only support multiline */ #include "MuiTextArea.h" #include "Root.h" #include <regex> #include <GLFW/glfw3.h> // how nasty is this?? mui::TextAreaInternal * internal(mui::TextArea * tf){ return tf->internalData(); } #define STB_TEXTEDIT_STRING mui::TextArea #define STB_TEXTEDIT_CHARTYPE uint32_t #define STB_TEXTEDIT_POSITIONTYPE int //TODO: utf8 support #define STB_TEXTEDIT_STRINGLEN(obj) ((int)internal(obj)->utf32.size()) #define STB_TEXTEDIT_CHARARR_LEN(arr,len) (len) #define STB_TEXTEDIT_LAYOUTROW(r,obj,n) mui::TextAreaInternal::layout_func(r,obj,n) #define STB_TEXTEDIT_GETWIDTH(obj,n,i) mui::TextAreaInternal::layout_width(obj,n,i) #define STB_TEXTEDIT_KEYTOTEXT(key) (((key) & KEYDOWN_BIT) ? 0 : (key)) // this only returns the first byte of a multi byte sequence :( #define STB_TEXTEDIT_GETCHAR(tc,i) (internal(tc)->utf32[i]) #define STB_TEXTEDIT_NEWLINE '\n' #define STB_TEXTEDIT_IS_SPACE(ch) isspace(ch) #define STB_TEXTEDIT_DELETECHARS mui::TextAreaInternal::delete_chars #define STB_TEXTEDIT_INSERTCHARS mui::TextAreaInternal::insert_chars #define KEYDOWN_BIT 0x8000 #define STB_TEXTEDIT_K_SHIFT 0x4000 #define STB_TEXTEDIT_K_CONTROL 0x2000 #define STB_TEXTEDIT_K_LEFT (KEYDOWN_BIT | 1) // actually use VK_LEFT, SDLK_LEFT, etc #define STB_TEXTEDIT_K_RIGHT (KEYDOWN_BIT | 2) // VK_RIGHT #define STB_TEXTEDIT_K_UP (KEYDOWN_BIT | 3) // VK_UP #define STB_TEXTEDIT_K_DOWN (KEYDOWN_BIT | 4) // VK_DOWN #define STB_TEXTEDIT_K_LINESTART (KEYDOWN_BIT | 5) // VK_HOME #define STB_TEXTEDIT_K_LINEEND (KEYDOWN_BIT | 6) // VK_END #define STB_TEXTEDIT_K_TEXTSTART (STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_CONTROL) #define STB_TEXTEDIT_K_TEXTEND (STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_CONTROL) #define STB_TEXTEDIT_K_DELETE (KEYDOWN_BIT | 7) // VK_DELETE #define STB_TEXTEDIT_K_BACKSPACE (KEYDOWN_BIT | 8) // VK_BACKSPACE #define STB_TEXTEDIT_K_UNDO (KEYDOWN_BIT | STB_TEXTEDIT_K_CONTROL | 'z') #define STB_TEXTEDIT_K_REDO (KEYDOWN_BIT | STB_TEXTEDIT_K_CONTROL | 'y') #define STB_TEXTEDIT_K_INSERT (KEYDOWN_BIT | 9) // VK_INSERT #define STB_TEXTEDIT_K_WORDLEFT (STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_CONTROL) #define STB_TEXTEDIT_K_WORDRIGHT (STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_CONTROL) #define STB_TEXTEDIT_K_PGUP (KEYDOWN_BIT | 10) // VK_PGUP -- not implemented #define STB_TEXTEDIT_K_PGDOWN (KEYDOWN_BIT | 11) // VK_PGDOWN -- not implemented #define STB_TEXTEDIT_MOVEWORDLEFT mui::TextAreaInternal::move_to_word_previous #define STB_TEXTEDIT_MOVEWORDRIGHT mui::TextAreaInternal::move_to_word_next #include "../libs/stb_textedit/include/stb_textedit/stb_textedit.h" #pragma mark UTF8-Helpers inline int mui::TextArea::octect_size( uint32_t codepoint ){ if (codepoint < 0x80) // two octets return 1; else if (codepoint < 0x800) // two octets return 2; else if (codepoint < 0x10000) // three octets return 3; else // four octets return 4; } int mui::TextArea::utf8_expected_len( char first ){ switch((unsigned char)first){ case 0xc0: return 2; case 0xe0: return 3; case 0xf0: return 4; default: return 1; } } string mui::TextArea::utf32_to_utf8( uint32_t codepoint ){ if (codepoint < 0x80) // one octet return string({(char)codepoint}); else if (codepoint < 0x800) { // two octets return string({ (char)((codepoint >> 6) | 0xc0), (char)((codepoint & 0x3f) | 0x80) }); } else if (codepoint < 0x10000) { // three octets return string({ (char)((codepoint >> 12) | 0xe0), (char)(((codepoint >> 6) & 0x3f) | 0x80), (char)((codepoint & 0x3f) | 0x80) }); } else { return string({ (char)((codepoint >> 18) | 0xf0), (char)(((codepoint >> 12) & 0x3f) | 0x80), (char)(((codepoint >> 6) & 0x3f) | 0x80), (char)((codepoint & 0x3f) | 0x80) }); } } inline size_t mui::TextArea::utf8_strlen(const string & line ){ size_t i = 0; for( auto c : ofUTF8Iterator(line) ){ ++i; } return i; } inline size_t mui::TextArea::utf8_to_utf32(const string & text, vector<uint32_t> & utf32, vector<size_t> & utf8_positions){ size_t i = 0; size_t pos = 0; utf32.clear(); utf8_positions.clear(); for( auto c : ofUTF8Iterator(text) ){ utf32.push_back(c); utf8_positions.push_back(pos); pos += octect_size(c); ++i; } return i; } inline vector<uint32_t> mui::TextArea::utf8_to_utf32(const string & text){ vector<uint32_t> res; for( auto c : ofUTF8Iterator(text) ){ res.push_back(c); } return res; } // define the functions we need void mui::TextArea::layout_func_impl(void *row_ptr, mui::TextArea *data, int start_i) { StbTexteditRow * row = (StbTexteditRow*)row_ptr; const ofRectangle &boundingBox = data->boundingBox; ofRectangle size = mui::Helpers::alignBox( data, boundingBox.width, boundingBox.height, data->horizontalAlign, data->verticalAlign ); // mui::Helpers::getFontStash().getTextBounds(data->text, data->fontStyle, boundingBox.x, boundingBox.y); // figure out where we currently are int pos = 0; float y = 0; for( int i = 0; i < data->lines.size(); i++){ const StyledLine & line = data->lines[i]; int lineLen = (int)data->utf32_line_length[i]; if( pos >= start_i ){ assert(line.elements.size()>0); row->num_chars = lineLen; row->x0 = size.x + line.elements.front().x; row->x1 = row->x0 + line.lineW; row->baseline_y_delta = 0; //??? row->ymin = size.y + y; row->ymax = size.y + y + line.lineH; return; } pos += lineLen; y += line.lineH; } row->num_chars = 0; row->x0 = size.x; row->x1 = size.x+size.width; row->baseline_y_delta = 0; row->ymin = y; row->ymax = y + 10; } // n: line starts at index n // i: is the char offset within the line // return value: is advance to the next letter (taking kerning and maybe other funny things into account) // i think it is: equivalent to: xpos(n+i+1)-xpos(n+i) float mui::TextArea::layout_width_impl(mui::TextArea * data, int n, int i ){ // if(i==0) return data->find_xpos_right(n); // else return data->find_xpos_right(n+i)-data->find_xpos_right(n+i-1); if(i==0) return data->getEditorCursorForIndex(n+1).rect.x; else return data->getEditorCursorForIndex(n+i+1).rect.x-data->getEditorCursorForIndex(n+i).rect.x; } // pos is the position in utf32 chars int mui::TextArea::delete_chars_impl(mui::TextArea *data, int pos, int num) { if(num==0) return 0; size_t from = data->idx_utf8(pos); size_t to = data->idx_utf8(pos+num); if(from==to) return 0; data->text.erase(data->text.begin()+from, data->text.begin()+to); data->commit(); // do an immediate commit() here? return 1; } // pos is the position in unicode chars // newtext is utf32 encoded! int mui::TextArea::insert_chars_impl(mui::TextArea *data, int pos, const STB_TEXTEDIT_CHARTYPE *newtext, int num){ size_t idx; if(pos==0) idx = 0; else if(pos<data->utf32.size()) idx = data->utf8_positions[pos-1]+octect_size(data->utf32[pos-1]); else idx = data->text.length(); idx = min(data->text.size(), idx); stringstream str; int len = 0; for( int i = 0; i < num; i++){ uint32_t ch = newtext[i]; if(data->onCharacterAdded.notifyRequireAll(ch)){ str << utf32_to_utf8(ch); len ++; } } string text = str.str(); if (data->onInsert) text = data->onInsert(text); data->text.insert(idx, text); data->commit(); return len; // always succeeds } int mui::TextArea::is_word_boundary( STB_TEXTEDIT_STRING *str, int idx ) { return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1; } static bool is_cool_coding_char(STB_TEXTEDIT_CHARTYPE c){ const static char * chars = "[]|{}().!=+-_,;:^&|#"; for(int i = strlen(chars)-1;i>=0; i--){ if((uint32_t)chars[i] == c) return true; } return false; } int mui::TextArea::move_to_word_previous_impl( STB_TEXTEDIT_STRING *str, int c ) { --c; // always move at least one character while( c >= 0 && !is_word_boundary( str, c ) && !is_cool_coding_char(STB_TEXTEDIT_GETCHAR(str,c))) --c; if( c < 0 ) c = 0; return c; } int mui::TextArea::move_to_word_next_impl( STB_TEXTEDIT_STRING *str, int c ) { const int len = STB_TEXTEDIT_STRINGLEN(str); ++c; // always move at least one character while( c < len && !is_word_boundary( str, c ) && !is_cool_coding_char(STB_TEXTEDIT_GETCHAR(str,c))) ++c; if( c > len ) c = len; return c; } #define STB_TEXTEDIT_IMPLEMENTATION #include "../libs/stb_textedit/include/stb_textedit/stb_textedit.h" #undef STB_TEXTEDIT_IMPLEMENTATION // this exists only because it's not possible to forward declare unnamed structs class mui::TextArea::EditorState : public STB_TexteditState{ }; mui::TextArea::TextArea( std::string text_, float x_, float y_, float width_, float height_ ) : mui::ScrollPane( x_, y_, width_, height_ ), text( text_), fontSize(-1), horizontalAlign(Left), verticalAlign(Middle),fontName(""),lastInteraction(0),selectAllOnFocus(false){ editor_view = new mui::TextAreaView(this, 0, 0, width, height); editor_view->cursor = mui::Cursor::IBeam; view->add(editor_view); state = new EditorState(); focusTransferable = false; stb_textedit_initialize_state(state,0); if( fontSize < 0 ) fontSize = mui::MuiConfig::fontSize; commit(); state->cursor = strlenWithLineStarts; }; mui::TextArea::~TextArea(){ editor_view->remove(); delete editor_view; delete state; } // internally redirect those, so that it goes straight into the real textarea and not the scroller bool mui::TextArea::hasFocus(){return editor_view->hasFocus(); } bool mui::TextArea::hasFocus( ofTouchEventArgs &touch ){ return editor_view->hasFocus(touch); }; bool mui::TextArea::requestFocus( ofTouchEventArgs &args ){ return editor_view->requestFocus(args); }; // internally redirect those, so that it goes straight into the real textarea and not the scroller bool mui::TextArea::hasKeyboardFocus(){ return editor_view->hasKeyboardFocus(); }; bool mui::TextArea::requestKeyboardFocus(){ return editor_view->requestKeyboardFocus(); }; //-------------------------------------------------------------- void mui::TextArea::update(){ mui::ScrollPane::update(); fontStyle.fontSize = fontSize; fontStyle.color = fg; fontStyle.fontID = fontName; } const string mui::TextArea::getText(){ return text; } void mui::TextArea::setText( string text ){ state->select_start = 0; state->select_end = strlenWithLineStarts; state->cursor = state->select_end; vector<uint32_t> text_utf32 = utf8_to_utf32(text); stb_textedit_paste(this, state, text_utf32.size()?&text_utf32[0]:nullptr, (int)text_utf32.size()); } void mui::TextArea::setTextAndNotify( string text ){ setText(text); ofNotifyEvent(onChange, text, this); } //-------------------------------------------------------------- void mui::TextArea::drawBackground(){ Container::drawBackground(); } //-------------------------------------------------------------- void mui::TextArea::layout(){ mui::ScrollPane::layout(); } void mui::TextArea::sizeToFit( float padX, float padY ){ commit(); // update bounding box width = boundingBox.width + padX; height = boundingBox.height + padY; layout(); // tell ourselves about the size change } void mui::TextArea::sizeToFitWidth( float padX ){ commit(); width = boundingBox.width + padX; layout(); } void mui::TextArea::sizeToFitHeight( float padY ){ commit(); height = boundingBox.height + padY; layout(); } //-------------------------------------------------------------- //deprecated ofRectangle mui::TextArea::box( float t, float r, float b, float l ){ ofRectangle size = Helpers::alignBox( this, boundingBox.width, boundingBox.height, horizontalAlign, verticalAlign ); return ofRectangle( size.x - boundingBox.x - l, size.y - boundingBox.y + t, boundingBox.width + l + r, boundingBox.height + t + b ); } //-------------------------------------------------------------- void mui::TextArea::commit(){ mui::Helpers::loadFont(fontName); if (!multiLine) canScrollX = canScrollY = false; fontStyle.fontSize = fontSize; fontStyle.color = fg; fontStyle.fontID = fontName; boundingBox = Helpers::getFontStash().getTextBounds(text, fontStyle, 0, 0); vector<StyledText> blocks{ {text,fontStyle} }; lines = Helpers::getFontStash().layoutLines(blocks, softWrap?editor_view->width:9999999); lineNumberSourceToDisplay.clear(); lineNumberDisplayToSource.clear(); int lineNumSrc = 0; int lineNumDisp = 0; int lastLineStart = 0; for( auto & line : lines ){ auto & last = line.elements.back(); lineNumberDisplayToSource.push_back(lineNumSrc); if(last.content.styledText.text == "\n"){ lineNumberSourceToDisplay.push_back(lastLineStart); lineNumSrc ++; lastLineStart = lineNumDisp+1; } lineNumDisp ++; } lineNumberSourceToDisplay.push_back(lastLineStart); if(lines.size() == 0){ lines = Helpers::getFontStash().layoutLines({{" ",fontStyle}}, 10); } strlenWithLineStarts = 0; utf32_line_length.clear(); utf32.clear(); utf8_positions.clear(); utf32.reserve(text.size()*1.5); utf8_positions.reserve(text.size()*1.5); size_t pos = 0; for(uint32_t ch : ofUTF8Iterator(text)){ utf32.push_back(ch); utf8_positions.push_back(pos); pos += octect_size(ch); } bool first = false; for( int i = 0; i < lines.size(); i++){ StyledLine & line = lines[i]; utf32_line_length.push_back(0); for( auto el : line.elements ){ utf32_line_length[i] += (int)utf8_strlen(el.content.styledText.text); } strlenWithLineStarts += utf32_line_length[i]; if( first ) first = false; else strlenWithLineStarts ++; } // Orient y on a simple uppercase character // Otherwise things go up and down unexpectedly ofRectangle baselineSize = Helpers::getFontStash().getTextBounds("M", fontStyle, 0, 0); boundingBox.height = baselineSize.height; boundingBox.y = baselineSize.y; if(true/*autoChangeHeight*/){ float h = 0; for( int i = (int)lines.size()-1;i>=0;i--){ StyledLine & line = lines[i]; for(int j = (int)line.elements.size()-1; j>=0; j--){ h = MAX(h,line.elements[j].baseLineY); } } // add one more line! to be sure we have enough space for the decenders if (multiLine) h += baselineSize.height / 3; h = max(minHeight, h - baselineSize.y); editor_view->width = viewportWidth; if (autoChangeHeight) { editor_view->height = h; height = h; } else { h = max(viewportHeight, h); if (h != editor_view->height) { editor_view->height = h; MUI_ROOT->needsLayout = true; } } } mui::ScrollPane::commit(); } bool mui::TextArea::keyPressed( ofKeyEventArgs &key ){ lastInteraction = ofGetElapsedTimeMillis(); short redoPt = state->undostate.redo_point; short undoPt = state->undostate.undo_point; short undoWhere = state->undostate.undo_rec[MIN(98,undoPt)].where; bool certainlyChanged = false; int keyMask = (ofGetKeyPressed(OF_KEY_SHIFT)?STB_TEXTEDIT_K_SHIFT:0) | #if defined(TARGET_OSX) (ofGetKeyPressed(OF_KEY_ALT)?STB_TEXTEDIT_K_CONTROL:0) #else (ofGetKeyPressed(OF_KEY_CONTROL)?STB_TEXTEDIT_K_CONTROL:0) #endif ; #ifdef _WIN32 // windows is funny with ctrl shortcuts if (ofGetKeyPressed(OF_KEY_CONTROL) && key.key >= 1 && key.key <= 26) { key.key = key.codepoint = 'a' + (key.key - 1); } #endif switch(key.key){ case OF_KEY_HOME: stb_textedit_key(this, state, STB_TEXTEDIT_K_LINESTART|keyMask); break; case OF_KEY_END: stb_textedit_key(this, state, STB_TEXTEDIT_K_LINEEND|keyMask); break; case OF_KEY_UP: // on osx cmd+up goes to the start if(ofGetKeyPressed(OF_KEY_COMMAND)) stb_textedit_key(this, state, STB_TEXTEDIT_K_TEXTSTART); else stb_textedit_key(this, state, STB_TEXTEDIT_K_UP|keyMask); break; case OF_KEY_DOWN: // on osx cmd+down goes to the end if(ofGetKeyPressed(OF_KEY_COMMAND)) stb_textedit_key(this, state, STB_TEXTEDIT_K_TEXTEND); else stb_textedit_key(this, state, STB_TEXTEDIT_K_DOWN|keyMask); break; case OF_KEY_LEFT: if(MUI_ROOT->getKeyPressed(OF_KEY_SUPER)) stb_textedit_key(this, state, STB_TEXTEDIT_K_LINESTART|keyMask ); else stb_textedit_key(this, state, STB_TEXTEDIT_K_LEFT|keyMask); break; case OF_KEY_RIGHT: if(MUI_ROOT->getKeyPressed(OF_KEY_SUPER)) stb_textedit_key(this, state, STB_TEXTEDIT_K_LINEEND|keyMask ); else stb_textedit_key(this, state, STB_TEXTEDIT_K_RIGHT|keyMask); break; case OF_KEY_BACKSPACE: stb_textedit_key(this, state, STB_TEXTEDIT_K_BACKSPACE|keyMask); break; case OF_KEY_DEL: stb_textedit_key(this, state, STB_TEXTEDIT_K_DELETE|keyMask); break; case OF_KEY_RETURN: stb_textedit_key(this, state, STB_TEXTEDIT_NEWLINE|keyMask); break; case OF_KEY_PAGE_UP: break; case OF_KEY_PAGE_DOWN: break; case OF_KEY_ESC: // do nothing! break; default: //ok, what about other shortcuts? ... if(MUI_ROOT->getKeyPressed(MUI_KEY_ACTION) && key.keycode==GLFW_KEY_A ){ state->select_start = 0; state->select_end = (int)strlenWithLineStarts; state->cursor = state->select_end; } else if(MUI_ROOT->getKeyPressed(MUI_KEY_ACTION) && key.codepoint == 'z'){ if (ofGetKeyPressed(OF_KEY_SHIFT)) stb_text_redo(this, state); else stb_text_undo(this, state); } else if(MUI_ROOT->getKeyPressed(MUI_KEY_ACTION) && (key.codepoint == 'Z' || key.codepoint == 'y')){ stb_text_redo(this, state); } else if(MUI_ROOT->getKeyPressed(MUI_KEY_ACTION) && key.codepoint == 'x'){ ofGetWindowPtr()->setClipboardString(getSelectedText()); stb_textedit_key(this, state, STB_TEXTEDIT_K_DELETE ); } else if(MUI_ROOT->getKeyPressed(MUI_KEY_ACTION) && key.codepoint == 'c'){ ofGetWindowPtr()->setClipboardString(getSelectedText()); } else if(MUI_ROOT->getKeyPressed(MUI_KEY_ACTION) && key.codepoint == 'v'){ string text = ofGetWindowPtr()->getClipboardString(); vector<uint32_t> text_utf32 = utf8_to_utf32(text); stb_textedit_paste(this, state, &text_utf32[0], (int)text_utf32.size()); } else if (key.key == OF_KEY_TAB && state->select_start != state->select_end) { // go back to prev line break if (state->select_start > state->select_end) swap(state->select_start, state->select_end); while (state->select_start > 0 && STB_TEXTEDIT_GETCHAR(this, state->select_start -1) != '\n'){ state->select_start--; } string text = getSelectedText(); if (ofGetKeyPressed(OF_KEY_SHIFT)) { if (text[0] == '\t') text = text.substr(1); std::regex e("\n\t"); text = regex_replace(text, e, "\n"); } else { std::regex e("\n"); text = "\t" + regex_replace(text, e, "\n\t"); } insertTextAtCursor(text,true); } else if(MUI_ROOT->getKeyPressed(MUI_KEY_ACTION)){ // a shortcut of sorts, but not for us. return false; } else{ uint32_t codept = key.codepoint; if (!utf8::internal::is_code_point_valid(codept)){ // what is it? don't know! ignore it! return true; } else if( codept == 0x09 ){ // control character, but ok } else if( codept < 0x1F || codept == 0x7F || (codept >= 0x0080 && codept <= 0x009F) ){ // control character return true; } // the next 20 or so lines are basically a verbatim copy from // stb_textedit_key() with a tiny change: // a char doesn't have a fixed size // EditorData * str = this; // can't add newline in single-line mode if (codept == '\n' && state->single_line) break; if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(this)) { stb_text_makeundo_replace(this, state, state->cursor, 1, 1); STB_TEXTEDIT_DELETECHARS(this, state->cursor, 1); if (STB_TEXTEDIT_INSERTCHARS(this, state->cursor, &codept, 1)) { ++state->cursor; state->has_preferred_x = 0; certainlyChanged = true; } } else { stb_textedit_delete_selection(this,state); // implicity clamps if (STB_TEXTEDIT_INSERTCHARS(this, state->cursor, &codept, 1)) { stb_text_makeundo_insert(state, state->cursor, 1); ++state->cursor; state->has_preferred_x = 0; certainlyChanged = true; } } } } if(certainlyChanged || undoPt != state->undostate.undo_point || redoPt != state->undostate.redo_point || undoWhere != state->undostate.undo_rec[MIN(98,state->undostate.undo_point)].where ){ ofNotifyEvent(onChange, text, this); } // check if we need to scroll { EditorCursor cursor = getEditorCursorForIndex(state->cursor); scrollIntoView(cursor.rect); } return true; } bool mui::TextArea::keyReleased( ofKeyEventArgs &key ){ return true; } mui::TextArea::EditorCursor mui::TextArea::getEditorCursorForIndex( int cursorPos ){ EditorCursor result; ofRectangle size = mui::Helpers::alignBox( this, boundingBox.width, boundingBox.height, horizontalAlign, verticalAlign ); //TODO: this should be cached int pos = 0; float yy = 0; ofRectangle bounds; for( int lineIdx = 0; lineIdx < lines.size(); lineIdx++ ){ StyledLine &line = lines[lineIdx]; int len = utf32_line_length[lineIdx]; if( pos + len <= cursorPos ){ pos += len; yy += line.lineH; } else{ for( vector<LineElement>::iterator elementIt = line.elements.begin(); elementIt != line.elements.end(); ++elementIt ){ LineElement &el = *elementIt; len = (int)utf8_strlen(el.content.styledText.text); if( pos + len <= cursorPos ){ pos += len; } else{ float x; switch(el.content.type){ case SEPARATOR_INVISIBLE: case SEPARATOR: x = el.area.x + el.area.width; case WORD_BLOCK: // it's here, and we know the offset inside the word already. // now let's find it within the string. size_t len = cursorPos-pos; ofRectangle size = mui::Helpers::getFontStash().getTextBounds(substr_utf8(pos, len), el.content.styledText.style, 0, 0); // this could be wrong. hard to tell for my purpose. (layout_width) x = el.x + size.x + size.width; } string sub = substr_utf8(pos,cursorPos-pos); bounds.height = line.lineH; bounds.x = size.x - boundingBox.x + x + bounds.width; bounds.y = size.y - boundingBox.y + yy - line.lineH*0.9; bounds.width = 0; bounds.height = line.lineH; result.rect = bounds; result.lineIt = lines.begin()+lineIdx; result.elementIt = elementIt; return result; } } break; } } if( bounds == ofRectangle() ){ // still nothing? must be at last position! if( lines.size() > 0 ){ float lineH = lines.back().lineH; bounds = lines.back().elements.back().area; bounds.x = size.x - boundingBox.x + bounds.x; bounds.y = size.y - boundingBox.y + yy - 2*lineH; bounds.height = lineH; result.lineIt = lines.end()-1; // there should be always at least one element on each line, // even if it's just a SEPARATOR_INVISIBLE result.elementIt = lines.back().elements.end()-1; result.rect = bounds; } else{ result.lineIt = lines.end(); } } // this is SLOW! // maybe at least remember it? return result; } int mui::TextArea::state_select_min(){ return min(state->select_start,state->select_end); } int mui::TextArea::state_select_max(){ return max(state->select_start,state->select_end); } int mui::TextArea::state_select_len(){ int res = state->select_start - state->select_end; return res<0?-res:res; } string mui::TextArea::getSelectedText(){ return substr_utf8(state_select_min(),state_select_len()); } void mui::TextArea::insertTextAtCursor(string text, bool select){ size_t sel_start = state->select_start; vector<uint32_t> text_utf32 = utf8_to_utf32(text); stb_textedit_paste(this, state, &text_utf32[0], (int)text_utf32.size()); commit(); if (select) { setSelectedRange(sel_start, sel_start + text_utf32.size()); } } int mui::TextArea::getCursorLine(){ int cursor = state->cursor; for(int i = 0; i < lines.size(); i++){ if(utf32_line_length[i]<cursor){ cursor -= utf32_line_length[i]; } else{ return lineNumberDisplayToSource[i]; } } return max(0,(int)lineNumberDisplayToSource.back()); } int mui::TextArea::getCursorColumn(){ int cursor = state->cursor; for(int i = 0; i < lines.size(); i++){ if(utf32_line_length[i]<cursor){ cursor -= utf32_line_length[i]; } else{ return cursor; } } return lines.size()==0?0:max(0,(int)utf32_line_length[0]-1); } ofVec2f mui::TextArea::getCursorPosition(){ EditorCursor c = getEditorCursorForIndex(state->cursor); return {c.rect.x, (*c.elementIt).baseLineY}; } void mui::TextArea::selectAll(){ stb_textedit_key(this, state, STB_TEXTEDIT_K_TEXTSTART); stb_textedit_key(this, state, STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT); } void mui::TextArea::selectNothing(){ state->select_start = state->select_end; } void mui::TextArea::setSelectedRange(size_t start, size_t end){ if(utf32.size()==0) return; start = CLAMP(start,0,utf32.size()-1); end = CLAMP(end,0,utf32.size()-1); state->select_start = min(start,end); state->select_end = max(start,end); } pair<size_t,size_t> mui::TextArea::getSelectedRange(){ return make_pair(state->select_start,state->select_end); } #pragma mark Editor Data size_t mui::TextArea::idx_utf8(size_t utf32_idx){ int sz = utf8_positions.size(); return sz==0?0:(utf32_idx<sz? utf8_positions[utf32_idx]: (utf8_positions[sz-1]+octect_size(utf32[sz-1])) ); } string mui::TextArea::substr_utf8( size_t utf32_index, size_t len){ size_t N = utf32.size(); if(len==0 || N == 0) return ""; size_t from = idx_utf8(utf32_index); size_t to = idx_utf8(CLAMP(utf32_index+len-1,0,N-1)) + octect_size(utf32[CLAMP(utf32_index+len-1,0,N-1)]); return text.substr(from,to-from); } void mui::TextAreaInternal::layout_func(void *row, TextArea *data, int start_i){ return mui::TextArea::layout_func_impl(row,data,start_i); } float mui::TextAreaInternal::layout_width(mui::TextArea * data, int n, int i ){ return mui::TextArea::layout_width_impl(data, n, i ); } int mui::TextAreaInternal::delete_chars(mui::TextArea *data, int pos, int num){ return mui::TextArea::delete_chars_impl(data, pos, num); } int mui::TextAreaInternal::insert_chars(mui::TextArea *data, int pos, const uint32_t *newtext, int num){ return mui::TextArea::insert_chars_impl(data, pos, newtext, num); } int mui::TextAreaInternal::move_to_word_previous( mui::TextArea *str, int c ){ return mui::TextArea::move_to_word_previous_impl( str, c ); } int mui::TextAreaInternal::move_to_word_next( mui::TextArea *str, int c ){ return mui::TextArea::move_to_word_next_impl( str, c ); } //-------------------------------------------------------------- mui::TextAreaView::TextAreaView(mui::TextArea * textArea, float x_, float y_, float width_, float height_) :t(textArea), mui::Container(x_,y_,width_,height_){ focusTransferable = false; } //-------------------------------------------------------------- mui::TextAreaView::~TextAreaView() { } //-------------------------------------------------------------- void mui::TextAreaView::draw() { ofRectangle size = Helpers::alignBox(this, t->boundingBox.width, t->boundingBox.height, t->horizontalAlign, t->verticalAlign); if (hasKeyboardFocus() && t->state->select_start != t->state->select_end) { int left = t->state_select_min(); int right = t->state_select_max(); ofSetColor(fg*0.5 + bg*0.5); mui::TextArea::EditorCursor from = t->getEditorCursorForIndex(left); mui::TextArea::EditorCursor to = t->getEditorCursorForIndex(right); ofRectangle rect = from.rect; float yy = rect.y; bool reset = false; if (from.lineIt != to.lineIt) { // selec to end of line rect.width = (*from.lineIt).lineW - rect.x; ofDrawRectangle(rect); from.lineIt++; reset = true; yy += (*from.lineIt).lineH; } while (from.lineIt != to.lineIt) { StyledLine &line = *from.lineIt; float x = size.x - t->boundingBox.x + line.elements.front().x; float y = yy; ofDrawRectangle(x, y, line.lineW, line.lineH); yy += line.lineH; ++from.lineIt; reset = true; } if (from.lineIt != t->lines.end()) { StyledLine &line = *from.lineIt; float x = reset ? (size.x - t->boundingBox.x + line.elements.front().x) : from.rect.x; float y = reset ? yy : from.rect.y; ofDrawRectangle(x, y, to.rect.x + to.rect.width - x, line.lineH); ++from.lineIt; } } // mui::Helpers::getFontStash().drawColumn(text, fontStyle, size.x-boundingBox.x, size.y-boundingBox.y, width); mui::Helpers::getFontStash().drawLines(t->lines, size.x - t->boundingBox.x, size.y - t->boundingBox.y, MuiConfig::debugDraw); if (hasKeyboardFocus()) { if (t->drawActiveBorder) { ofSetColor(200); ofNoFill(); ofDrawRectangle(0.5, 0.5, width - 1, height - 1); ofFill(); } // getting the time is slow, but it can only happen // for a single textfield here because of the focus (so we're fine) uint64_t time = ofGetElapsedTimeMillis(); if (((time - t->lastInteraction) % 1000) < 500) { ofSetColor(255); ofRectangle bounds = t->getEditorCursorForIndex(t->state->cursor).rect; ofDrawRectangle(bounds.x + bounds.width, bounds.y + 2, 2, bounds.height - 2); } } ofSetColor(255); } void mui::TextAreaView::touchDown(ofTouchEventArgs &touch) { t->lastInteraction = ofGetElapsedTimeMillis(); if (t->selectAllOnFocus && !hasKeyboardFocus()) { t->selectAll(); } else { stb_textedit_click(t, t->state, touch.x, touch.y); } requestKeyboardFocus(); } void mui::TextAreaView::touchUp(ofTouchEventArgs &touch) { } void mui::TextAreaView::touchUpOutside(ofTouchEventArgs &touch) { } void mui::TextAreaView::touchMoved(ofTouchEventArgs &touch) { stb_textedit_drag(t, t->state, touch.x, touch.y); } void mui::TextAreaView::touchMovedOutside(ofTouchEventArgs &touch) { stb_textedit_drag(t, t->state, touch.x, touch.y); } void mui::TextAreaView::mouseScroll(ofMouseEventArgs &args) { t->mouseScroll(args); }
30.857868
190
0.676921
kritzikratzi
f72fbfb118491d9658517a41feba8e1f12c5e7f8
529
cpp
C++
baekjoon/2156.cpp
3-24/Competitive-Programming
8cb3b85bf89db2c173cb0b136de27f2983f335fc
[ "MIT" ]
1
2019-07-15T00:27:37.000Z
2019-07-15T00:27:37.000Z
baekjoon/2156.cpp
3-24/Competitive-Programming
8cb3b85bf89db2c173cb0b136de27f2983f335fc
[ "MIT" ]
null
null
null
baekjoon/2156.cpp
3-24/Competitive-Programming
8cb3b85bf89db2c173cb0b136de27f2983f335fc
[ "MIT" ]
null
null
null
#include <stdio.h> #include <iostream> #include <algorithm> using namespace std; int main(){ int n; scanf("%d",&n); int arr[n+1],D[n+1],i; for (i=0;i<n;i++){ scanf("%d",&arr[i]); } for (i=0;i<n;i++){ if (i==0){D[i] = arr[0];} else if (i==1){D[i] = arr[0]+arr[1];} else if (i==2){D[i] = max({D[i-1],arr[2]+arr[0],arr[2]+arr[1]});} else{ D[i] = max({D[i-1],arr[i]+D[i-2],arr[i]+arr[i-1]+D[i-3]}); } } printf("%d",D[n-1]); return 0; }
22.041667
73
0.425331
3-24
f730000977e3f3c5d38f1cc8f45305e50d49f622
10,155
cpp
C++
osrMain/DX11RenderMain.cpp
OSRTeam/OpenSoundRefenation
3118ea723a2ba94af33ab34bc65eafbd52f7169a
[ "Apache-2.0", "MIT" ]
9
2019-01-17T13:11:06.000Z
2022-02-22T10:38:16.000Z
osrMain/DX11RenderMain.cpp
OSRTeam/OpenSoundRefenation
3118ea723a2ba94af33ab34bc65eafbd52f7169a
[ "Apache-2.0", "MIT" ]
null
null
null
osrMain/DX11RenderMain.cpp
OSRTeam/OpenSoundRefenation
3118ea723a2ba94af33ab34bc65eafbd52f7169a
[ "Apache-2.0", "MIT" ]
3
2019-08-09T16:01:37.000Z
2020-08-08T09:58:02.000Z
/********************************************************* * Copyright (C) VERTVER, 2018. All rights reserved. * OpenSoundRefenation - WINAPI open-source DAW * MIT-License ********************************************************** * Module Name: OSR User Interface ********************************************************** * DX11RenderMain.cpp * Direct3D11 main implementation *********************************************************/ #include "stdafx.h" #include <d3dcompiler.h> #pragma comment(lib, "d3d9.lib") #pragma comment(lib, "d3d11.lib") #pragma comment(lib, "dxgi.lib") #pragma comment(lib, "d3dcompiler.lib") OSRCODE DX11Render::CreateRenderWindow(HWND WindowHandle) { HRESULT hr = NULL; DXGI_SWAP_CHAIN_DESC &sd = m_pChainDesc; DXGI_ADAPTER_DESC LegacyDesc = {}; DXGI_ADAPTER_DESC1 Desc = {}; if (!WindowHandle) { return DX_OSR_BAD_ARGUMENT; } MainHwnd = WindowHandle; // if our PC doesn't support DXGIFactor1 - try to use older if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&m_pDXGIFactory)))) { FAILEDX2(CreateDXGIFactory(IID_PPV_ARGS(&m_pLegacyDXGIFactory))); } if (!m_pDXGIFactory) { if (!m_pLegacyDXGIFactory) { return DX_OSR_BAD_HW; } else { FAILEDX2(m_pLegacyDXGIFactory->QueryInterface(IID_PPV_ARGS(&m_pDXGIFactory))); } } //#TODO: take set adapters for user if (m_pLegacyDXGIFactory) { m_pDXGIFactory->EnumAdapters(NULL, &m_pLegacyDXGIAdapter); m_pLegacyDXGIAdapter->QueryInterface(IID_PPV_ARGS(&m_pDXGIAdapter)); _RELEASE(m_pLegacyDXGIAdapter); _RELEASE(m_pLegacyDXGIFactory); m_pDXGIAdapter->GetDesc(&LegacyDesc); } else { m_pDXGIFactory->EnumAdapters1(NULL, &m_pDXGIAdapter); m_pDXGIAdapter->GetDesc1(&Desc); } sd.BufferDesc.Height = 0; sd.BufferDesc.Width = 0; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferCount = 2; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; sd.OutputWindow = MainHwnd; sd.Windowed = TRUE; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; D3D_FEATURE_LEVEL pFeatureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0 }; D3D_FEATURE_LEVEL FeatureLevel = {}; hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, pFeatureLevels, sizeof(pFeatureLevels) / sizeof(pFeatureLevels[0]), D3D11_SDK_VERSION, &sd, &m_pDXGISwapChain, &m_pDevice, &FeatureLevel, &m_pContext ); if (FAILED(hr)) { FAILEDX2( //-V568 D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, &pFeatureLevels[1], sizeof(pFeatureLevels) / sizeof(pFeatureLevels[0] - 1), D3D11_SDK_VERSION, &sd, &m_pDXGISwapChain, &m_pDevice, &FeatureLevel, &m_pContext )); } ID3D11Texture2D* pBackBuffer = nullptr; m_pDXGISwapChain->GetBuffer(NULL, IID_PPV_ARGS(&pBackBuffer)); m_pDevice->CreateRenderTargetView(pBackBuffer, NULL, &m_pRenderTargetView); _RELEASE(pBackBuffer); return OSR_SUCCESS; } OSRCODE DX11Render::LoadShader( LPCWSTR lpShaderName, LPCSTR* lpShaderFile ) { DWORD dwShaderWritten = 0; DWORD dwShaderSize = 0; LPCSTR lpShader = nullptr; LPWSTR StaticBuf = nullptr; WSTRING_PATH szPathToDir = { 0 }; GetApplicationDirectory(&StaticBuf); memcpy(szPathToDir, StaticBuf, 520); _snwprintf_s(szPathToDir, sizeof(WSTRING_PATH), L"%s%s", szPathToDir, L"\\Shaders"); //-V575 DWORD dwGetDir = GetFileAttributesW(szPathToDir); if (dwGetDir == INVALID_FILE_ATTRIBUTES || !(dwGetDir & FILE_ATTRIBUTE_DIRECTORY)) { if (!CreateDirectoryW(szPathToDir, nullptr)) { DWORD dwError = GetLastError(); if (!IsProcessWithAdminPrivilege() && dwError == ERROR_ACCESS_DENIED) { if (THROW4(L"Can't create temp directory because access denied. Re-run application with 'Administrator' privilege?")) { RunWithAdminPrivilege(); } } else { THROW1(L"Can't create temp directory"); } } } else { _snwprintf_s(szPathToDir, sizeof(WSTRING_PATH), L"%s%s%s", szPathToDir, L"\\", lpShaderName); //-V575 HANDLE hFile = CreateFileW(szPathToDir, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (!hFile || hFile == INVALID_HANDLE_VALUE) { return FS_OSR_BAD_HANDLE; } FILE_STANDARD_INFO fileInfo = {}; GetFileInformationByHandleEx(hFile, FileStandardInfo, &fileInfo, sizeof(fileInfo)); dwShaderSize = fileInfo.EndOfFile.LowPart; lpShader = (LPCSTR)FastAlloc(dwShaderSize); ReadFile(hFile, (LPVOID)lpShader, dwShaderSize, &dwShaderWritten, nullptr); CloseHandle(hFile); } if (!lpShader) { return FS_OSR_BAD_PATH; } *lpShaderFile = lpShader; return OSR_SUCCESS; } OSRCODE DX11Render::BeginRenderBlur( ID3D11DeviceContext* pCustomDeviceContext, DWORD Height, DWORD Width ) { if (Width > 10000 || !Width) Width = 1; if (Height > 10000 || !Height) Height = 1; static D3D11_TEXTURE2D_DESC textureDesc = { }; bool RestartRenderTargets = false; if (textureDesc.Width != Width || textureDesc.Height != Height) { RestartRenderTargets = true; } textureDesc.ArraySize = 1; textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = 0; textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; textureDesc.Height = Height; textureDesc.MipLevels = 1; textureDesc.MiscFlags = 0; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Usage = D3D11_USAGE_DEFAULT; textureDesc.Width = Width; static D3D11_SHADER_RESOURCE_VIEW_DESC textureDescSR = { }; textureDescSR.Format = DXGI_FORMAT_R8G8B8A8_UNORM; textureDescSR.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; textureDescSR.Texture2D.MipLevels = 1; textureDescSR.Texture2D.MostDetailedMip = 0; if (RestartRenderTargets) { _RELEASE(pTargetView1); _RELEASE(pTargetView2); _RELEASE(pTargetView3); _RELEASE(pResourceView1); _RELEASE(pResourceView2); _RELEASE(pResourceView3); _RELEASE(pTexture1); _RELEASE(pTexture2); _RELEASE(pTexture3); FAILEDX2(m_pDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture1)); FAILEDX2(m_pDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture2)); FAILEDX2(m_pDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture3)); FAILEDX2(m_pDevice->CreateRenderTargetView(pTexture1, nullptr, &pTargetView1)); FAILEDX2(m_pDevice->CreateRenderTargetView(pTexture2, nullptr, &pTargetView2)); FAILEDX2(m_pDevice->CreateRenderTargetView(pTexture3, nullptr, &pTargetView3)); FAILEDX2(m_pDevice->CreateShaderResourceView(pTexture1, &textureDescSR, &pResourceView1)); FAILEDX2(m_pDevice->CreateShaderResourceView(pTexture2, &textureDescSR, &pResourceView2)); FAILEDX2(m_pDevice->CreateShaderResourceView(pTexture3, &textureDescSR, &pResourceView3)); } static LPCSTR lpShader = nullptr; if (!lpShader) { OSRFAIL2(LoadShader(L"MBlur.hlsl", &lpShader), L"Can't load shader"); } if (!vertexShaderBlur) { FAILEDX2(D3DCompile(lpShader, strlen(lpShader), nullptr, nullptr, nullptr, "VSSimpleBlur", "vs_4_0", 0, 0, &vertexShaderBlur, nullptr)); FAILEDX2(m_pDevice->CreateVertexShader(vertexShaderBlur->GetBufferPointer(), vertexShaderBlur->GetBufferSize(), nullptr, &pBlurVertexShader)); } if (!pBlurPixelShaderU) { FAILEDX2(D3DCompile(lpShader, strlen(lpShader), nullptr, nullptr, nullptr, "PSSimpleBlurU", "ps_4_0", 0, 0, &pixelShaderBlurU, nullptr)); FAILEDX2(m_pDevice->CreatePixelShader(pixelShaderBlurU->GetBufferPointer(), pixelShaderBlurU->GetBufferSize(), nullptr, &pBlurPixelShaderU)); } if (!pBlurPixelShaderV) { FAILEDX2(D3DCompile(lpShader, strlen(lpShader), nullptr, nullptr, nullptr, "PSSimpleBlurV", "ps_4_0", 0, 0, &pixelShaderBlurV, nullptr)); FAILEDX2(m_pDevice->CreatePixelShader(pixelShaderBlurV->GetBufferPointer(), pixelShaderBlurV->GetBufferSize(), nullptr, &pBlurPixelShaderV)); } if (!m_pDisplaySizeBuffer) { D3D11_BUFFER_DESC pDesc = {}; pDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; pDesc.ByteWidth = sizeof(float) * 4; pDesc.CPUAccessFlags = 0;// D3D11_CPU_ACCESS_WRITE; pDesc.MiscFlags = 0; pDesc.StructureByteStride = 0; pDesc.Usage = D3D11_USAGE_DEFAULT;// DYNAMIC; FAILEDX2(m_pDevice->CreateBuffer(&pDesc, nullptr, &m_pDisplaySizeBuffer)); } pCustomDeviceContext->OMSetRenderTargets(1, &pTargetView1, nullptr); float ffgfdgfdg[4] = { 0.07f, 0.07f, 0.07f, 1.00f }; pCustomDeviceContext->ClearRenderTargetView(pTargetView1, ffgfdgfdg); return OSR_SUCCESS; } OSRCODE DX11Render::EndRenderBlur( ID3D11DeviceContext* pCustomDeviceContext, DWORD Height, DWORD Width ) { ID3D11Buffer* Buf = nullptr; UINT ba1 = 0; UINT ba2 = 0; // stage 1 D3D11_VIEWPORT vp; memset(&vp, 0, sizeof(D3D11_VIEWPORT)); vp.Width = Width; vp.Height = Height; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = vp.TopLeftY = 0; pCustomDeviceContext->RSSetViewports(1, &vp); const D3D11_RECT r = { 0, 0, Width, Height }; pCustomDeviceContext->RSSetScissorRects(1, &r); float DisplaySize[4] = { Width, Height , 0.0, 0.0}; pCustomDeviceContext->UpdateSubresource(m_pDisplaySizeBuffer, 0, nullptr, &DisplaySize[0], 0, 0); if (m_pDisplaySizeBuffer) { pCustomDeviceContext->PSSetConstantBuffers(5, 1, &m_pDisplaySizeBuffer); } pCustomDeviceContext->VSSetShader(pBlurVertexShader, nullptr, 0); pCustomDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); pCustomDeviceContext->IASetVertexBuffers(0, 1, &Buf, &ba1, &ba2); pCustomDeviceContext->IASetIndexBuffer(nullptr, DXGI_FORMAT_R16_UINT, 0); pCustomDeviceContext->IASetInputLayout(nullptr); pCustomDeviceContext->OMSetRenderTargets(1, &pTargetView2, nullptr); pCustomDeviceContext->PSSetShaderResources(0, 1, &pResourceView1); pCustomDeviceContext->PSSetShader(pBlurPixelShaderU, nullptr, 0); pCustomDeviceContext->Draw(3, 0); // stage 2 pCustomDeviceContext->OMSetRenderTargets(1, &m_pRenderTargetView, nullptr); pCustomDeviceContext->PSSetShaderResources(0, 1, &pResourceView2); pCustomDeviceContext->PSSetShader(pBlurPixelShaderV, nullptr, 0); pCustomDeviceContext->Draw(3, 0); return OSR_SUCCESS; }
31.055046
144
0.742885
OSRTeam
f730c11c7760a16388ec888a459f61c0e1f8fb1f
4,565
cpp
C++
markcore/ut/use_markcore.cpp
unihykes/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
2
2018-03-27T02:46:03.000Z
2018-05-24T02:49:17.000Z
markcore/ut/use_markcore.cpp
six-th/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
null
null
null
markcore/ut/use_markcore.cpp
six-th/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
null
null
null
/*************************************************************************************************** LICENSE: 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:liu.hao([email protected]) Time:2018-2 info: ***************************************************************************************************/ #include <markcore.h> #include <gtest/gtest.h> //////////////////////////////////////////////////////////////////////////////////////////////////// TEST(mkheaders, pragma) { #ifdef __WINDOWS__ // 链接基础库 #pragma comment(lib, "shell32.lib") #pragma comment(lib, "advapi32.lib") #pragma comment(lib, "user32.lib") #pragma comment(lib, "Ws2_32.lib") #pragma comment(lib, "Mpr.lib") #pragma comment(lib, "DbgHelp.lib") //关闭部分编译警告 // 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2' #pragma warning(disable:4251) // 'function': was declared deprecated #pragma warning(disable:4996) // 'this' : used in base member initializer list #pragma warning(disable:4355) // 'symbol name': attributes not present on previous declaration. #pragma warning(disable: 4985) // 'virtual function overrides' : previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers #pragma warning(disable: 4373) // 'keyword' : ignored on left of 'type' when no variable is declared #pragma warning(disable: 4091) #endif } TEST(mkheaders, PrintMacro) { //操作系统版本,在begin.cmake中定义 #ifdef __WINDOWS__ MK_PRINT("__WINDOWS__ = %d", __WINDOWS__); #endif #ifdef __LINUX__ MK_PRINT("__LINUX__ = %d", __LINUX__); #endif //编译器版本 #ifdef _MSC_VER MK_PRINT("_MSC_VER = %d", _MSC_VER); #endif #ifdef __GNUC__ MK_PRINT("__GNUC__ = %d", __GNUC__); #endif //VC版本 #ifdef WINVER MK_PRINT("WINVER = 0x%04x", WINVER); #endif #ifdef _WIN32_WINNT MK_PRINT("_WIN32_WINNT = 0x%04x", _WIN32_WINNT); #endif #ifdef _WIN32_WINDOWS MK_PRINT("_WIN32_WINDOWS = 0x%04x", _WIN32_WINDOWS); #endif #ifdef _WIN32_IE MK_PRINT("_WIN32_IE = 0x%04x", _WIN32_IE); #endif //windows常用头文件 #ifdef _WINSOCK2API_ MK_PRINT("_WINSOCK2API_ is used"); #endif #ifdef _WINSOCKAPI_ MK_PRINT("_WINSOCKAPI_ is used"); #endif #ifdef _INC_TCHAR MK_PRINT("_INC_TCHAR is used"); #endif //64位宏 #ifdef __x86_64__ MK_PRINT("__x86_64__ is used"); #endif #ifdef __ia64__ MK_PRINT("__ia64__ is used"); #endif #ifdef __PPC64__ MK_PRINT("__PPC64__ is used"); #endif #ifdef __powerpc64__ MK_PRINT("__powerpc64__ is used"); #endif #ifdef __mips64 MK_PRINT("__mips64 is used"); #endif #ifdef __arch64__ MK_PRINT("__arch64__ is used"); #endif #ifdef __aarch64__ MK_PRINT("__aarch64__ is used"); #endif #ifdef _WIN64 MK_PRINT("_WIN64 = %d", _WIN64); #endif #ifdef __64BIT__ MK_PRINT("__64BIT__ is used"); #endif //unicode宏,在begin.cmake中定义 #ifdef _UNICODE MK_PRINT("_UNICODE = %d", _UNICODE); #endif #ifdef UNICODE MK_PRINT("UNICODE = %d", UNICODE); #endif //debug宏 #ifdef _DEBUG MK_PRINT("_DEBUG = %d", _DEBUG); MK_PRINT("__DEBUG__ is used"); #endif //va_copy宏 #ifdef va_copy MK_PRINT("va_copy is used"); #endif #ifdef __va_copy MK_PRINT("__va_copy is used"); #endif //__FUNC_NAME__宏 #ifdef __FUNC_NAME__ MK_PRINT(_T("__FUNC_NAME__ = %s"), __FUNC_NAME__); #endif } TEST(mkheaders, mkChar) { const mkChar* ch1 = _T("abcecdrgg"); MK_PRINT(_T("ch1 = %s"), ch1); const mkChar ch3[] = _T("123456789"); //mk_char 长度 #define CONSTANT_STRING_LEN(str) ((sizeof(str)/sizeof(mkChar)) - 1) int size3 = CONSTANT_STRING_LEN(ch3); MK_PRINT(_T("ch3 = %s, size = %d"), ch3, size3); } TEST(mkheaders, int64) { int64 i1 = -123456; uint64 i2 = 123456; MK_PRINT(_T("i1 = %lld, i2 = %lld"), i1, i2); } TEST(mkheaders, MK_ASSERT) { MK_ASSERT(true); //MK_ASSERT(false); }
24.153439
146
0.62322
unihykes
f73c165749ddd353556967b987f6ac880665b7e8
2,887
cpp
C++
libStat3rd/Statistical/RegressionFactory.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
3
2021-06-14T15:36:46.000Z
2022-02-28T15:16:08.000Z
libStat3rd/Statistical/RegressionFactory.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
1
2021-07-17T07:52:15.000Z
2021-07-17T07:52:15.000Z
libStat3rd/Statistical/RegressionFactory.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
3
2021-07-12T14:52:38.000Z
2021-11-28T17:10:33.000Z
#include "RegressionFactory.hpp" using namespace EnjoLib; RegressionFactory::RegressionFactory() { //ctor } RegressionFactory::~RegressionFactory() { //dtor } /* #include "RegressionRegression3.hpp" #include "RegressionMKL.hpp" #include "RegressionNumpy.hpp" #include "RegressionNewmat10.hpp" */ /* Corrade::Containers::Pointer<RegressionAbstract> RegressionAbstract::CreateRegression3() { return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionRegression3()); } Corrade::Containers::Pointer<RegressionAbstract> RegressionAbstract::CreateDefault() { //return CreateNewmat(); /// TODO: Errors in tests, just like MKL! Ergo: wrong Regression or tests! return CreateMKL(); } Corrade::Containers::Pointer<RegressionAbstract> RegressionAbstract::CreateMKL() { return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionMKL()); } #ifdef USE_LIB_NEWMAT Corrade::Containers::Pointer<RegressionAbstract> RegressionAbstract::CreateNewmat() { return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionNewmat10()); } #endif Corrade::Containers::Pointer<RegressionAbstract> RegressionAbstract::CreateNumpy() { return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionNumpy()); } EIGENTYPE_DEFAULT, EIGENTYPE_EIGEN3, EIGENTYPE_MKL, EIGENTYPE_NEWMAT, EIGENTYPE_NUMPY */ #include "3rdParty/RegressionGSL.hpp" #include "3rdParty/RegressionEigen.hpp" //#include "RegressionAF.h" #include <Util/Except.hpp> #include <Template/CorradePointer.h> Corrade::Containers::Pointer<RegressionAbstract> RegressionFactory::CreateDefault() const { return Create(RegressionAbstract::RegType::REG_EIGEN); } Corrade::Containers::Pointer<RegressionAbstract> RegressionFactory::Create(const RegressionAbstract::RegType & eigType) const { return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionEigen()); } /* #include "RegressionGSL.h" #include "RegressionEigen.h" //#include "RegressionAF.h" #include <Util/Except.hpp> #include <Template/CorradePointer.h> Corrade::Containers::Pointer<RegressionAbstract> RegressionAbstract::Create(const RegressionAbstract::RegType & type) { switch (type) { case RegType::REG_GSL: return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionGSL()); case RegType::REG_EIGEN: return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionEigen()); //case RegType::REG_AFIRE: return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionAF()); case RegType::REG_AFIRE: return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionEigen()); } throw EnjoLib::ExceptRuntimeError("RegressionAbstract::Create() Not handled."); } Corrade::Containers::Pointer<RegressionAbstract> RegressionAbstract::CreateDefault() { return Create(RegType::REG_EIGEN); } */
31.725275
125
0.764808
EnjoMitch
f73e335112f0fe4fc726fb6f647602c6cc30e053
2,671
cpp
C++
MidiNote.cpp
christofmuc/juce-utils
e5d7e0b4ac6f3c0d43d3f3cff779f5f8e72275e4
[ "MIT" ]
10
2020-02-28T21:00:25.000Z
2021-11-18T03:24:57.000Z
MidiNote.cpp
christofmuc/juce-utils
e5d7e0b4ac6f3c0d43d3f3cff779f5f8e72275e4
[ "MIT" ]
null
null
null
MidiNote.cpp
christofmuc/juce-utils
e5d7e0b4ac6f3c0d43d3f3cff779f5f8e72275e4
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2019-2021 Christof Ruch * * 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 "MidiNote.h" #include <cmath> MidiNote::MidiNote(double frequency, double frequencyA4 /* = 440.0 */) : frequency_(frequency), frequencyA4_(frequencyA4) { midiNote_ = frequencyToNoteNumber(frequency, frequencyA4_); } MidiNote::MidiNote(int noteNumber, double frequencyA4 /* = 440.0 */) : midiNote_(noteNumber), frequencyA4_(frequencyA4) { frequency_ = noteNumberToFrequency(noteNumber, frequencyA4_); } int MidiNote::frequencyToNoteNumber(double frequency, double frequencyA4 /* = 440.0 */) { // https://en.wikipedia.org/wiki/Piano_key_frequencies if (frequency > 0.0) { return (int) std::round(12 * std::log2(frequency / frequencyA4) + 69); } else { return 0; } } double MidiNote::noteNumberToFrequency(int noteNumber, double frequencyA4 /* = 440.0 */) { // 69 is MIDI for A4 return frequencyA4 * std::pow(2.0, (noteNumber - 69) / 12.0); } int MidiNote::noteNumber() const { return midiNote_; } double MidiNote::frequency() const { return frequency_; } double MidiNote::cents() { // A wild ride: http://www.sengpielaudio.com/calculator-centsratio.htm if (frequency_ > 0.0) { return 1200.0 * std::log2(frequency_ / noteNumberToFrequency(midiNote_, frequencyA4_)); } else { return 0.0; } } std::string MidiNote::name() const { // Ok, JUCE can do this for us if (midiNote_ > 0) { return MidiMessage::getMidiNoteName(midiNote_, true, true, 4).toStdString(); } else { return "-"; } }
30.701149
121
0.70161
christofmuc
f7451eb7c142df31100dcc499730a8cf2a995ae5
6,424
hpp
C++
src/math/Quaternion.hpp
jmitchell24/cpp-utility-lib
76e7bae9f07b741c409a282604a999ab86fc0702
[ "Apache-2.0" ]
null
null
null
src/math/Quaternion.hpp
jmitchell24/cpp-utility-lib
76e7bae9f07b741c409a282604a999ab86fc0702
[ "Apache-2.0" ]
null
null
null
src/math/Quaternion.hpp
jmitchell24/cpp-utility-lib
76e7bae9f07b741c409a282604a999ab86fc0702
[ "Apache-2.0" ]
null
null
null
// Copyright 2013, James Mitchell, All rights reserved. #pragma once #include "../Types.hpp" #include "../string/Types.hpp" #include "../string/Segment.hpp" #include "../typetraits/CallTraits.hpp" #include "Matrix4x4.hpp" #include "Vector4D.hpp" namespace util { template <typename N> struct QuatN { typedef N Num; typedef Num& NumRef; typedef best_param<Num> NumParam; typedef Vec3N<Num> Vec3; typedef Vec3& Vec3Ref; typedef best_param<Vec3> Vec3Param; typedef Vec4N<Num> Vec4; typedef Vec4& Vec4Ref; typedef best_param<Vec4> Vec4Param; typedef Mat44N<Num> Mat44; typedef Mat44& Mat44Ref; typedef best_param<Mat44> Mat44Param; typedef QuatN<Num> Quat; typedef Quat& QuatRef; typedef best_param<Quat> QuatParam; typedef typename Vec4::Components Components; union { struct { union { struct { Num x,y,z; }; Vec3 complex; }; union { Num w, real; }; }; Components components; Vec4 vector; }; inline QuatN() : vector() {} inline QuatN(Quat&& q) : vector(std::move(q.vector)) {} inline QuatN(Quat const& q) : vector(q.vector) {} template <typename P> inline explicit QuatN(QuatN<P> const& q) : components(q.components) {} inline explicit QuatN(Vec4Param v) : vector(v) {} inline QuatN(Vec3Param complex, NumParam real) : complex(complex), real(real) {} inline QuatN(NumParam x, NumParam y, NumParam z, NumParam w) : x(x), y(y), z(z), w(w) {} inline Quat conjugate() const // conjugate { return Quat(-complex, real); } inline Num length() const { return vector.length(); } inline Quat normal() const { return Quat(vector.normal()); } inline Quat inverse() const { return conjugate() / normal(); } inline static Quat euler(NumParam x, NumParam y, NumParam z) { Num const c1 = std::cos(z / (Num)2),c2 = std::cos(y / (Num)2),c3 = std::cos(x / (Num)2), s1 = std::sin(z / (Num)2),s2 = std::sin(y / (Num)2),s3 = std::sin(x / (Num)2); return Quat( c1*c2*s3 - s1*s2*c3, c1*s2*c3 + s1*c2*s3, s1*c2*c3 - c1*s2*s3, c1*c2*c3 + s1*s2*s3); } inline static Quat euler(Vec3Param v) { return euler(v.x, v.y, v.z); } inline Mat44 matrix() const { typename Mat44::Components const components = { +w,-z,+y,+x, +z,+w,-x,+y, -y,+x,+w,+z, -x,-y,-z,+w }; return Mat44(components); } inline Mat44 rightMatrix() const { typename Mat44::Components const components = { +w,-z, y,-x, +z,+w,-x,-y, -y,+x,+w,-z, +x,+y,+z,+w }; return Mat44(components); } inline Mat44 rotation() const { typename Mat44::Components const components = { (Num)1-(Num)2*y*y - (Num)2*z*z, (Num)2*x*y - (Num)2*z*w, (Num)2*x*z + (Num)2*y*w, (Num)0, (Num)2*x*y + (Num)2*z*w, (Num)1-(Num)2*x*x - (Num)2*z*z, (Num)2*y*z - (Num)2*x*w, (Num)0, (Num)2*x*z - (Num)2*y*w, (Num)2*y*z + (Num)2*x*w, (Num)1-(Num)2*x*x - (Num)2*y*y, (Num)0, (Num)0 , (Num)0 , (Num)0 , (Num)1 }; return Mat44(components); } Vec3 rotatedVector(Vec3Param v) const { return (*this * Quat(v, Num()) * conjugate()).complex; } inline Quat operator* (NumParam s) const { return Quat(vector * s); } inline Quat operator/ (NumParam s) const { return Quat(vector / s); } inline Quat operator+ (NumParam s) const { return Quat(vector + s); } inline Quat operator- (NumParam s) const { return Quat(vector - s); } inline Quat operator+ (QuatParam q) const { return Quat(vector + q.vector); } inline Quat operator- (QuatParam q) const { return Quat(vector - q.vector); } inline Quat operator/ (QuatParam q) const { return Quat(vector / q.vector); } inline Quat operator* (QuatParam q) const { return Quat(y*q.z - z*q.y + x*q.w + w*q.x, z*q.x - x*q.z + y*q.w + w*q.y, x*q.y - y*q.x + z*q.w + w*q.z, w*q.w - x*q.x - y*q.y - z*q.z); } inline Quat& operator = (QuatParam q) { vector = q.vector; return *this; } inline Quat& operator*= (QuatParam q) { return *this = *this * q; } inline Quat& operator/= (QuatParam q) { return *this = *this / q; } inline Quat& operator+= (QuatParam q) { return *this = *this + q; } inline Quat& operator-= (QuatParam q) { return *this = *this - q; } inline Quat& operator*= (NumParam n) { return *this = *this * n; } inline Quat& operator/= (NumParam n) { return *this = *this / n; } inline Quat& operator+= (NumParam n) { return *this = *this + n; } inline Quat& operator-= (NumParam n) { return *this = *this - n; } inline bool tryParse(Segment const& s) { return vector.tryParse(s); } inline string_t str() const { return vector.str(); } DEFINE_OBJECT_OSTREAM_OPERATOR(Quat) DEFINE_OBJECT_ISTREAM_OPERATOR(Quat) }; template <typename N> using QuatT = QuatN<N>; typedef QuatT<real_t> Quat; typedef QuatT<float> Quatf; typedef QuatT<double> Quatd; extern template struct QuatN<float>; extern template struct QuatN<double>; }
29.603687
119
0.475716
jmitchell24
f74657909e9fe922540ca914440d658265313dca
12,286
cpp
C++
src/ADBDriverDLL/src/DriverNetSyncInternal.cpp
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
9
2019-05-20T12:06:36.000Z
2022-03-24T19:11:06.000Z
src/ADBDriverDLL/src/DriverNetSyncInternal.cpp
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
null
null
null
src/ADBDriverDLL/src/DriverNetSyncInternal.cpp
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
3
2020-07-06T04:51:33.000Z
2021-07-26T20:08:02.000Z
/* MIT License Android remote Viewer, GUI ADB tools Android Viewer developed to view and control your android device from a PC. ADB exchange Android Viewer, support scale view, input tap from mouse, input swipe from keyboard, save/copy screenshot, etc.. Copyright (c) 2016-2019 PS GitHub: https://github.com/ClnViewer/ADB-Android-Viewer 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, sub license, 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 "DriverInternal.h" #include "DriverConst.h" #include "Utils/extTraceFunction.h" #include <errno.h> #define ADBSYNCDATA_SIZE static_cast<int32_t>(sizeof(DriverNet::ADBSYNCDATA)) #define ADBSYNCID_SIZE static_cast<int32_t>(sizeof(((DriverNet::ADBSYNCDATA*)0)->id)) #define TRACE_DBG_STR_0 "pkt.rsz = %d, pkt.asz = %d" #define TRACE_DBG_STR_1 "ecode = %d, errno = %d, error: %s" #define TRACE_DBG_STR_2 ", errno = %d, error: %s" namespace GameDev { DriverNet::SyncTagType DriverNet::receiveData(SOCKET client, std::unique_ptr<char[]> & dbuf, DriverNet::ADBSYNCPKT & pkt) { tracer(); struct timeval tms{}; fd_set fds{}; FD_ZERO(&fds); FD_SET(client, &fds); tms.tv_sec = 5; tms.tv_usec = 0; errno = 0; pkt.buff = nullptr; switch (::select(client + 1, &fds, nullptr, nullptr, &tms)) { case SOCKET_ERROR: { if (DriverNet::GetNetBlock()) trace_return(DriverNet::SyncTagType::SYNC_TAG_CONTINUE); pkt.rsz = -2; trace_info( TRACE_DBG_STR_1, pkt.rsz, errno, ((errno) ? strerror(errno) : "-") ); trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } case 0: /// timeout { if (!errno) trace_return(DriverNet::SyncTagType::SYNC_TAG_END); pkt.rsz = -3; trace_info( TRACE_DBG_STR_1, pkt.rsz, errno, ((errno) ? strerror(errno) : "-") ); trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } default: { switch ((pkt.rsz = ::recv(client, dbuf.get(), 65536, 0))) { case 0: /// disconnect { pkt.rsz = -4; trace_info( TRACE_DBG_STR_1, pkt.rsz, errno, ((errno) ? strerror(errno) : "-") ); trace_return(DriverNet::SyncTagType::SYNC_TAG_END); } case SOCKET_ERROR: { if (DriverNet::GetNetBlock()) trace_return(DriverNet::SyncTagType::SYNC_TAG_CONTINUE); pkt.rsz = -1; trace_info( TRACE_DBG_STR_1, pkt.rsz, errno, ((errno) ? strerror(errno) : "-") ); trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } default: { if (pkt.rsz > 0) { pkt.buff = dbuf.get(); trace_return(DriverNet::SyncTagType::SYNC_TAG_OKAY); } trace_return(DriverNet::SyncTagType::SYNC_TAG_END); } } break; } } } bool DriverNet::receivedDataWrite(FILE *fpp, DriverNet::ADBSYNCPKT & pkt) { tracer(); if (!pkt.buff) trace_return(false); errno = 0; size_t sz = static_cast<size_t>(pkt.rsz); if (::fwrite(pkt.buff, 1, sz, fpp) != sz) trace_return(false); pkt.asz -= pkt.rsz; trace_info( TRACE_DBG_STR_0 TRACE_DBG_STR_2, pkt.rsz, pkt.asz, errno, ((errno) ? strerror(errno) : "-") ); trace_return(true); } DriverNet::SyncTagType DriverNet::parseDataTag(DriverNet::ADBSYNCPKT & pkt, DriverNet::ADBSYNCDATA const & req) { tracer(); do { if (req.sz >= (UINT_MAX - 1)) { trace_break(pkt.rsz = -9); } pkt.asz = static_cast<int32_t>(req.sz); trace_info( TRACE_DBG_STR_0 ", req.sz = %u", pkt.rsz, pkt.asz, req.sz ); if (pkt.asz <= 0) { trace_break(pkt.rsz = -5); } if (pkt.rsz < 0) { trace_break(pkt.rsz = -7); } else if (pkt.rsz == 0) { trace_return(DriverNet::SyncTagType::SYNC_TAG_END); } else if (pkt.rsz <= ADBSYNCDATA_SIZE) trace_return(DriverNet::SyncTagType::SYNC_TAG_CONTINUE); pkt.rsz -= ADBSYNCDATA_SIZE; pkt.buff += ADBSYNCDATA_SIZE; trace_info( TRACE_DBG_STR_0 ", buffer offset = %d", pkt.rsz, pkt.asz, ADBSYNCDATA_SIZE ); trace_return(DriverNet::SyncTagType::SYNC_TAG_OKAY); } while (0); trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } DriverNet::SyncTagType DriverNet::parseData(SOCKET client, FILE *fpp, DriverNet::ADBSYNCPKT & pkt, bool isrecursive) { tracer(); DriverNet::ADBSYNCDATA req{}; DriverNet::SyncTagType type; if (!pkt.buff) trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); if (pkt.rsz < ADBSYNCDATA_SIZE) type = DriverNet::SyncTagType::SYNC_TAG_NONE; else { req = SyncDataFromBuff(pkt.buff); type = trace_call(SyncDataType<DriverNet::ADBSYNCDATA>, req); } trace_info( "switch -> " TRACE_DBG_STR_0 ", case = %s", pkt.rsz, pkt.asz, enumtostring(type) ); switch (type) { case DriverNet::SyncTagType::SYNC_TAG_DATA: { if ((!isrecursive) && (!sendOkay(client))) trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); type = trace_call(parseDataTag, pkt, req); if (type == DriverNet::SyncTagType::SYNC_TAG_OKAY) trace_break(0); trace_info( "warning: parseDataTag return (%s), no tagged", enumtostring(type) ); if (isrecursive) trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); trace_return(type); } case DriverNet::SyncTagType::SYNC_TAG_DONE: { pkt.rsz = pkt.asz = 0; trace_return(DriverNet::SyncTagType::SYNC_TAG_END); } case DriverNet::SyncTagType::SYNC_TAG_NONE: { if (pkt.asz <= 0) { pkt.rsz = -6; trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } if (pkt.rsz < 0) { pkt.rsz = -9; trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } else if (pkt.rsz == 0) { trace_return(DriverNet::SyncTagType::SYNC_TAG_CONTINUE); } break; } default: { trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } } trace_info( "switch -> " TRACE_DBG_STR_0 ", calc = %d", pkt.rsz, pkt.asz, (pkt.rsz - pkt.asz - ADBSYNCID_SIZE) ); if (pkt.rsz <= pkt.asz) { if (!receivedDataWrite(fpp, pkt)) trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); trace_return(DriverNet::SyncTagType::SYNC_TAG_CONTINUE); } int32_t asz = pkt.asz, rsz = (pkt.rsz - asz); pkt.rsz = asz; if (!receivedDataWrite(fpp, pkt)) trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); if ((rsz - ADBSYNCDATA_SIZE) >= 0) { pkt.rsz = rsz; pkt.asz = rsz; pkt.buff += asz; /* /// Debug last block: std::string fname("__SyncFileReceive_bin_"); fname += std::to_string(cnt++); FILE __AUTO(__autofile) * fp = ::fopen(fname.c_str(), "ab+"); fwrite(pkt.buff, 1, pkt.rsz, fp); */ return trace_call(parseData, client, fpp, pkt, true); } trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } bool DriverNet::sendOkay(SOCKET client) { tracer(); DriverNet::ADBSYNCDATA req = SyncDataMake(DriverNet::SyncTagType::SYNC_TAG_OKAY, 0U); bool ret = (::send(client, (const char*)&req, sizeof(req), 0) == static_cast<int32_t>(sizeof(req))); trace_return(ret); } bool DriverNet::receiveErrors(DriverNet::ADBSYNCPKT & pkt, std::string & rs) { # if defined(_BUILD_WARNING_0) switch (pkt.rsz) { case -1: rs = DriverNet::GetNetError(__LINE__); break; case -2: rs.assign(DriverConst::ls_errorSFR2); break; case -3: rs.assign(DriverConst::ls_errorSFR3); break; case -4: rs.assign(DriverConst::ls_errorSFR4); break; case -5: rs.assign(DriverConst::ls_errorSFR5); break; case -6: rs.assign(DriverConst::ls_errorSFR6); break; case -7: rs.assign(DriverConst::ls_errorSFR7); break; case -8: rs.assign(DriverConst::ls_errorSFR8); break; case -9: rs.assign(DriverConst::ls_errorSFR9); break; case -10: rs.assign(DriverConst::ls_errorSFR10); break; case 0: { if (pkt.asz) rs.assign(DriverConst::ls_errorSFR00); else rs.assign(DriverConst::ls_errorSFR0); break; } } # endif return !((pkt.rsz < 0) || (pkt.asz)); } }
34.222841
121
0.479652
ClnViewer
f7469e5417a8f33a50284c86f9afc5f6645c102e
828
cpp
C++
dynamic_programming/lis.cpp
fredbr/algorithm-implementations
19da93dc4632cbba91f6014e821f9b08b4e00248
[ "CC0-1.0" ]
13
2018-08-23T22:11:23.000Z
2021-06-10T04:15:09.000Z
dynamic_programming/lis.cpp
fredbr/algorithm-implementations
19da93dc4632cbba91f6014e821f9b08b4e00248
[ "CC0-1.0" ]
null
null
null
dynamic_programming/lis.cpp
fredbr/algorithm-implementations
19da93dc4632cbba91f6014e821f9b08b4e00248
[ "CC0-1.0" ]
3
2019-09-06T17:44:38.000Z
2019-09-10T12:41:35.000Z
#include <bits/stdc++.h> using namespace std; template <int sz> struct Bit { int b[sz]; void upd(int x, int val) { for (int i = x; i < sz; i += i&-i) b[i] = max(b[i], val); } int get(int x) { int ans = 0; for (int i = x; i; i -= i&-i) ans = max(ans, b[i]); return ans; } }; template <typename T> void compress(T* v, int n) { vector<T> vv(n+1); for (int i = 1; i <= n; i++) vv[i] = v[i]; sort(vv.begin()+1, vv.end()); for (int i = 1; i <= n; i++) v[i] = lower_bound(vv.begin()+1, vv.end(), v[i]) - vv.begin(); } const int maxn = 101010; int v[maxn]; Bit<maxn> bt; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) cin >> v[i]; compress(v, n); for (int i = 1; i <= n; i++) { int x = bt.get(v[i]-1); bt.upd(v[i], x+1); } int ans = bt.get(n); cout << ans << "\n"; }
13.57377
64
0.487923
fredbr
f749e3d3d41dd78a9d9ab0ab2eab30651c9d0bee
4,522
cpp
C++
Core/JPetParamAndDataFactory/JPetParamAndDataFactory.cpp
Alvarness/j-pet-framework
899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd
[ "Apache-2.0" ]
null
null
null
Core/JPetParamAndDataFactory/JPetParamAndDataFactory.cpp
Alvarness/j-pet-framework
899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd
[ "Apache-2.0" ]
null
null
null
Core/JPetParamAndDataFactory/JPetParamAndDataFactory.cpp
Alvarness/j-pet-framework
899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd
[ "Apache-2.0" ]
null
null
null
/** * @copyright Copyright 2017 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetParamAndDataFactory.cpp */ #include "./JPetParamAndDataFactory.h" namespace param_and_data_factory { JPetScin makeScin(int id, float attenLen, float length, float height, float width, JPetBarrelSlot& p_barrelSlot ) { JPetScin scinObject(id, attenLen, length, height, width); scinObject.setBarrelSlot(p_barrelSlot); return scinObject; } JPetFEB makeFEB(int p_id, bool p_isActive, const std::string& p_status, const std::string& p_description, int p_version, int p_userId, int p_n_time_outputs_per_input, int p_n_notime_outputs_per_input, JPetTRB& p_TRB) { JPetFEB objectFEB(p_id, p_isActive, p_status, p_description, p_version, p_userId, p_n_time_outputs_per_input, p_n_notime_outputs_per_input); objectFEB.setTRB(p_TRB); return objectFEB; } JPetLayer makeLayer(int id, bool isActive, const std::string& name, float radius, JPetFrame& frame) { JPetLayer objectLayer(id, isActive, name, radius); objectLayer.setFrame(frame); return objectLayer; } JPetHit makeHit(float e, float qe, float t, float qt, TVector3& pos, JPetPhysSignal& siga, JPetPhysSignal& sigb, JPetBarrelSlot& bslot, JPetScin& scin, float qtd, float td) { JPetHit hitObject(e, qe, t, qt, pos, siga, sigb, bslot, scin); hitObject.setQualityOfTimeDiff(qtd); hitObject.setTimeDiff(td); return hitObject; } JPetSigCh makeSigCh(JPetPM& pm, JPetTRB& trb, JPetFEB& feb, JPetTOMBChannel& channel, float val, JPetSigCh::EdgeType type, float thr, Int_t daqch, unsigned int threshold_number) { JPetSigCh sigChObject(type, val ); sigChObject.setPM(pm); sigChObject.setTRB(trb); sigChObject.setFEB(feb); sigChObject.setTOMBChannel(channel); sigChObject.setThreshold(thr); sigChObject.setDAQch(daqch); sigChObject.setThresholdNumber(threshold_number); return sigChObject; } JPetBarrelSlot makeBarrelSlot(JPetLayer& p_layer, int id, bool isActive, const std::string& name, float theta, int inFrameID) { JPetBarrelSlot barrelSlotObject(id, isActive, name, theta, inFrameID); barrelSlotObject.setLayer(p_layer); return barrelSlotObject; } JPetTimeWindow makeTimeWindow(const std::vector<JPetSigCh>& vec) { JPetTimeWindow timeWindowObject; for (auto sigch : vec) { timeWindowObject.add<JPetSigCh>(sigch); } return timeWindowObject; } JPetPM makePM(JPetPM::Side side, int id, int set, int opt, std::pair<float, float>& gain, std::string description, JPetFEB& p_FEB, JPetScin& p_scin, JPetBarrelSlot& p_barrelSlot) { JPetPM pmObject(side, id, set, opt, gain, description); pmObject.setFEB(p_FEB); pmObject.setScin(p_scin); pmObject.setBarrelSlot(p_barrelSlot); return pmObject; } JPetBaseSignal makeBaseSignal(JPetPM& pm, JPetBarrelSlot& bs) { JPetBaseSignal baseSignalObject; baseSignalObject.setPM(pm); baseSignalObject.setBarrelSlot(bs); return baseSignalObject; } JPetPhysSignal makePhysSignal(float time, float qualityOfTime, double phe, double qualityOfPhe, JPetRecoSignal& recoSignal) { JPetPhysSignal physSignalObject; physSignalObject.setTime(time); physSignalObject.setQualityOfTime(qualityOfTime); physSignalObject.setPhe(phe); physSignalObject.setQualityOfPhe(qualityOfPhe); physSignalObject.setRecoSignal(recoSignal); return physSignalObject; } JPetRawSignal makeRawSignal(const std::vector<JPetSigCh>& vec) { JPetRawSignal rawSignalObject(vec.size()); for (const auto& sigch : vec) { rawSignalObject.addPoint(sigch); } return rawSignalObject; } JPetTOMBChannel makeTOMBChannel(int p_channel, JPetFEB& p_FEB, JPetTRB& p_TRB, JPetPM& p_PM, float p_threshold, unsigned int lcn, unsigned int fin) { JPetTOMBChannel tombChannelObject(p_channel); tombChannelObject.setFEB(p_FEB); tombChannelObject.setTRB(p_TRB); tombChannelObject.setPM(p_PM); tombChannelObject.setThreshold(p_threshold); tombChannelObject.setLocalChannelNumber(lcn); tombChannelObject.setFEBInputNumber(fin); return tombChannelObject; } }
35.606299
216
0.776648
Alvarness
f74ea99d4c989d55cac6a245af0ad5e75f2ecb0d
3,451
cpp
C++
day3/src/p2.cpp
aeden/aoc2021
ca0e796169d5ca86f899e72d0754914445aacfb0
[ "MIT" ]
1
2021-12-01T13:08:14.000Z
2021-12-01T13:08:14.000Z
day3/src/p2.cpp
aeden/aoc2021
ca0e796169d5ca86f899e72d0754914445aacfb0
[ "MIT" ]
null
null
null
day3/src/p2.cpp
aeden/aoc2021
ca0e796169d5ca86f899e72d0754914445aacfb0
[ "MIT" ]
1
2021-12-07T21:12:57.000Z
2021-12-07T21:12:57.000Z
#include <iostream> #include <fstream> #include <string> #include <vector> #include <bitset> using namespace std; const int SAMPLE_BITS= 5; const int DATA_BITS = 12; const int BIT_LENGTH = DATA_BITS; vector<string> read_data(string filename) { ifstream infile; infile.open(filename); vector<string> data; if (infile.is_open()) { string line; while(getline(infile, line)) { data.push_back(line); } return data; } else { cout << "Failed to read data" << endl; return data; } } void print_bitsets(vector<bitset<BIT_LENGTH> > bitsets) { for (int i = 0; i < bitsets.size(); i++) { cout << bitsets[i]; if (i < bitsets.size() - 1) { cout << ","; } } cout << endl; } vector<bitset<BIT_LENGTH> > strings_to_bitsets(vector<string> data) { vector<bitset<BIT_LENGTH> > bitsets; for (int i = 0; i < data.size(); i++) { bitset<BIT_LENGTH> bits (data[i]); bitsets.push_back(bits); } return bitsets; } vector<bitset<BIT_LENGTH> > oxygen_generator_rating(int column_number, vector<bitset<BIT_LENGTH> > bitsets) { vector<bitset<BIT_LENGTH> > on; vector<bitset<BIT_LENGTH> > off; for (int i = 0; i < bitsets.size(); i++) { string bitstring = bitsets[i].to_string(); if (bitstring[column_number] == '1') { on.push_back(bitsets[i]); } else { off.push_back(bitsets[i]); } } if (on.size() > off.size()) { return on; } else if (on.size() == off.size()) { return on; } else { return off; } } vector<bitset<BIT_LENGTH> > co2_scrubber_rating(int column_number, vector<bitset<BIT_LENGTH> > bitsets) { vector<bitset<BIT_LENGTH> > on; vector<bitset<BIT_LENGTH> > off; for (int i = 0; i < bitsets.size(); i++) { string bitstring = bitsets[i].to_string(); if (bitstring[column_number] == '1') { on.push_back(bitsets[i]); } else { off.push_back(bitsets[i]); } } if (on.size() > off.size()) { return off; } else if (on.size() == off.size()) { return off; } else { return on; } } int calculate_oxygen_generator_rating(vector<string> data) { vector<bitset<BIT_LENGTH> > bitsets = strings_to_bitsets(data); cout << "Processing " << bitsets.size() << " rows for oxygen generator rating" << endl; for (int h = 0; h < BIT_LENGTH; h++) { bitsets = oxygen_generator_rating(h, bitsets); } return bitsets[0].to_ulong(); } int calculate_co2_scrubber_rating(vector<string> data) { vector<bitset<BIT_LENGTH> > bitsets = strings_to_bitsets(data); cout << "Processing " << bitsets.size() << " rows for CO2 scrubber rating" << endl; for (int h = 0; h < BIT_LENGTH; h++) { bitsets = co2_scrubber_rating(h, bitsets); } return bitsets[0].to_ulong(); } int main (int argc, char** argv) { string filename; if (argc != 2) { cout << "Usage: " << argv[0] << " datafile" << endl; return 1; } else { filename = argv[1]; } vector<string> data = read_data(filename); cout << "Loaded " << data.size() << " data lines" << endl; int oxygen_generator_rating = calculate_oxygen_generator_rating(data); int co2_scrubber_rating = calculate_co2_scrubber_rating(data); cout << "Oxygen generator rating: " << oxygen_generator_rating << endl; cout << "CO2 scrubber rating: " << co2_scrubber_rating << endl; cout << "Life support rating: " << oxygen_generator_rating * co2_scrubber_rating << endl; cout << "Done" << endl; return 0; }
24.475177
109
0.631991
aeden
f750452af42344d188eeaf8749b027c3a3cb454b
1,503
cpp
C++
src/c/basetypes/CData.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
3
2019-07-16T13:19:50.000Z
2020-01-06T10:42:23.000Z
src/c/basetypes/CData.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
15
2018-12-11T14:00:48.000Z
2021-12-21T17:42:42.000Z
src/c/basetypes/CData.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
2
2015-05-26T18:07:22.000Z
2017-04-04T10:01:17.000Z
#include "CData.h" #include "MailCore/MCCore.h" #include "CBase+Private.h" #include <typeinfo> #define nativeType mailcore::Data #define structName CData C_SYNTHESIZE_CONSTRUCTOR() C_SYNTHESIZE_COBJECT_CAST() CData CData_dataWithBytes(const char* bytes, unsigned int length) { CData result; result.instance = mailcore::Data::dataWithBytes(bytes, length); return result; } C_SYNTHESIZE_FUNC_WITH_SCALAR(const char*, bytes) C_SYNTHESIZE_FUNC_WITH_SCALAR(unsigned int, length) C_SYNTHESIZE_FUNC_WITH_VOID(destructiveDataClear) bool CData_externallyAllocatedMemory(CData self) { return self.instance->externallyAllocatedMemory(); } CBytesDeallocator CData_bytesDeallocator(CData self) { return self.instance->bytesDeallocator(); } CData Value_mailCoreTypeInfo() { return getTypeNameFromObject(&typeid(mailcore::Value)); } CData getTypeNameFromObject(CObject obj) { const std::type_info * info = &typeid(* obj.instance); return getTypeNameFromObject(info); } CData getTypeNameFromObject(const std::type_info * info) { CData result; #ifdef __LIBCPP_TYPEINFO size_t hash_value = info->hash_code(); const char* bytes = (char*)&hash_value; unsigned int length = sizeof(hash_value); result.instance = mailcore::Data::dataWithBytes(bytes, length); #else const char* bytes = info->name(); unsigned int length = (unsigned int) strlen(info->name()); result.instance = mailcore::Data::dataWithBytes(bytes, length); #endif return result; }
27.327273
67
0.754491
readdle
f754cb95c833b09b3c816ce4c13d717bb9752ab5
1,923
cpp
C++
src/device/Device.cpp
open-aquarium/open-aquarium-embedded
04470926ae052b862c87340560335032e8c30be4
[ "MIT" ]
null
null
null
src/device/Device.cpp
open-aquarium/open-aquarium-embedded
04470926ae052b862c87340560335032e8c30be4
[ "MIT" ]
1
2021-03-14T23:57:56.000Z
2021-03-14T23:57:56.000Z
src/device/Device.cpp
open-aquarium/open-aquarium-embedded
04470926ae052b862c87340560335032e8c30be4
[ "MIT" ]
null
null
null
#include "Device.h" /*Device::Device() { }*/ uint16_t Device::getFreeSRAM() { return (int) SP - (int) (__brkval == 0 ? (int)&__heap_start : (int)__brkval); } uint16_t Device::getSRAMUsage() { return this->getTotalSRAM() - this->getFreeSRAM(); } uint16_t Device::getTotalSRAM() { // return 8192; // 8 KB return (int) RAMEND - (int) &__data_start; } /*int Device::getFreeFlash() { return -1; } int Device::getFreeEEPROM() { return -1; }*/ float Device::getDeviceInbuiltTemperature() { // https://playground.arduino.cc/Main/InternalTemperatureSensor/ #if defined(__AVR_ATmega168A__) || defined(__ATmega168P__) || defined(__AVR_ATmega328__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega32U4__) unsigned int wADC; double t; // The internal temperature has to be used // with the internal reference of 1.1V. // Channel 8 can not be selected with // the analogRead function yet. // Set the internal reference and mux. ADMUX = (_BV(REFS1) | _BV(REFS0) | _BV(MUX3)); ADCSRA |= _BV(ADEN); // enable the ADC delay(20); // wait for voltages to become stable. ADCSRA |= _BV(ADSC); // Start the ADC // Detect end-of-conversion while (bit_is_set(ADCSRA,ADSC)); // Reading register "ADCW" takes care of how to read ADCL and ADCH. wADC = ADCW; // The offset of 324.31 could be wrong. It is just an indication. t = (wADC - 324.31 ) / 1.22; return t; #else return -273.15; // Absolute Zero Celcius //OA_MIN_FLOAT; //std::numeric_limits<float>::lowest(); #endif } String Device::getCPU() { return F("ATmega2560"); } uint8_t Device::getCPUSpeed() { return 16; // MHz } uint8_t Device::getAnalogIO() { return 16; } uint8_t Device::getDigitalIO() { return 54; } uint8_t Device::getDigitalPWM() { return 15; } uint16_t Device::getTotalEEPROM() { return 4096; // 4KB } uint32_t Device::getTotalFlash() { return 33554432; // 32MB }
21.852273
152
0.668747
open-aquarium
f755ba950f073011290e4045bc51832a4c1a1318
431
cpp
C++
binary_GA/binary_GA_utils.cpp
donRumata03/PowerfulGA
e4e2370287a7b654caf92adac8a64a39e23468c9
[ "MIT" ]
3
2020-04-11T10:48:01.000Z
2021-02-09T11:43:12.000Z
binary_GA/binary_GA_utils.cpp
donRumata03/PowerfulGA
e4e2370287a7b654caf92adac8a64a39e23468c9
[ "MIT" ]
6
2020-12-03T15:37:45.000Z
2020-12-09T11:02:37.000Z
binary_GA/binary_GA_utils.cpp
donRumata03/PowerfulGA
e4e2370287a7b654caf92adac8a64a39e23468c9
[ "MIT" ]
1
2021-04-25T21:50:09.000Z
2021-04-25T21:50:09.000Z
#include "binary_GA_utils.h" namespace binary_GA { population generate_population(const pms& ranges, size_t amount) { } void mutate(genome& target_genome, const vector<double>& sigmas, double target_gene_number) { } vector<vector<double>> select_matting_pool(const population& genomes, const vector<double>& fitnesses, size_t amount) { } population perform_crossover_matting(parents_t& parents) { } }
16.576923
118
0.742459
donRumata03
f756340b057918c4f1874c68657acdcd6657e851
14,521
cpp
C++
m2qt/m2qt_callback.cpp
ttuna/m2qt
614cc86765ccb2e096bf2bfbe12d03e311ec657f
[ "MIT" ]
null
null
null
m2qt/m2qt_callback.cpp
ttuna/m2qt
614cc86765ccb2e096bf2bfbe12d03e311ec657f
[ "MIT" ]
null
null
null
m2qt/m2qt_callback.cpp
ttuna/m2qt
614cc86765ccb2e096bf2bfbe12d03e311ec657f
[ "MIT" ]
null
null
null
#include "m2qt_callback.h" #include "m2qt_messageparser.h" #include <QCryptographicHash> #include <QJsonObject> #include <QTextStream> #include <QDebug> using namespace M2QT; namespace { static CallbackHelper* helper = new M2QT::CallbackHelper(); // ---------------------------------------------------------------------------- // // Handler callbacks ... // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- Response DebugOutputHandler(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; QByteArray debug_msg; QTextStream debug_stream(&debug_msg); // mongrel2 message ... debug_stream << "\n-------------------------" << endl; debug_stream << "DebugOutputHandler:\n" << endl; debug_stream << "\tuuid:" << uuid << endl; debug_stream << "\tid:" << id << endl; debug_stream << "\tpath:" << path << endl; debug_stream << "\tnetstring entries:" << net_strings.count() << endl; // json header ... debug_stream << "\n\tJson header:" << endl; QJsonObject jobj = M2QT::getJsonHeader(net_strings); QJsonObject::const_iterator iter = jobj.constBegin(); for ( ;iter!=jobj.constEnd(); ++iter ) { debug_stream << "\t\t" << left << iter.key() << ":" << iter.value().toString() << endl; } // netstring payload ... debug_stream << "\n\tPayload:" << endl; for(int i = 1; i<net_strings.size(); ++i) { debug_stream << "\t\t" << std::get<NS_SIZE>(net_strings[i]) << ":" << std::get<NS_DATA>(net_strings[i]) << endl; } debug_stream << "-------------------------" << endl; // remove \0 chars from debug_msg ... debug_msg.replace('\0', ""); helper->signalDebug(QLatin1String(debug_msg)); return Response(); } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- Response WebsocketHandshakeHandler(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; // get HEADER ... QJsonObject jobj = M2QT::getJsonHeader(net_strings); if (jobj.isEmpty()) { emit helper->signalError(QStringLiteral("WebsocketHandshakeHandler - No header available!")); return Response(); } // get SEC-WEBSOCKET-KEY ... QJsonValue val = jobj.value("sec-websocket-key"); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketHandshakeHandler - Couldn't find SEC-WEBSOCKET-KEY header!")); return Response(); } // calc SEC-WEBSOCKET-ACCEPT ... QByteArray key = val.toString().toLatin1() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; QByteArray accept = QCryptographicHash::hash(key, QCryptographicHash::Sha1).toBase64(); // TODO: consider SEC-WEBSOCKET-PROTOCOL ... (see https://tools.ietf.org/html/rfc6455#section-11.3.4) // TODO: consider SEC-WEBSOCKET-EXTENSIONS ... (see https://tools.ietf.org/html/rfc6455#section-11.3.2) // build response body ... QByteArray response_data("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: upgrade\r\nSec-WebSocket-Accept: "); response_data += accept + "\r\n\r\n"; NetString rep_id = std::make_tuple(static_cast<quint32>(id.size()), id); // build Response ... Response rep = std::make_tuple(uuid, rep_id, response_data); return rep; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- Response WebsocketCloseHandler(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; QByteArray response_data; QByteArray ws_header = M2QT::getWebSocketHeader(response_data.size(), 0x08, 0x00); response_data.prepend(ws_header); NetString rep_id = std::make_tuple(static_cast<quint32>(id.size()), id); // build Response ... Response rep = std::make_tuple(uuid, rep_id, response_data); return rep; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- Response WebsocketEchoHandler(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; QByteArray response_data; // = "HTTP/1.1 202 Accepted\r\n\r\n"; for (int i = 1; i<net_strings.size(); ++i) { response_data += std::get<NS_DATA>(net_strings[i]); } QByteArray ws_header = M2QT::getWebSocketHeader(response_data.size(), 0x01, 0x00); response_data.prepend(ws_header); NetString rep_id = std::make_tuple(static_cast<quint32>(id.size()), id); // build Response ... Response rep = std::make_tuple(uuid, rep_id, response_data); return rep; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- Response WebsocketPongHandler(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; QByteArray response_data; for (int i = 1; i<net_strings.size(); ++i) { response_data += std::get<NS_DATA>(net_strings[i]); } QByteArray ws_header = M2QT::getWebSocketHeader(response_data.size(), 0x0A, 0x00); response_data.prepend(ws_header); NetString rep_id = std::make_tuple(static_cast<quint32>(id.size()), id); // build Response ... Response rep = std::make_tuple(uuid, rep_id, response_data); return rep; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- #ifdef ENABLE_DEV_CALLBACKS Response HeavyDutyHandler(const Request &in_message) { Q_UNUSED(in_message) return Response(); } #endif // ---------------------------------------------------------------------------- // // Filter callbacks ... // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- bool WebsocketHandshakeFilter(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; // get HEADER - first NetString must be the header obj ... QJsonObject jobj = M2QT::getJsonHeader(net_strings); if (jobj.isEmpty()) { emit helper->signalError(QStringLiteral("WebsocketHandshakeFilter - No header available!")); return false; } // get METHOD ... QJsonValue val = jobj.value(QLatin1String("METHOD")); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketHandshakeFilter - Couldn't find METHOD header!")); return false; } // must be "WEBSOCKET_HANDSHAKE" ... if (val.toString() != QLatin1String("WEBSOCKET_HANDSHAKE")) return false; return true; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- bool WebsocketCloseFilter(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; // get HEADER - first NetString must be the header obj ... QJsonObject jobj = M2QT::getJsonHeader(net_strings); if (jobj.isEmpty()) { emit helper->signalError(QStringLiteral("WebsocketCloseFilter - No header available!")); return false; } // get METHOD ... QJsonValue val = jobj.value(QLatin1String("METHOD")); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketCloseFilter - Couldn't find METHOD header!")); return false; } // must be "WEBSOCKET" ... if (val.toString() != QLatin1String("WEBSOCKET")) return false; // get FLAGS ... val = jobj.value(QLatin1String("FLAGS")); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketCloseFilter - Couldn't find FLAGS header!")); return false; } // req opcode must be 0x08 = close frame ... bool ok = false; quint8 value = val.toString().toInt(&ok, 16); if (ok == false || value == 0x0 || (value^(1<<7)) != 0x08) return false; return true; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- bool WebsocketEchoFilter(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; // get HEADER - first NetString must be the header obj ... QJsonObject jobj = M2QT::getJsonHeader(net_strings); if (jobj.isEmpty()) { emit helper->signalError(QStringLiteral("WebsocketEchoFilter - No header available!")); return false; } // get METHOD ... QJsonValue val = jobj.value(QLatin1String("METHOD")); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketEchoFilter - Couldn't find METHOD header!")); return false; } // must be "WEBSOCKET" ... if (val.toString() != QLatin1String("WEBSOCKET")) return false; // get FLAGS ... val = jobj.value(QLatin1String("FLAGS")); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketEchoFilter - Couldn't find FLAGS header!")); return false; } // req opcode must be 0x01 = text frame ... bool ok = false; quint8 value = val.toString().toInt(&ok, 16); if (ok == false || value == 0x0 || (value^(1<<7)) != 0x01) return false; return true; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- bool WebsocketPongFilter(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; // get HEADER - first NetString must be the header obj ... QJsonObject jobj = M2QT::getJsonHeader(net_strings); if (jobj.isEmpty()) { emit helper->signalError(QStringLiteral("WebsocketPongFilter - No header available!")); return false; } // get METHOD ... QJsonValue val = jobj.value(QLatin1String("METHOD")); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketPongFilter - Couldn't find METHOD header!")); return false; } // must be "WEBSOCKET" ... if (val.toString() != QLatin1String("WEBSOCKET")) return false; // get FLAGS ... val = jobj.value(QLatin1String("FLAGS")); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketPongFilter - Couldn't find FLAGS header!")); return false; } // req opcode must be 0x09 = ping frame ... bool ok = false; quint8 value = val.toString().toInt(&ok, 16); if (ok == false || value == 0x0 || (value^(1<<7)) != 0x09) return false; return true; } } // namespace namespace M2Qt { const QString DEBUG_OUTPUT_NAME = "debug_output"; const QString WS_HANDSHAKE_NAME = "websocket_handshake"; const QString WS_CLOSE_NAME = "websocket_close"; const QString WS_ECHO_NAME = "websocket_echo"; const QString WS_PONG_NAME = "websocket_pong"; const QString HEAVY_DUTY_NAME = "heavy_duty"; } // ---------------------------------------------------------------------------- // // class CallbackManager // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // handler callback names and filter callback names must correspond if they have to work together ... // ---------------------------------------------------------------------------- QMap<QString, HandlerCallback> CallbackManager::m_handler_callback_map = { { M2Qt::DEBUG_OUTPUT_NAME, &DebugOutputHandler }, { M2Qt::WS_HANDSHAKE_NAME, &WebsocketHandshakeHandler }, { M2Qt::WS_CLOSE_NAME, &WebsocketCloseHandler }, { M2Qt::WS_ECHO_NAME, &WebsocketEchoHandler }, { M2Qt::WS_PONG_NAME, &WebsocketPongHandler }, #ifdef ENABLE_DEV_CALLBACKS { M2Qt::HEAVY_DUTY_NAME, &HeavyDutyHandler }, #endif }; QMap<QString, FilterCallback> CallbackManager::m_filter_callback_map = { { M2Qt::WS_HANDSHAKE_NAME, &WebsocketHandshakeFilter }, { M2Qt::WS_CLOSE_NAME, &WebsocketCloseFilter }, { M2Qt::WS_ECHO_NAME, &WebsocketEchoFilter }, { M2Qt::WS_PONG_NAME, &WebsocketPongFilter }, }; // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- CallbackManager::CallbackManager(QObject *parent) : QObject(parent) { m_p_static_cb_helper = helper; if (m_p_static_cb_helper != nullptr) { connect(m_p_static_cb_helper, &CallbackHelper::signalError, this, &CallbackManager::signalError); connect(m_p_static_cb_helper, &CallbackHelper::signalWarning, this, &CallbackManager::signalWarning); connect(m_p_static_cb_helper, &CallbackHelper::signalDebug, this, &CallbackManager::signalDebug); connect(m_p_static_cb_helper, &CallbackHelper::signalInfo, this, &CallbackManager::signalInfo); } } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- HandlerCallback CallbackManager::getHandlerCallback(const QString &in_name) { return m_handler_callback_map.value(in_name, nullptr); } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- FilterCallback CallbackManager::getFilterCallback(const QString &in_name) { return m_filter_callback_map.value(in_name, nullptr); }
38.930295
162
0.547621
ttuna
f75df7015a3e5ca381fb59d593d466148d724304
692
cpp
C++
Leetcode_challenges/Day15/canSquare.cpp
vishwajeet-hogale/LearnSTL
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
[ "MIT" ]
null
null
null
Leetcode_challenges/Day15/canSquare.cpp
vishwajeet-hogale/LearnSTL
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
[ "MIT" ]
null
null
null
Leetcode_challenges/Day15/canSquare.cpp
vishwajeet-hogale/LearnSTL
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
[ "MIT" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> using namespace std; bool getSets(vector<int> &nums,vector<int> &r,int i){ if(i == nums.size()){ return !r[0] && !r[1] && !r[2] && !r[3]; } for(int j=0;j<r.size();j++){ r[j] -= nums[i]; if(getSets(nums,r,i+1)){ return true; } r[j] += nums[i]; } return false; } bool makesquare(vector<int> &nums){ int sum = 0; for(int i:nums) sum += i; if(sum % 4 == 0){ vector<int> r(4,sum/4); return getSets(nums,r,0); } return false; } int main(){ vector<int> nums({1,1,2,2,1}); cout<<makesquare(nums)<<endl; return 0; }
20.352941
53
0.479769
vishwajeet-hogale
f766180031763498659c8b4c461d6bad09bcfd61
3,079
cpp
C++
bridge/runtime/src/main/native/jni/InputReaderMirrorImpl.cpp
asakusafw/asakusafw-m3bp
ffb811da0055ff75f13e73ee4eedb261a46988e0
[ "Apache-2.0" ]
1
2016-12-13T07:50:36.000Z
2016-12-13T07:50:36.000Z
bridge/runtime/src/main/native/jni/InputReaderMirrorImpl.cpp
asakusafw/asakusafw-m3bp
ffb811da0055ff75f13e73ee4eedb261a46988e0
[ "Apache-2.0" ]
153
2016-04-01T08:20:15.000Z
2022-02-09T22:30:46.000Z
bridge/runtime/src/main/native/jni/InputReaderMirrorImpl.cpp
asakusafw/asakusafw-m3bp
ffb811da0055ff75f13e73ee4eedb261a46988e0
[ "Apache-2.0" ]
6
2016-04-01T07:31:57.000Z
2017-03-17T03:15:47.000Z
/* * Copyright 2011-2021 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl.h" #include "mirror.hpp" #include "jniutil.hpp" using namespace asakusafw::jni; /* * Class: com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl * Method: hasKey0 * Signature: (J)Z */ JNIEXPORT jboolean JNICALL Java_com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_hasKey0 (JNIEnv *env, jclass, jlong _self) { try { auto* self = reinterpret_cast<InputReaderMirror*>(_self); return self->has_key(); } catch (JavaException &e) { e.rethrow(env); return false; } catch (std::exception &e) { handle_native_exception(env, e); return false; } } /* * Class: com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl * Method: getInputBufferFragment0 * Signature: (JZ[J)V */ JNIEXPORT void JNICALL Java_com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_getInputBufferFragment0 (JNIEnv *env, jclass, jlong _self, jboolean is_key, jlongArray results) { try { auto* self = reinterpret_cast<InputReaderMirror*>(_self); jlong array[com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_VALUES_SIZE]; std::tuple<const void *, const void *, m3bp::size_type> buffer; if (is_key) { buffer = self->key_buffer(); } else { buffer = self->value_buffer(); } array[com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_INDEX_BUFFER_PTR] = to_pointer(std::get<0>(buffer)); array[com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_INDEX_OFFSET_TABLE_PTR] = to_pointer(std::get<1>(buffer)); array[com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_INDEX_RECORD_COUNT] = static_cast<jlong>(std::get<2>(buffer)); env->SetLongArrayRegion(results, 0, com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_VALUES_SIZE, &array[0]); } catch (JavaException &e) { e.rethrow(env); } catch (std::exception &e) { handle_native_exception(env, e); } } /* * Class: com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl * Method: close0 * Signature: (J)V */ JNIEXPORT void JNICALL Java_com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_close0 (JNIEnv *env, jclass, jlong _self) { try { auto* self = reinterpret_cast<InputReaderMirror*>(_self); delete self; } catch (JavaException &e) { e.rethrow(env); } catch (std::exception &e) { handle_native_exception(env, e); } }
36.654762
128
0.713868
asakusafw
f768e730e3f441c605bfca00f3f57825f33554f4
2,691
cpp
C++
src/vectorMagnitudeDirection.cpp
D-K-E/udacity-linear-algebra
8494440627a48ca13e1d2ec166cb1939639155e0
[ "MIT" ]
null
null
null
src/vectorMagnitudeDirection.cpp
D-K-E/udacity-linear-algebra
8494440627a48ca13e1d2ec166cb1939639155e0
[ "MIT" ]
null
null
null
src/vectorMagnitudeDirection.cpp
D-K-E/udacity-linear-algebra
8494440627a48ca13e1d2ec166cb1939639155e0
[ "MIT" ]
null
null
null
/* Vector Operations Program Author: Kaan Purpose: Implement addition, subtraction, and scalar multiplication Usage: Run the program, enter the vectors. */ // Declare Packages ------------ #include <vector> #include <iostream> #include <assert.h> #include <math.h> // End of Declare Packages ----- // Functions ------------------- void print_vector(std::vector<double> vector_print){ int v_size; v_size = vector_print.size(); for(int i=0; i<v_size; i++){ std::cout << vector_print[i] << ", "; } std::cout << "\n"; } std::vector<double> vector_scalar_multiplication(std::vector<double> scaled_vector, double scalar, int vector_size){ std::vector<double> result_vector; for(int i=0; i<vector_size; i++){ double multiplication_result; multiplication_result = scaled_vector[i] * scalar; result_vector.push_back(multiplication_result); } return(result_vector); } double vector_magnitude(const std::vector<double> input_vector, int vector_size){ double magnitude;// stores the magnitude of the vector for(int i=0; i < vector_size; i++){ magnitude += pow(input_vector[i], 2.0); } magnitude = sqrt(magnitude); return(magnitude); } std::vector<double> vector_normaliser(std::vector<double> input_vector, int vector_size){ double scalar; // stores the magnitude of the vector double vec_magnitude; vec_magnitude = vector_magnitude(input_vector, vector_size); scalar = 1 / vec_magnitude; // std::vector<double> result_vector; result_vector = vector_scalar_multiplication(input_vector, scalar, vector_size); return(result_vector); } int main(){ // input vector double input; // input value which would be taken from the user std::cout << "Enter your numbers to be taken to the vector and 2.2 to quit: " << std::endl; std::vector<double> vector_1; // First vector for operations input = 0.2; while(input != -4.554){ std::cin >> input; vector_1.push_back(input); } int vec_size; // store the vector size vec_size = vector_1.size(); int vector_mag; // stores vector magnitude std::vector<double> norm_vector; // stores the unit vector vector_mag = vector_magnitude(vector_1, vec_size); norm_vector = vector_normaliser(vector_1, vec_size); std::cout << "Vector Magnitude: " << vector_mag << "\n" << "Unit Vector: " << std::endl; print_vector(norm_vector); return(0); }
28.935484
83
0.616128
D-K-E
f76ad5a740f87e4d795898f335907769b4d51388
945
cpp
C++
src/standard-release/commits/iconventional.cpp
Symbitic/standard-release
335cc62979be076f50c311336bb954fe0adc71c9
[ "MIT" ]
null
null
null
src/standard-release/commits/iconventional.cpp
Symbitic/standard-release
335cc62979be076f50c311336bb954fe0adc71c9
[ "MIT" ]
null
null
null
src/standard-release/commits/iconventional.cpp
Symbitic/standard-release
335cc62979be076f50c311336bb954fe0adc71c9
[ "MIT" ]
null
null
null
#include "iconventional.h" /* https://www.npmjs.com/package/conventional-changelog-writer */ using namespace StandardRelease; IConventionalCommit::IConventionalCommit() : m_valid(false) , m_error() , m_commits() , m_semver() { } IConventionalCommit::~IConventionalCommit() {} void IConventionalCommit::setVersion(const SemVer &semver) { m_semver = semver; } SemVer IConventionalCommit::version() const { return m_semver; } void IConventionalCommit::setValid(bool valid) { m_valid = valid; } void IConventionalCommit::setError(const Error error) { m_error = error; } void IConventionalCommit::setCommits(const IConventionalCommit::Commits commits) { m_commits = commits; } IConventionalCommit::Commits IConventionalCommit::commits() const { return m_commits; } bool IConventionalCommit::isValid() const { return m_valid; } Error IConventionalCommit::error() const { return m_error; }
17.830189
82
0.731217
Symbitic
f7738133bf9137aae741ad00a0af999d084ecfdb
28,509
cpp
C++
StarEngine/jni/Helpers/Helpers.cpp
madhubandubey9/StarEngine
1d0adcf8cfd50bc223be6f333c4f2a0af5260b27
[ "MIT" ]
455
2015-02-04T01:39:12.000Z
2022-03-18T17:28:34.000Z
StarEngine/jni/Helpers/Helpers.cpp
madhubandubey9/StarEngine
1d0adcf8cfd50bc223be6f333c4f2a0af5260b27
[ "MIT" ]
1
2016-12-25T09:14:12.000Z
2016-12-25T14:48:27.000Z
StarEngine/jni/Helpers/Helpers.cpp
madhubandubey9/StarEngine
1d0adcf8cfd50bc223be6f333c4f2a0af5260b27
[ "MIT" ]
117
2015-01-30T10:13:54.000Z
2022-03-08T03:46:42.000Z
#include "Helpers.h" #include "..\Logger.h" #include "FilePath.h" #include <iostream> #include <fstream> #include <string> #include <locale> #include <clocale> #include <vector> #ifdef _WIN32 #include <windows.h> #endif #ifdef ANDROID #include "HelpersAndroid.h" #include "../StarEngine.h" #endif namespace star { const uint32 GenerateHash(const tstring & str) { uint32 hash(0); for(size_t i = 0; i < str.size(); ++i) { hash = 65599 * hash + str[i]; } return hash ^ (hash >> 16); } void LaunchWebpage(const tstring & page) { #ifdef _WIN32 ShellExecute(NULL, _T("open"), page.c_str(), NULL, NULL, SW_SHOWNORMAL); #endif } tstring GetFileName(const tstring & path) { auto index = path.find_last_of('/'); if(index == tstring::npos) { index = path.find_last_of('\\'); } if(index != tstring::npos) { index += 1; return path.substr(index, path.length() - index); } return path; } template <> sstring_16 string_cast<sstring_16, sstring_16> (const sstring_16 & value) { return value; } template <> sstring_16 string_cast<sstring_16, swstring> (const swstring & value) { sstring_16 str(value.begin(), value.end()); return str; } template <> sstring_16 string_cast<sstring_16, sstring> (const sstring & value) { sstring_16 str(value.begin(), value.end()); return str; } template <> swstring string_cast<swstring, sstring_16> (const sstring_16 & value) { swstring str(value.begin(), value.end()); return str; } template <> sstring string_cast<sstring, sstring_16> (const sstring_16 & value) { sstring str(value.begin(), value.end()); return str; } template <> swstring string_cast<swstring, swstring> (const swstring & value) { return value; } template <> sstring string_cast<sstring, sstring> (const sstring & value) { return value; } template <> sstring string_cast<sstring, swstring> (const swstring & value) { sstring str(value.begin(), value.end()); return str; } template <> swstring string_cast<swstring, sstring> (const sstring & value) { swstring str(value.begin(), value.end()); return str; } template <> sstring_16 string_cast<sstring_16, schar_16> (const schar_16 * value) { return sstring_16(value); } template <> sstring_16 string_cast<sstring_16, swchar> (const swchar * value) { return string_cast<sstring_16, swstring>(value); } template <> sstring_16 string_cast<sstring_16, schar> (const schar * value) { return string_cast<sstring_16, sstring>(value); } template <> schar_16 * string_cast<schar_16*, sstring_16> (const sstring_16 & value) { schar_16 * cstr = const_cast<schar_16*>( value.c_str() ); return cstr; } template <> swchar * string_cast<swchar*, sstring_16> (const sstring_16 & value) { swchar * cstr = const_cast<swchar*>( string_cast<swstring, sstring_16>( value ).c_str() ); return cstr; } template <> schar * string_cast<schar*, sstring_16> (const sstring_16 & value) { schar * cstr = const_cast<schar*>( string_cast<sstring, sstring_16>( value ).c_str() ); return cstr; } template <> sstring string_cast<sstring, schar_16> (const schar_16 * value) { return string_cast<sstring, sstring_16>(value); } template <> swstring string_cast<swstring, schar_16> (const schar_16 * value) { return string_cast<swstring, sstring_16>(value); } template <> schar_16* string_cast<schar_16*, sstring> (const sstring & value) { schar_16 * cstr = const_cast<schar_16*>( string_cast<sstring_16, sstring>(value).c_str() ); return cstr; } template <> schar_16* string_cast<schar_16*, swstring> (const swstring & value) { schar_16 * cstr = const_cast<schar_16*>( string_cast<sstring_16, swstring>(value).c_str() ); return cstr; } template <> swstring string_cast<swstring, swchar> (const swchar * value) { return string_cast<swstring, swstring>(value); } template <> sstring string_cast<sstring, schar> (const schar * value) { return string_cast<sstring, sstring>(value); } template <> sstring string_cast<sstring, swchar> (const swchar * value) { return string_cast<sstring, swstring>(value); } template <> swstring string_cast<swstring, schar> (const schar * value) { return string_cast<swstring, sstring>(value); } template <> schar* string_cast<schar*, swstring> (const swstring & value) { schar * result = const_cast<schar*>( string_cast<sstring, swstring>(value).c_str() ); return result; } template <> schar* string_cast<schar*, sstring> (const sstring & value) { schar * result = const_cast<schar*>(value.c_str()); return result; } template <> swchar* string_cast<swchar*, swstring> (const swstring & value) { swchar * result = const_cast<swchar*>(value.c_str()); return result; } template <> swchar* string_cast<swchar*, sstring> (const sstring & value) { swchar * result = const_cast<swchar*>( string_cast<swstring, sstring>(value).c_str() ); return result; } template <> swchar* string_cast<swchar*, schar> (const schar * value) { return string_cast<swchar*>( sstring(value) ); } template <> swchar* string_cast<swchar*, swchar> (const swchar * value) { return const_cast<swchar*>(value); } template <> schar* string_cast<schar*, swchar> (const swchar * value) { return string_cast<schar*>( swstring(value) ); } template <> schar* string_cast<schar*, schar> (const schar * value) { return const_cast<schar*>(value); } template <> schar_16* string_cast<schar_16*, schar> (const schar * value) { return string_cast<schar_16*, sstring>(value); } template <> schar_16* string_cast<schar_16*, swchar> (const swchar * value) { return string_cast<schar_16*, swstring>(value); } template <> schar* string_cast<schar*, schar_16> (const schar_16 * value) { return string_cast<schar*, sstring_16>(value); } template <> swchar* string_cast<swchar*, schar_16> (const schar_16 * value) { return string_cast<swchar*, sstring_16>(value); } template <> tstring string_cast<tstring, fvec2> (const fvec2 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y; return strstr.str(); } template <> tstring string_cast<tstring, pos> (const pos & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.l; return strstr.str(); } template <> tstring string_cast<tstring, fvec3> (const fvec3 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z; return strstr.str(); } template <> tstring string_cast<tstring, fvec4> (const fvec4 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z << _T(";"); strstr << value.w; return strstr.str(); } template <> tstring string_cast<tstring, fquat> (const fquat & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z << _T(";"); strstr << value.w; return strstr.str(); } template <> tstring string_cast<tstring, dvec2> (const dvec2 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y; return strstr.str(); } template <> tstring string_cast<tstring, dvec3> (const dvec3 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z; return strstr.str(); } template <> tstring string_cast<tstring, dvec4> (const dvec4 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z << _T(";"); strstr << value.w; return strstr.str(); } template <> tstring string_cast<tstring, dquat> (const dquat & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z << _T(";"); strstr << value.w; return strstr.str(); } template <> tstring string_cast<tstring, ivec2> (const ivec2 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y; return strstr.str(); } template <> tstring string_cast<tstring, ivec3> (const ivec3 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z; return strstr.str(); } template <> tstring string_cast<tstring, ivec4> (const ivec4 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z << _T(";"); strstr << value.w; return strstr.str(); } template <> tstring string_cast<tstring, uvec2> (const uvec2 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y; return strstr.str(); } template <> tstring string_cast<tstring, uvec3> (const uvec3 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z; return strstr.str(); } template <> tstring string_cast<tstring, uvec4> (const uvec4 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z << _T(";"); strstr << value.w; return strstr.str(); } template <> tstring string_cast<tstring, Color> (const Color & value) { tstringstream strstr; strstr << value.r << _T(";"); strstr << value.g << _T(";"); strstr << value.b << _T(";"); strstr << value.a; return strstr.str(); } template <> bool string_cast<bool, tstring> (const tstring & value) { tstring val(value); transform(val.begin(), val.end(), val.begin(), ::tolower); return val[0] == _T('t'); } template <> int32 string_cast<int32, tstring> (const tstring & value) { return ttoi(value.c_str()); } template <> uint32 string_cast<uint32, tstring> (const tstring & value) { return uint32(string_cast<int32>(value)); } template <> long string_cast<long, tstring> (const tstring & value) { return static_cast<long>(ttoi(value.c_str())); } template <> float32 string_cast<float32, tstring> (const tstring & value) { return static_cast<float32>(ttof(value.c_str())); } template <> float64 string_cast<float64, tstring> (const tstring & value) { return ttof(value.c_str()); } template <> fvec2 string_cast<fvec2, tstring> (const tstring & value) { fvec2 vec; int32 index = value.find(';',0); vec.x = string_cast<float32>(value.substr(0, index)); vec.y = string_cast<float32>(value.substr(++index,value.size()-index)); return vec; } template <> pos string_cast<pos, tstring> (const tstring & value) { pos pos; int32 index = value.find(';', 0); pos.x = string_cast<float32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); pos.y = string_cast<float32>(value.substr(index, index2 - index)); pos.l = lay(string_cast<int32>(value.substr(++index2, value.size() - index2))); return pos; } template <> fvec3 string_cast<fvec3, tstring> (const tstring & value) { fvec3 vec; int32 index = value.find(';', 0); vec.x = string_cast<float32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<float32>(value.substr(index, index2 - index)); vec.z = string_cast<float32>(value.substr(++index2, value.size() - index2)); return vec; } template <> fvec4 string_cast<fvec4, tstring> (const tstring & value) { fvec4 vec; int32 index = value.find(';', 0); vec.x = string_cast<float32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<float32>(value.substr(index, index2 - index)); index = value.find(';', ++index2); vec.z = string_cast<float32>(value.substr(index2, index - index2)); vec.w = string_cast<float32>(value.substr(++index, value.size() - index)); return vec; } template <> fquat string_cast<fquat, tstring> (const tstring & value) { fquat quat; int32 index = value.find(';', 0); quat.x = string_cast<float32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); quat.y = string_cast<float32>(value.substr(index, index2 - index)); index = value.find(';', ++index2); quat.z = string_cast<float32>(value.substr(index2, index - index2)); quat.w = string_cast<float32>(value.substr(++index, value.size() - index)); return quat; } template <> dvec2 string_cast<dvec2, tstring> (const tstring & value) { dvec2 vec; int32 index = value.find(';', 0); vec.x = string_cast<float64>(value.substr(0, index)); vec.y = string_cast<float64>(value.substr(++index, value.size() - index)); return vec; } template <> dvec3 string_cast<dvec3, tstring> (const tstring & value) { dvec3 vec; int32 index = value.find(';', 0); vec.x = string_cast<float64>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<float64>(value.substr(index, index2 - index)); vec.z = string_cast<float64>(value.substr(++index2, value.size() - index2)); return vec; } template <> dvec4 string_cast<dvec4, tstring> (const tstring & value) { dvec4 vec; int32 index = value.find(';', 0); vec.x = string_cast<float64>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<float64>(value.substr(index, index2 - index)); index = value.find(';', ++index2); vec.z = string_cast<float64>(value.substr(index2, index - index2)); vec.w = string_cast<float64>(value.substr(++index, value.size() - index)); return vec; } template <> dquat string_cast<dquat, tstring> (const tstring & value) { dquat quat; int32 index = value.find(';', 0); quat.x = string_cast<float64>(value.substr(0, index)); int32 index2 = value.find(';', ++index); quat.y = string_cast<float64>(value.substr(index, index2 - index)); index = value.find(';', ++index2); quat.z = string_cast<float64>(value.substr(index2, index - index2)); quat.w = string_cast<float64>(value.substr(++index, value.size() - index)); return quat; } template <> ivec2 string_cast<ivec2, tstring> (const tstring & value) { ivec2 vec; int32 index = value.find(';', 0); vec.x = string_cast<int32>(value.substr(0, index)); vec.y = string_cast<int32>(value.substr(++index ,value.size() - index)); return vec; } template <> ivec3 string_cast<ivec3, tstring> (const tstring & value) { ivec3 vec; int32 index = value.find(';', 0); vec.x = string_cast<int32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<int32>(value.substr(index, index2 - index)); vec.z = string_cast<int32>(value.substr(++index2, value.size() - index2)); return vec; } template <> ivec4 string_cast<ivec4, tstring> (const tstring & value) { ivec4 vec; int32 index = value.find(';', 0); vec.x = string_cast<int32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<int32>(value.substr(index, index2 - index)); index = value.find(';', ++index2); vec.z = string_cast<int32>(value.substr(index2, index - index2)); vec.w = string_cast<int32>(value.substr(++index, value.size() - index)); return vec; } template <> uvec2 string_cast<uvec2, tstring> (const tstring & value) { uvec2 vec; int32 index = value.find(';', 0); vec.x = string_cast<uint32>(value.substr(0, index)); vec.y = string_cast<uint32>(value.substr(++index, value.size() - index)); return vec; } template <> uvec3 string_cast<uvec3, tstring> (const tstring & value) { uvec3 vec; int32 index = value.find(';', 0); vec.x = string_cast<uint32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<uint32>(value.substr(index, index2 - index)); vec.z = string_cast<uint32>(value.substr(++index2, value.size() - index2)); return vec; } template <> uvec4 string_cast<uvec4, tstring> (const tstring & value) { uvec4 vec; int32 index = value.find(';', 0); vec.x = string_cast<uint32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<uint32>(value.substr(index, index2 - index)); index = value.find(';', ++index2); vec.z = string_cast<uint32>(value.substr(index2, index - index2)); vec.w = string_cast<uint32>(value.substr(++index, value.size() - index)); return vec; } template <> Color string_cast<Color, tstring> (const tstring & value) { Color color; int32 index = value.find(';', 0); color.r = string_cast<float32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); color.g = string_cast<float32>(value.substr(index, index2 - index)); index = value.find(';', ++index2); color.b = string_cast<float32>(value.substr(index2, index - index2)); color.a = string_cast<float32>(value.substr(++index, value.size() - index)); return color; } void ReadTextFile(const tstring & file, tstring & text, DirectoryMode directory) { FilePath file_path = FilePath(file, directory); #ifdef ANDROID if(directory == DirectoryMode::assets) { SerializedData data; star_a::ReadFileAsset(file, data); text = string_cast<tstring>(data.data); delete [] data.data; } else { text = _T(""); sifstream myfile; myfile.open(string_cast<sstring>(file_path.GetFullPath()), std::ios::in); ASSERT_LOG(myfile.is_open(), _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); sstring str; while (std::getline(myfile, str)) { text += str; } myfile.close(); } #else tifstream myfile; myfile.open(file_path.GetFullPath(), std::ios::in); ASSERT_LOG(myfile.is_open(), _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); tstring str; while (std::getline(myfile,str)) { text += str; } myfile.close(); #endif text += _T('\0'); } bool ReadTextFileSafe(const tstring & file, tstring & text, DirectoryMode directory, bool logWarning) { FilePath file_path = FilePath(file, directory); bool succes(false); #ifdef ANDROID if(directory == DirectoryMode::assets) { SerializedData data; succes = star_a::ReadFileAssetSafe(file, data, logWarning); if(succes) { text = string_cast<tstring>(data.data); delete [] data.data; } else { text = EMPTY_STRING; } return succes; } else { text = EMPTY_STRING; sifstream myfile; myfile.open(string_cast<sstring>(file_path.GetFullPath()), std::ios::in); succes = myfile.is_open(); if(succes) { sstring str; while (std::getline(myfile,str)) { text += str; } myfile.close(); } else if(logWarning) { LOG(LogLevel::Warning, _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); } } #else tifstream myfile; myfile.open(file_path.GetFullPath(), std::ios::in); succes = myfile.is_open(); if(succes) { tstring str; while (std::getline(myfile,str)) { text += str; } myfile.close(); } else if(logWarning) { LOG(LogLevel::Warning, _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); } #endif text += _T('\0'); return succes; } tstring ReadTextFile(const tstring & file, DirectoryMode directory) { tstring text; ReadTextFile(file, text, directory); return text; } void WriteTextFile(const tstring & file, const tstring & text, DirectoryMode directory) { FilePath file_path = FilePath(file, directory); #ifdef ANDROID ASSERT_LOG(directory != DirectoryMode::assets, _T("Android doesn't support writing to a text file in the assets directory."), STARENGINE_LOG_TAG); sofstream myfile(string_cast<sstring>(file_path.GetFullPath()), std::ios::out); ASSERT_LOG(myfile.is_open(), _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); myfile << text; myfile.close(); #else tofstream myfile(file_path.GetFullPath(), std::ios::out); ASSERT_LOG(myfile.is_open(), _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); myfile << text; myfile.close(); #endif } void AppendTextFile(const tstring & file, const tstring & text, DirectoryMode directory) { FilePath file_path = FilePath(file, directory); #ifdef ANDROID ASSERT_LOG(directory != DirectoryMode::assets, _T("Android doesn't support writing to a text file in the assets directory."), STARENGINE_LOG_TAG); sofstream myfile(string_cast<sstring>(file_path.GetFullPath()), std::ios::out | std::ios::app); ASSERT_LOG(myfile.is_open(), _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); myfile << text; myfile.close(); #else tofstream myfile(file_path.GetFullPath(), std::ios::out | std::ios::app); ASSERT_LOG(myfile.is_open(), _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); myfile << text; myfile.close(); #endif } schar * ReadBinaryFile(const tstring & file, uint32 & size, DirectoryMode directory) { FilePath file_path = FilePath(file, directory); #ifdef ANDROID if(directory == DirectoryMode::assets) { SerializedData data; star_a::ReadFileAsset(file, data); size = data.size; return data.data; } else { sifstream binary_file; binary_file.open(string_cast<sstring>(file_path.GetFullPath()).c_str(), std::ios::in | std::ios::binary | std::ios::ate); ASSERT_LOG(binary_file.is_open(), _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); schar * buffer(nullptr); size = uint32(binary_file.tellg()); buffer = new schar[size]; binary_file.seekg(0, std::ios::beg); binary_file.read(buffer, sizeof(schar) * size); binary_file.close(); return buffer; } #else sifstream binary_file; binary_file.open(file_path.GetFullPath(), std::ios::in | std::ios::binary | std::ios::ate); ASSERT_LOG(binary_file.is_open(), _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); schar * buffer(nullptr); size = uint32(binary_file.tellg()); buffer = new schar[size]; binary_file.seekg(0, std::ios::beg); binary_file.read(buffer, sizeof(schar) * size); binary_file.close(); return buffer; #endif } bool ReadBinaryFileSafe(const tstring & file, schar *& buffer, uint32 & size, DirectoryMode directory, bool logWarning) { FilePath file_path = FilePath(file, directory); #ifdef ANDROID if(directory == DirectoryMode::assets) { SerializedData data; bool result = star_a::ReadFileAssetSafe(file, data, logWarning); size = data.size; buffer = data.data; return result; } else { sifstream binary_file; binary_file.open(string_cast<sstring>(file_path.GetFullPath()).c_str(), std::ios::in | std::ios::binary | std::ios::ate); bool succes = binary_file.is_open(); if (succes) { size = uint32(binary_file.tellg()); buffer = new schar[size]; binary_file.seekg(0, std::ios::beg); binary_file.read(buffer, sizeof(schar) * size); binary_file.close(); } else if(logWarning) { LOG(LogLevel::Warning, _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); } return succes; } #else sifstream binary_file; binary_file.open(file_path.GetFullPath(), std::ios::in | std::ios::binary | std::ios::ate); bool succes = binary_file.is_open(); if (succes) { size = uint32(binary_file.tellg()); buffer = new schar[size]; binary_file.seekg(0, std::ios::beg); binary_file.read(buffer, sizeof(schar) * size); binary_file.close(); } else if(logWarning) { LOG(LogLevel::Warning, _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); } return succes; #endif } void WriteBinaryFile(const tstring & file, schar * buffer, uint32 size, DirectoryMode directory) { FilePath file_path = FilePath(file, directory); #ifdef ANDROID ASSERT_LOG(directory != DirectoryMode::assets, _T("Android doesn't support writing to a binary file in the assets directory."), STARENGINE_LOG_TAG); sofstream binary_file; binary_file.open(string_cast<sstring>(file_path.GetFullPath()), std::ios::binary | std::ios::trunc); ASSERT_LOG(binary_file.is_open(), _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); for(uint32 i = 0 ; i < size ; ++i) { binary_file << buffer[i]; } binary_file.close(); #else sofstream binary_file; binary_file.open(file_path.GetFullPath(), std::ios::binary | std::ios::trunc); ASSERT_LOG(binary_file.is_open(), _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); for(uint32 i = 0 ; i < size ; ++i) { binary_file << buffer[i]; } binary_file.close(); #endif } void AppendBinaryFile(const tstring & file, schar * buffer, uint32 size, DirectoryMode directory) { FilePath file_path = FilePath(file, directory); #ifdef ANDROID ASSERT_LOG(directory != DirectoryMode::assets, _T("Android doesn't support writing to a binary file in the assets directory."), STARENGINE_LOG_TAG); sofstream binary_file(string_cast<sstring>(file_path.GetFullPath()), std::ios::out | std::ios::binary | std::ios::app); ASSERT_LOG(binary_file.is_open(), _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); for(uint32 i = 0 ; i < size ; ++i) { binary_file << buffer[i]; } binary_file.close(); #else sofstream binary_file(file_path.GetFullPath(), std::ios::out | std::ios::binary | std::ios::app); ASSERT_LOG(binary_file.is_open(), _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); for(uint32 i = 0 ; i < size ; ++i) { binary_file << buffer[i]; } binary_file.close(); #endif } schar * DecryptBinaryFile(const tstring & file, uint32 & size, const std::function<schar*(const schar*, uint32&)> & decrypter, DirectoryMode directory) { schar * buffer = ReadBinaryFile(file, size, directory); schar * decryptedBuffer = decrypter(buffer, size); delete [] buffer; return decryptedBuffer; } bool DecryptBinaryFileSafe(const tstring & file, schar *& buffer, uint32 & size, const std::function<schar*(const schar*, uint32&)> & decrypter, DirectoryMode directory, bool logWarning) { schar * tempBuffer(nullptr); bool result = ReadBinaryFileSafe(file, tempBuffer, size, directory, logWarning); if(result) { buffer = decrypter(tempBuffer, size); if(tempBuffer != nullptr) { delete [] buffer; } } return result; } void EncryptBinaryFile(const tstring & file, schar * buffer, uint32 size, const std::function<schar*(const schar*, uint32&)> & encrypter, DirectoryMode directory) { schar * encryptedBuffer = encrypter(buffer, size); WriteBinaryFile(file, encryptedBuffer, size, directory); delete [] encryptedBuffer; } }
24.366667
98
0.627837
madhubandubey9
f773d8954bf9f8e6fb62b9055d5df53a3eaa91ad
10,893
cpp
C++
Source/Urho3D/Scene/CameraViewport.cpp
vinhig/rbfx
884de45c623d591f346a2abd5e52edaa84bcc137
[ "MIT" ]
441
2018-12-26T14:50:23.000Z
2021-11-05T03:13:27.000Z
Source/Urho3D/Scene/CameraViewport.cpp
vinhig/rbfx
884de45c623d591f346a2abd5e52edaa84bcc137
[ "MIT" ]
221
2018-12-29T17:40:23.000Z
2021-11-06T21:41:55.000Z
Source/Urho3D/Scene/CameraViewport.cpp
vinhig/rbfx
884de45c623d591f346a2abd5e52edaa84bcc137
[ "MIT" ]
101
2018-12-29T13:08:10.000Z
2021-11-02T09:58:37.000Z
// // Copyright (c) 2017-2020 the rbfx project. // // 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 <EASTL/sort.h> #include "../Core/CoreEvents.h" #include "../Core/StringUtils.h" #include "../Engine/PluginApplication.h" #include "../Graphics/Camera.h" #include "../Graphics/Graphics.h" #include "../Graphics/RenderPath.h" #include "../IO/FileSystem.h" #include "../IO/Log.h" #include "../Resource/ResourceCache.h" #include "../Resource/XMLFile.h" #include "../Scene/CameraViewport.h" #include "../Scene/Node.h" #include "../Scene/Scene.h" #include "../Scene/SceneEvents.h" namespace Urho3D { static ResourceRef defaultRenderPath{XMLFile::GetTypeStatic(), "RenderPaths/Forward.xml"}; CameraViewport::CameraViewport(Context* context) : Component(context) , viewport_(context->CreateObject<Viewport>()) , rect_(fullScreenViewport) , renderPath_(defaultRenderPath) , screenRect_{0, 0, 1920, 1080} { if (Graphics* graphics = context_->GetSubsystem<Graphics>()) screenRect_ = {0, 0, graphics->GetWidth(), graphics->GetHeight()}; } void CameraViewport::SetNormalizedRect(const Rect& rect) { rect_ = rect; IntRect viewportRect( static_cast<int>(screenRect_.Left() + screenRect_.Width() * rect.Left()), static_cast<int>(screenRect_.Top() + screenRect_.Height() * rect.Top()), static_cast<int>(screenRect_.Left() + screenRect_.Width() * rect.Right()), static_cast<int>(screenRect_.Top() + screenRect_.Height() * rect.Bottom()) ); viewport_->SetRect(viewportRect); using namespace CameraViewportResized; VariantMap args{}; args[P_VIEWPORT] = GetViewport(); args[P_CAMERA] = GetViewport()->GetCamera(); args[P_SIZE] = viewportRect; args[P_SIZENORM] = rect; SendEvent(E_CAMERAVIEWPORTRESIZED, args); } void CameraViewport::RegisterObject(Context* context) { context->RegisterFactory<CameraViewport>("Scene"); } void CameraViewport::OnNodeSet(Node* node) { if (node == nullptr) viewport_->SetCamera(nullptr); else { SubscribeToEvent(node, E_COMPONENTADDED, [this](StringHash, VariantMap& args) { using namespace ComponentAdded; if (Component* component = static_cast<Component*>(args[P_COMPONENT].GetPtr())) { if (Camera* camera = component->Cast<Camera>()) { viewport_->SetCamera(camera); camera->SetViewMask(camera->GetViewMask() & ~(1U << 31U)); // Do not render last layer. } } }); SubscribeToEvent(node, E_COMPONENTREMOVED, [this](StringHash, VariantMap& args) { using namespace ComponentRemoved; if (Component* component = static_cast<Component*>(args[P_COMPONENT].GetPtr())) { if (component->GetType() == Camera::GetTypeStatic()) viewport_->SetCamera(nullptr); } }); if (Camera* camera = node->GetComponent<Camera>()) { viewport_->SetCamera(camera); camera->SetViewMask(camera->GetViewMask() & ~(1U << 31U)); // Do not render last layer. } else { // If this node does not have a camera - get or create it on next frame. This is required because Camera may // be created later when deserializing node. SubscribeToEvent(E_BEGINFRAME, [this](StringHash, VariantMap& args) { if (Node* node = GetNode()) { if (Camera* camera = node->GetOrCreateComponent<Camera>()) { viewport_->SetCamera(camera); camera->SetViewMask(camera->GetViewMask() & ~(1U << 31U)); // Do not render last layer. } } UnsubscribeFromEvent(E_BEGINFRAME); }); } } } void CameraViewport::OnSceneSet(Scene* scene) { viewport_->SetScene(scene); } IntRect CameraViewport::GetScreenRect() const { return screenRect_; } const ea::vector<AttributeInfo>* CameraViewport::GetAttributes() const { if (attributesDirty_) const_cast<CameraViewport*>(this)->RebuildAttributes(); return &attributes_; } template<typename T> AttributeInfo& CameraViewport::RegisterAttribute(const AttributeInfo& attr) { attributes_.push_back(attr); return attributes_.back(); } void CameraViewport::RebuildAttributes() { auto* context = this; // Normal attributes. URHO3D_ACCESSOR_ATTRIBUTE("Viewport", GetNormalizedRect, SetNormalizedRect, Rect, fullScreenViewport, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("RenderPath", GetLastRenderPath, SetRenderPath, ResourceRef, defaultRenderPath, AM_DEFAULT); // PostProcess effects are special. One file may contain multiple effects that can be enabled or disabled. { effects_.clear(); for (const auto& dir: context_->GetSubsystem<ResourceCache>()->GetResourceDirs()) { ea::vector<ea::string> effects; ea::string resourcePath = "PostProcess/"; ea::string scanDir = AddTrailingSlash(dir) + resourcePath; context_->GetSubsystem<FileSystem>()->ScanDir(effects, scanDir, "*.xml", SCAN_FILES, false); for (const auto& effectFileName: effects) { auto effectPath = resourcePath + effectFileName; auto* effect = context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>(effectPath); auto root = effect->GetRoot(); ea::string tag; for (auto command = root.GetChild("command"); command.NotNull(); command = command.GetNext("command")) { tag = command.GetAttribute("tag"); if (tag.empty()) { URHO3D_LOGWARNING("Invalid PostProcess effect with empty tag"); continue; } if (effects_.find(tag) != effects_.end()) continue; effects_[tag] = resourcePath + effectFileName; } } } StringVector tags = effects_.keys(); ea::quick_sort(tags.begin(), tags.end()); for (auto& effect : effects_) { auto getter = [this, &effect](const CameraViewport&, Variant& value) { if (RenderPath* renderPath = viewport_->GetRenderPath()) value = renderPath->IsEnabled(effect.first); else value = false; }; auto setter = [this, &effect](const CameraViewport&, const Variant& value) { RenderPath* path = viewport_->GetRenderPath(); if (!path) return; if (!path->IsAdded(effect.first)) path->Append(context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>(effect.second)); path->SetEnabled(effect.first, value.GetBool()); }; URHO3D_CUSTOM_ACCESSOR_ATTRIBUTE(effect.first.c_str(), getter, setter, bool, false, AM_DEFAULT); } } attributesDirty_ = false; } RenderPath* CameraViewport::RebuildRenderPath() { if (!viewport_) return nullptr; SharedPtr<RenderPath> oldRenderPath(viewport_->GetRenderPath()); if (XMLFile* renderPathFile = context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>(renderPath_.name_)) { viewport_->SetRenderPath(renderPathFile); RenderPath* newRenderPath = viewport_->GetRenderPath(); for (const auto& effect : effects_) { if (oldRenderPath->IsEnabled(effect.first)) { if (!newRenderPath->IsAdded(effect.first)) newRenderPath->Append(context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>(effect.second)); newRenderPath->SetEnabled(effect.first, true); } } return newRenderPath; } return nullptr; } void CameraViewport::SetRenderPath(const ResourceRef& renderPathResource) { if (!viewport_ || !context_->GetSubsystem<Graphics>()) return; if (!renderPathResource.name_.empty() && renderPathResource.type_ != XMLFile::GetTypeStatic()) { URHO3D_LOGWARNINGF("Incorrect RenderPath file '%s' type.", renderPathResource.name_.c_str()); return; } SharedPtr<RenderPath> oldRenderPath(viewport_->GetRenderPath()); const ea::string& renderPathFileName = renderPathResource.name_.empty() ? defaultRenderPath.name_ : renderPathResource.name_; if (XMLFile* renderPathFile = context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>(renderPathFileName)) { if (!viewport_->SetRenderPath(renderPathFile)) { URHO3D_LOGERRORF("Loading renderpath from %s failed. File probably is not a renderpath.", renderPathFileName.c_str()); return; } RenderPath* newRenderPath = viewport_->GetRenderPath(); for (const auto& effect : effects_) { if (oldRenderPath->IsEnabled(effect.first)) { if (!newRenderPath->IsAdded(effect.first)) newRenderPath->Append(context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>(effect.second)); newRenderPath->SetEnabled(effect.first, true); } } renderPath_.name_ = renderPathFileName; } else { URHO3D_LOGERRORF("Loading renderpath from %s failed. File is missing or you have no permissions to read it.", renderPathFileName.c_str()); } } void CameraViewport::UpdateViewport() { SetNormalizedRect(GetNormalizedRect()); } }
36.069536
129
0.623061
vinhig
f777337c6d45ab6c2c4ba104b4d345eb58a51e70
4,613
cpp
C++
3C1V_Donkey_Kong/DonkeyKong_Solution/Source/ModuleEnemies.cpp
unaidiaz/pryecto1
aa074c32587e8207cb89d6634391bb43aa9a4657
[ "BSD-3-Clause" ]
2
2020-05-20T15:48:29.000Z
2020-08-17T03:35:56.000Z
3C1V_Donkey_Kong/DonkeyKong_Solution/Source/ModuleEnemies.cpp
unaidiaz/proyecto1
aa074c32587e8207cb89d6634391bb43aa9a4657
[ "BSD-3-Clause" ]
null
null
null
3C1V_Donkey_Kong/DonkeyKong_Solution/Source/ModuleEnemies.cpp
unaidiaz/proyecto1
aa074c32587e8207cb89d6634391bb43aa9a4657
[ "BSD-3-Clause" ]
null
null
null
#include "ModuleEnemies.h" #include "Application.h" #include"ModulePlayer.h" #include "ModuleRender.h" #include "ModuleTextures.h" #include "ModuleAudio.h" #include "SceneLevel4.h" #include"Enemy_Barril.h" #include"Enemy_Barrilazul.h" #include "Enemy.h" #include "Enemy_Llama.h" #include "Enemy_Kong.h" #include "muelle.h" #include "SDL/include/SDL.h" #include "SDL_image/include/SDL_image.h" #include<time.h> #pragma comment( lib, "SDL_image/libx86/SDL2_image.lib" ) #define SPAWN_MARGIN 50 ModuleEnemies::ModuleEnemies(bool startEnabled) : Module(startEnabled) { for (uint i = 0; i < MAX_ENEMIES; ++i) enemies[i] = nullptr; } ModuleEnemies::~ModuleEnemies() { } bool ModuleEnemies::Start() { enemigos = App->textures->Load("Assets/objetosanimados.png"); kongs = App->textures->Load("Assets/sprites.png"); enemyDestroyedFx = App->audio->LoadFx("Assets/8. SFX (Kill).wav"); return true; } update_status ModuleEnemies::PreUpdate() { // Remove all enemies scheduled for deletion for (int i = 0; i < MAX_ENEMIES; i++) { if (enemies[i] != nullptr && enemies[i]->pendientedeelim == true) { delete enemies[i]; enemies[i] = nullptr; } } return update_status::UPDATE_CONTINUE; } update_status ModuleEnemies::Update() { HandleEnemiesSpawn(); for (uint i = 0; i < MAX_ENEMIES; ++i) { if (enemies[i] != nullptr) enemies[i]->Update(); } HandleEnemiesDespawn(); return update_status::UPDATE_CONTINUE; } update_status ModuleEnemies::PostUpdate() { for (uint i = 0; i < MAX_ENEMIES; ++i) { if (enemies[i] != nullptr) enemies[i]->Draw(); } return update_status::UPDATE_CONTINUE; } // Called before quitting bool ModuleEnemies::CleanUp() { LOG("Freeing all enemies"); App->textures->Unload(kongs); App->textures->Unload(enemigos); for (int i = 0; i < MAX_ENEMIES; ++i) { if (enemies[i] != nullptr) { delete enemies[i]; enemies[i] = nullptr; } } return true; } bool ModuleEnemies::AddEnemy(Enemy_Type type, int x, int y,int direccion) { bool ret = false; for (uint i = 0; i < MAX_ENEMIES; ++i) { if (spawnQueue[i].type == Enemy_Type::NO_TYPE) { spawnQueue[i].type = type; spawnQueue[i].x = x; spawnQueue[i].y = y; spawnQueue[i].direccion = direccion; ret = true; break; } } return ret; } void ModuleEnemies::HandleEnemiesSpawn() { // Iterate all the enemies queue for (int i = 0; i < MAX_ENEMIES; i++) { if (spawnQueue[i].type != Enemy_Type::NO_TYPE) { SpawnEnemy(spawnQueue[i]); spawnQueue[i].type = Enemy_Type::NO_TYPE; // Removing the newly spawned enemy from the queue } } } void ModuleEnemies::HandleEnemiesDespawn() { // Iterate existing enemies for (int i = 0; i < MAX_ENEMIES; i++) { if (enemies[i] != nullptr&&enemies[i]->pendientedeelim==true) { delete enemies[i]; enemies[i] = nullptr; } } } void ModuleEnemies::SpawnEnemy(const EnemySpawnpoint& info) { // Find an empty slot in the enemies array for (uint i = 0; i < MAX_ENEMIES; ++i) { if (enemies[i] == nullptr) { switch (info.type) { case Enemy_Type::LLAMA: enemies[i] = new Enemy_Llama(info.x, info.y, info.direccion); enemies[i]->enemigo = enemigos; enemies[i]->destroyedFx = enemyDestroyedFx; break; case Enemy_Type::KONG: enemies[i] = new Enemy_Kong(info.x, info.y, info.direccion); enemies[i]->kong = kongs; enemies[i]->destroyedFx = enemyDestroyedFx; break; case Enemy_Type::barril: enemies[i] = new Enemybarril(info.x, info.y, info.direccion); enemies[i]->barriltext = enemigos; enemies[i]->destroyedFx = enemyDestroyedFx; break; case Enemy_Type::barrilazul: enemies[i] = new Enemybarrilazul(info.x, info.y, info.direccion); enemies[i]->barriltext = enemigos; enemies[i]->destroyedFx = enemyDestroyedFx; break; case Enemy_Type::MUELLE: enemies[i] = new Muelle(info.x, info.y, info.direccion); enemies[i]->muelles = enemigos; enemies[i]->destroyedFx = enemyDestroyedFx; break; } break; } } } void ModuleEnemies::OnCollision(Collider* c1, Collider* c2) { for (uint i = 0; i < MAX_ENEMIES; ++i) { if (enemies[i] != nullptr) { if (c1->type == c1->Enemigo && c2->type == c2->martillo) { if (c1 == enemies[i]->GetCollider()) { App->audio->PlayFx(App->enemies->enemyDestroyedFx);//Notify the enemy of a collision enemies[i]->destr(); break; } } else { enemies[i]->OnCollision(c1, c2); } } } } bool ModuleEnemies::compene() { for (int i = 0; i < MAX_ENEMIES; i++) { if (enemies[i] != nullptr) { return false; } } return true; }
20.686099
95
0.656406
unaidiaz
f77a0206d669785a0f6b7d2be5174d9d9277d9de
2,728
hpp
C++
app/Snapper.hpp
isonil/survival
ecb59af9fcbb35b9c28fd4fe29a4628f046165c8
[ "MIT" ]
1
2017-05-12T10:12:41.000Z
2017-05-12T10:12:41.000Z
app/Snapper.hpp
isonil/Survival
ecb59af9fcbb35b9c28fd4fe29a4628f046165c8
[ "MIT" ]
null
null
null
app/Snapper.hpp
isonil/Survival
ecb59af9fcbb35b9c28fd4fe29a4628f046165c8
[ "MIT" ]
1
2019-01-09T04:05:36.000Z
2019-01-09T04:05:36.000Z
#ifndef APP_SNAPPER_HPP #define APP_SNAPPER_HPP #include "engine/util/Vec3.hpp" #include <array> namespace app { class Structure; class StructureDef; class Snapper { public: static std::vector <std::pair <engine::FloatVec3, engine::FloatVec3>> trySnap(const Structure &first, const StructureDef &secondDef, const engine::FloatVec3 &designatedPos); private: static std::vector <std::pair <engine::FloatVec3, engine::FloatVec3>> floorToFloor(const engine::FloatVec3 &firstSize, const engine::FloatVec3 &secondSize, const engine::FloatVec3 &designatedPos, const Structure &first, const engine::FloatVec3 &secondPosOffset); static std::vector <std::pair <engine::FloatVec3, engine::FloatVec3>> wallToWall(const engine::FloatVec3 &firstSize, const engine::FloatVec3 &secondSize, const engine::FloatVec3 &designatedPos, const Structure &first, const engine::FloatVec3 &secondPosOffset); static std::vector <std::pair <engine::FloatVec3, engine::FloatVec3>> floorToWall(const engine::FloatVec3 &firstSize, const engine::FloatVec3 &secondSize, const engine::FloatVec3 &designatedPos, const Structure &first, const engine::FloatVec3 &secondPosOffset); static std::vector <std::pair <engine::FloatVec3, engine::FloatVec3>> wallToFloor(const engine::FloatVec3 &firstSize, const engine::FloatVec3 &secondSize, const engine::FloatVec3 &designatedPos, const Structure &first, const engine::FloatVec3 &secondPosOffset); static engine::FloatVec3 relPosToWorldPos(const engine::FloatVec3 &relPos, const Structure &structure); template <std::size_t N> static std::vector <int> getBestHotspots(const engine::FloatVec3 &pos, const Structure &structure, const std::array <engine::FloatVec3, N> &hotspots); }; template <std::size_t N> std::vector <int> Snapper::getBestHotspots(const engine::FloatVec3 &pos, const Structure &structure, const std::array <engine::FloatVec3, N> &hotspots) { int minIndex{-1}; float minDist{}; int minSecondIndex{-1}; float minSecondDist{}; for(size_t i = 0; i < hotspots.size(); ++i) { const auto &inWorldPos = relPosToWorldPos(hotspots[i], structure); float dist{pos.getDistanceSq(inWorldPos)}; if(dist < minDist || minIndex < 0) { minSecondIndex = minIndex; minSecondDist = minDist; minIndex = i; minDist = dist; } else if(dist < minSecondDist || minSecondIndex < 0) { minSecondIndex = i; minSecondDist = dist; } } std::vector <int> ret; if(minIndex >= 0) ret.push_back(minIndex); if(minSecondIndex >= 0) ret.push_back(minSecondIndex); return ret; } } // namespace app #endif // APP_SNAPPER_HPP
40.117647
266
0.707845
isonil
f77ff8aa7082cd461fe2b307bd8f25f60a792a47
6,971
cpp
C++
modules/web/fcgiCHAT.cpp
omnidynmc/openapi
7c28179859125efb8c945d0c44543194e6bcd09f
[ "MIT" ]
null
null
null
modules/web/fcgiCHAT.cpp
omnidynmc/openapi
7c28179859125efb8c945d0c44543194e6bcd09f
[ "MIT" ]
null
null
null
modules/web/fcgiCHAT.cpp
omnidynmc/openapi
7c28179859125efb8c945d0c44543194e6bcd09f
[ "MIT" ]
null
null
null
#include <fcgi_stdio.h> #include <list> #include <fstream> #include <queue> #include <cstdlib> #include <cstdio> #include <cstring> #include <new> #include <iostream> #include <string> #include <exception> #include <stdio.h> #include <unistd.h> #include <time.h> #include <mysql++.h> #include <openframe/openframe.h> #include "App.h" #include "EarthTools.h" #include "DBI_Web.h" #include "Tag.h" #include "Web.h" #include "webCommands.h" namespace modweb { using namespace mysqlpp; /************************************************************************** ** fcgiCHAT Class ** **************************************************************************/ bool isValidCallsign(const std::string &callsign) { openframe::StringTool::regexMatchListType rl; return openframe::StringTool::ereg("^([a-zA-Z0-9]{2,6})([-]{1}[0-9]+)?[*]*$", callsign, rl) > 0; } // isValidCallsign const int fcgiCHAT::Execute(COMMAND_ARGUMENTS) { openapi::App_Log *log = static_cast<openapi::App_Log *>( ePacket->getVariable("log") ); openframe::StringTool::regexMatchListType rl; openframe::Url *u = (openframe::Url *) ePacket->getVariable("url"); map<string, double> stats; openframe::Stopwatch sw_total; sw_total.Start(); // check for broken implementation if (!u->exists("chat_sequence")) return CMDERR_SYNTAX; std::string chat_sequence = (*u)["chat_sequence"]; bool ok = openframe::StringTool::ereg("^([0-9]+)$", chat_sequence, rl); if (!ok) { FCGI_printf("# ERROR: invalid chat sequence\n"); return CMDERR_SYNTAX; } // if openframe::Stopwatch sw; sw.Start(); // grab next chat sequence mysqlpp::StoreQueryResult res; ok = web->dbi_w()->get("getNextChatSeq", res); unsigned int next_sequence = 0; if (ok) next_sequence = atoi( res[0]["sequence"].c_str() ); stats["next_seq"] = sw.Time(); // process nick/ip std::string nick = u->exists("nick") ? (*u)["nick"] : ""; std::string ip = ePacket->getString("request.remote.addr"); bool is_user_call_valid = isValidCallsign(nick); if (!is_user_call_valid) { ok = openframe::StringTool::ereg("^([0-9]{1,3}[.][0-9]{1,3}[.])[0-9]{1,3}[.][0-9]{1,3}", ip, rl); if (!ok) return CMDERR_SYNTAX; nick = "[" + rl[1].matchString + "*]"; } // if sw.Start(); // process session if there std::string hash = u->exists("session") ? (*u)["session"] : ""; std::string timezone = u->exists("timezone") ? (*u)["timezone"] : "unknown"; std::string idle = u->exists("idle") && (*u)["idle"].length() ? (*u)["idle"] : "0"; ok = openframe::StringTool::ereg("^([0-9a-zA-Z]{32})$", hash, rl); if (ok) { web->dbi_w()->set("setWebWho", hash, "openapi", ip, nick, timezone, "0", idle); } // if else FCGI_printf("# ERROR: invalid or missing hash\n"); stats["set_who"] = sw.Time(); sw.Start(); // handle chat insertion std::string message = u->exists("message") ? (*u)["message"] : ""; if (is_user_call_valid && message.length()) { bool inserted = web->dbi_w()->set("setChat", ip, nick, message, stringify<unsigned int>(next_sequence) ); if (inserted) ++next_sequence; } // if else FCGI_printf("# ERROR: could not insert message, missing or invalid nick\n"); stats["set_chat"] = sw.Time(); sw.Start(); // get current sequence ok = web->dbi_r()->get("getChatBySequence", res, chat_sequence); if (ok) { for(DBI_Web::resultSizeType i=res.num_rows() - 1; ; i--) { openframe::Vars v; v.add("TY", "CH"); v.add("NK", res[i]["nick"].c_str()); v.add("MS", res[i]["message"].c_str()); v.add("SQ", res[i]["sequence"].c_str()); v.add("DT", res[i]["post_date"].c_str()); FCGI_printf("%s\n", v.compile().c_str()); if (i == 0) break; } // for } // if stats["get_chat"] = sw.Time(); sw.Start(); // process web who time_t active_ts = time(NULL) - 60; DBI_Web::resultSizeType num_users = web->dbi_r()->get("getWhoByTime", res, stringify<time_t>(active_ts) ); size_t hidden_count = 0; if (num_users) { for(DBI_Web::resultSizeType i=0; i < res.num_rows(); i++) { openframe::Vars v; v.add("TY", "OL"); time_t idle = atoi( res[i]["idle"].c_str() ); std::string css_class; if (idle < 300) { v.add("ISI", "0"); css_class = "chatHere"; } // if else { v.add("ISI", "1"); css_class = "chatIdle"; } // else std::stringstream url; std::string nick = openframe::Vars::Urlencode( res[i]["nick"].c_str(), false ); bool is_call_valid = isValidCallsign(res[i]["nick"].c_str() ); int count = atoi( res[i]["count"].c_str() ); if (is_call_valid) { url << "<span class=\"" << css_class << "\"><a " << "href=\"javascript:changeFieldById(\'openaprs_form_chat_message\',\'" << nick << ", \')\">" << nick << "</a>"; if (count > 1) url << " (" << count << ")"; url << "</span>"; } // if else { url << "<span class=\"" << css_class << "\">" << nick; if (count > 1) url << " (" << count << ")"; url << "</span>"; hidden_count++; } // if v.add("URL", url.str()); v.add("NK", nick); v.add("IDL", res[i]["idle"].c_str() ); FCGI_printf("%s\n", v.compile().c_str()); } //for } // if openframe::Vars v; v.add("TY", "ST"); v.add("NU", stringify<DBI_Web::resultSizeType>(num_users) ); v.add("HC", stringify<size_t>(hidden_count) ); v.add("SQ", stringify<unsigned int>(next_sequence) ); FCGI_printf("%s\n", v.compile().c_str()); stats["get_who"] = sw.Time(); stats["total"] = sw_total.Time(); std::stringstream s; s << std::fixed << std::setprecision(0) << "stats chat " << "seq " << (stats["next_seq"]*1000) << "ms" << ", who " << (stats["set_who"]*1000) << "ms" << ", post " << (stats["set_chat"]*1000) << "ms" << ", msgs " << (stats["get_chat"]*1000) << "ms" << ", whos " << (stats["get_who"]*1000) << "ms" << ", total " << (stats["total"]*1000) << "ms"; if (stats["total"] > 2.0) log->warn(s.str()); else log->info(s.str()); FCGI_printf("# Total getNextChatSeq %0.5fs\n", stats["next_seq"]); FCGI_printf("# Total setWho %0.5fs\n", stats["set_who"]); FCGI_printf("# Total setChat %0.5fs\n", stats["set_chat"]); FCGI_printf("# Total getChatBySequence %0.5fs\n", stats["get_chat"]); FCGI_printf("# Total %0.5f\n", sw_total.Time()); return CMDERR_SUCCESS; } // fcgiCHAT::Execute } // namespace modweb
32.273148
111
0.527901
omnidynmc
f782d31f58d0659025581dbf9d78ec3776d5b27b
1,404
hpp
C++
src/common/deserializer.hpp
adlerjohn/ech-cpp-dev
60584994266b1c83e997e831238d14f5bd015e5a
[ "Apache-2.0" ]
2
2020-06-01T00:30:12.000Z
2020-06-05T18:41:48.000Z
src/common/deserializer.hpp
adlerjohn/ech-cpp-dev
60584994266b1c83e997e831238d14f5bd015e5a
[ "Apache-2.0" ]
null
null
null
src/common/deserializer.hpp
adlerjohn/ech-cpp-dev
60584994266b1c83e997e831238d14f5bd015e5a
[ "Apache-2.0" ]
1
2020-06-05T18:33:28.000Z
2020-06-05T18:33:28.000Z
#pragma once // System includes #include <cstddef> // Library includes #include "crypto/byteset.hpp" namespace ech { namespace deserializer { /** * Move bytes from the serialized representation directly into a byteset container. * @tparam T Type of byteset. * @param serial Serialized representation (will get modified). * @return Instance of T. */ template<class T> [[nodiscard]] const T move(std::deque<std::byte>& serial) { constexpr auto N = T::size(); static_assert(std::is_base_of<crypto::ByteSet<N>, T>::value, "must move to byteset or child"); if (serial.size() < N) { throw std::runtime_error("too few bytes when moving"); } auto bytes = std::array<std::byte, N>(); std::copy_n(serial.begin(), N, bytes.begin()); serial.erase(serial.begin(), serial.begin() + N); return T(bytes); } // TODO change this to vector with index for beginning if benchmarking is slow /** * Deserialize a primitive integer type. * @tparam T Type of integer. * @tparam B Size of integer, in bytes. * @param serial Serialized representation (will get modified). * @return Instance of T. */ template<class T, size_t B> [[nodiscard]] const T deserialize(std::deque<std::byte>& serial) { const auto bytes = move<crypto::byteset<B>>(serial); T t; for (const auto& byte : bytes) { t <<= 8; t |= static_cast<uint8_t>(byte); } return t; } } // namespace deserializer } // namespace ech
22.645161
95
0.689459
adlerjohn
f786d644e7ad3bc178847d7615ea71bb0031e382
1,637
cc
C++
dreal/util/math.cc
soonhokong/dreal4
573e613560f5dce9ad54a2f685e060fe447310c7
[ "Apache-2.0" ]
104
2017-12-07T18:17:35.000Z
2022-03-31T06:58:13.000Z
dreal/util/math.cc
soonhokong/dreal4
573e613560f5dce9ad54a2f685e060fe447310c7
[ "Apache-2.0" ]
250
2017-09-01T01:32:45.000Z
2022-03-29T04:08:00.000Z
dreal/util/math.cc
soonhokong/dreal4
573e613560f5dce9ad54a2f685e060fe447310c7
[ "Apache-2.0" ]
16
2018-01-07T07:40:11.000Z
2022-03-24T05:01:11.000Z
/* Copyright 2017 Toyota Research Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "dreal/util/math.h" #include <cmath> #include <iostream> #include <limits> #include "dreal/util/exception.h" using std::int64_t; using std::modf; using std::numeric_limits; namespace dreal { bool is_integer(const double v) { // v should be in [int_min, int_max]. if (!((numeric_limits<int>::lowest() <= v) && (v <= numeric_limits<int>::max()))) { return false; } double intpart{}; // dummy variable return modf(v, &intpart) == 0.0; } int convert_int64_to_int(const int64_t v) { if (numeric_limits<int>::min() <= v && v <= numeric_limits<int>::max()) { return v; } else { throw DREAL_RUNTIME_ERROR("Fail to convert a int64_t value {} to int", v); } } double convert_int64_to_double(const int64_t v) { constexpr int64_t m{ 1UL << static_cast<unsigned>(numeric_limits<double>::digits)}; if (-m <= v && v <= m) { return v; } else { throw DREAL_RUNTIME_ERROR("Fail to convert a int64_t value {} to double", v); } } } // namespace dreal
27.745763
78
0.672572
soonhokong
f7942f03328ecfd2ca4febc685efc7f233f1a4ed
964
cpp
C++
Codigos de ejercicios en cpp/Programa 12.cpp
EulisesBrazon/ejercicios-c-
700235bced91bc6f508ca6d203ea7ee7c241006c
[ "Apache-2.0" ]
null
null
null
Codigos de ejercicios en cpp/Programa 12.cpp
EulisesBrazon/ejercicios-c-
700235bced91bc6f508ca6d203ea7ee7c241006c
[ "Apache-2.0" ]
null
null
null
Codigos de ejercicios en cpp/Programa 12.cpp
EulisesBrazon/ejercicios-c-
700235bced91bc6f508ca6d203ea7ee7c241006c
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<stdio.h> #include<conio.h> using namespace std; int main() { double L1,L2,L3,n=1,Mayor; cout<<"Ingrese el primer lado del triangulo"<<endl; cin>>L1; cout<<"Ingrese el segundo lado del triangulo"<<endl; cin>>L2; cout<<"Ingrese el tercer lado del triangulo"<<endl; cin>>L3; if((L1>L2)&&(L1>L3)) Mayor=L1; else if(L2>L3) Mayor=L2; else Mayor=L3; if(Mayor==L1) { if((L2+L3)<=L1) { cout<<"el triangulo es invalido"<<endl; n=0; } }else if(Mayor==L2) { if((L1+L3)<=L2) { cout<<"el triangulo es invalido"<<endl; n=0; } }else if(Mayor==L3) { if((L1+L2)<=L3) { cout<<"el triangulo es invalido"<<endl; n=0; } } if (n==1) { if ((L1==L2)&&(L2==L3)) cout<<"Es un triangulo equilatero"<<endl; else if(L1!=L2&&L1!=L3&&L3!=L2) cout<<"Es un triangulo escaleno"<<endl; else cout<<"Es un triangulo isosceles"<<endl; } getch(); return 0; }
17.851852
53
0.572614
EulisesBrazon
f799755e7e47dcb07d48be5193db428cbaf2a490
18,648
hpp
C++
c++/include/serial/objectiter.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/include/serial/objectiter.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/include/serial/objectiter.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
#ifndef OBJECTITER__HPP #define OBJECTITER__HPP /* $Id: objectiter.hpp 358154 2012-03-29 15:05:12Z gouriano $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Eugene Vasilchenko * * File Description: * Iterators, which work on object information data */ #include <corelib/ncbistd.hpp> #include <serial/objectinfo.hpp> /** @addtogroup ObjStreamSupport * * @{ */ BEGIN_NCBI_SCOPE ///////////////////////////////////////////////////////////////////////////// /// /// CConstObjectInfoEI -- /// /// Container iterator /// Provides read access to elements of container /// @sa CConstObjectInfo::BeginElements class NCBI_XSERIAL_EXPORT CConstObjectInfoEI { public: CConstObjectInfoEI(void); CConstObjectInfoEI(const CConstObjectInfo& object); CConstObjectInfoEI& operator=(const CConstObjectInfo& object); /// Is iterator valid bool Valid(void) const; /// Is iterator valid DECLARE_OPERATOR_BOOL(Valid()); bool operator==(const CConstObjectInfoEI& obj) const { return GetElement() == obj.GetElement(); } bool operator!=(const CConstObjectInfoEI& obj) const { return GetElement() != obj.GetElement(); } /// Get index of the element in the container TMemberIndex GetIndex(void) const { return m_Iterator.GetIndex(); } /// Advance to next element void Next(void); /// Advance to next element CConstObjectInfoEI& operator++(void); /// Get element data and type information CConstObjectInfo GetElement(void) const; /// Get element data and type information CConstObjectInfo operator*(void) const; bool CanGet(void) const { return true; } const CItemInfo* GetItemInfo(void) const { return 0; } protected: bool CheckValid(void) const; private: CConstContainerElementIterator m_Iterator; }; ///////////////////////////////////////////////////////////////////////////// /// /// CObjectInfoEI -- /// /// Container iterator /// Provides read/write access to elements of container /// @sa CObjectInfo::BeginElements class NCBI_XSERIAL_EXPORT CObjectInfoEI { public: CObjectInfoEI(void); CObjectInfoEI(const CObjectInfo& object); CObjectInfoEI& operator=(const CObjectInfo& object); /// Is iterator valid bool Valid(void) const; /// Is iterator valid DECLARE_OPERATOR_BOOL(Valid()); bool operator==(const CObjectInfoEI& obj) const { return GetElement() == obj.GetElement(); } bool operator!=(const CObjectInfoEI& obj) const { return GetElement() != obj.GetElement(); } /// Get index of the element in the container TMemberIndex GetIndex(void) const { return m_Iterator.GetIndex(); } /// Advance to next element void Next(void); /// Advance to next element CObjectInfoEI& operator++(void); /// Get element data and type information CObjectInfo GetElement(void) const; /// Get element data and type information CObjectInfo operator*(void) const; void Erase(void); bool CanGet(void) const { return true; } const CItemInfo* GetItemInfo(void) const { return 0; } protected: bool CheckValid(void) const; private: CContainerElementIterator m_Iterator; }; ///////////////////////////////////////////////////////////////////////////// /// /// CObjectTypeInfoII -- /// /// Item iterator (either class member or choice variant) /// provides access to the data type information. class NCBI_XSERIAL_EXPORT CObjectTypeInfoII { public: const string& GetAlias(void) const; /// Is iterator valid bool Valid(void) const; /// Is iterator valid DECLARE_OPERATOR_BOOL(Valid()); bool operator==(const CObjectTypeInfoII& iter) const; bool operator!=(const CObjectTypeInfoII& iter) const; /// Advance to next element void Next(void); const CItemInfo* GetItemInfo(void) const; /// Get index of the element in the container (class or choice) TMemberIndex GetIndex(void) const { return GetItemIndex(); } protected: CObjectTypeInfoII(void); CObjectTypeInfoII(const CClassTypeInfoBase* typeInfo); CObjectTypeInfoII(const CClassTypeInfoBase* typeInfo, TMemberIndex index); const CObjectTypeInfo& GetOwnerType(void) const; const CClassTypeInfoBase* GetClassTypeInfoBase(void) const; TMemberIndex GetItemIndex(void) const; void Init(const CClassTypeInfoBase* typeInfo); void Init(const CClassTypeInfoBase* typeInfo, TMemberIndex index); bool CanGet(void) const { return true; } bool CheckValid(void) const; private: CObjectTypeInfo m_OwnerType; TMemberIndex m_ItemIndex; TMemberIndex m_LastItemIndex; }; ///////////////////////////////////////////////////////////////////////////// /// /// CObjectTypeInfoMI -- /// /// Class member iterator /// provides access to the data type information. class NCBI_XSERIAL_EXPORT CObjectTypeInfoMI : public CObjectTypeInfoII { typedef CObjectTypeInfoII CParent; public: CObjectTypeInfoMI(void); CObjectTypeInfoMI(const CObjectTypeInfo& info); CObjectTypeInfoMI(const CObjectTypeInfo& info, TMemberIndex index); /// Get index of the member in the class TMemberIndex GetMemberIndex(void) const; /// Advance to next element CObjectTypeInfoMI& operator++(void); CObjectTypeInfoMI& operator=(const CObjectTypeInfo& info); /// Get containing class type CObjectTypeInfo GetClassType(void) const; /// Get data type information operator CObjectTypeInfo(void) const; /// Get data type information CObjectTypeInfo GetMemberType(void) const; /// Get data type information CObjectTypeInfo operator*(void) const; void SetLocalReadHook(CObjectIStream& stream, CReadClassMemberHook* hook) const; void SetGlobalReadHook(CReadClassMemberHook* hook) const; void ResetLocalReadHook(CObjectIStream& stream) const; void ResetGlobalReadHook(void) const; void SetPathReadHook(CObjectIStream* in, const string& path, CReadClassMemberHook* hook) const; void SetLocalWriteHook(CObjectOStream& stream, CWriteClassMemberHook* hook) const; void SetGlobalWriteHook(CWriteClassMemberHook* hook) const; void ResetLocalWriteHook(CObjectOStream& stream) const; void ResetGlobalWriteHook(void) const; void SetPathWriteHook(CObjectOStream* stream, const string& path, CWriteClassMemberHook* hook) const; void SetLocalSkipHook(CObjectIStream& stream, CSkipClassMemberHook* hook) const; void ResetLocalSkipHook(CObjectIStream& stream) const; void SetPathSkipHook(CObjectIStream* stream, const string& path, CSkipClassMemberHook* hook) const; void SetLocalCopyHook(CObjectStreamCopier& stream, CCopyClassMemberHook* hook) const; void SetGlobalCopyHook(CCopyClassMemberHook* hook) const; void ResetLocalCopyHook(CObjectStreamCopier& stream) const; void ResetGlobalCopyHook(void) const; void SetPathCopyHook(CObjectStreamCopier* stream, const string& path, CCopyClassMemberHook* hook) const; public: // mostly for internal use const CMemberInfo* GetMemberInfo(void) const; protected: void Init(const CObjectTypeInfo& info); void Init(const CObjectTypeInfo& info, TMemberIndex index); const CClassTypeInfo* GetClassTypeInfo(void) const; bool IsSet(const CConstObjectInfo& object) const; private: CMemberInfo* GetNCMemberInfo(void) const; }; ///////////////////////////////////////////////////////////////////////////// /// /// CObjectTypeInfoVI -- /// /// Choice variant iterator /// provides access to the data type information. class NCBI_XSERIAL_EXPORT CObjectTypeInfoVI : public CObjectTypeInfoII { typedef CObjectTypeInfoII CParent; public: CObjectTypeInfoVI(const CObjectTypeInfo& info); CObjectTypeInfoVI(const CObjectTypeInfo& info, TMemberIndex index); /// Get index of the variant in the choice TMemberIndex GetVariantIndex(void) const; /// Advance to next element CObjectTypeInfoVI& operator++(void); CObjectTypeInfoVI& operator=(const CObjectTypeInfo& info); /// Get containing choice type CObjectTypeInfo GetChoiceType(void) const; /// Get data type information CObjectTypeInfo GetVariantType(void) const; /// Get data type information CObjectTypeInfo operator*(void) const; void SetLocalReadHook(CObjectIStream& stream, CReadChoiceVariantHook* hook) const; void SetGlobalReadHook(CReadChoiceVariantHook* hook) const; void ResetLocalReadHook(CObjectIStream& stream) const; void ResetGlobalReadHook(void) const; void SetPathReadHook(CObjectIStream* stream, const string& path, CReadChoiceVariantHook* hook) const; void SetLocalWriteHook(CObjectOStream& stream, CWriteChoiceVariantHook* hook) const; void SetGlobalWriteHook(CWriteChoiceVariantHook* hook) const; void ResetLocalWriteHook(CObjectOStream& stream) const; void ResetGlobalWriteHook(void) const; void SetPathWriteHook(CObjectOStream* stream, const string& path, CWriteChoiceVariantHook* hook) const; void SetLocalSkipHook(CObjectIStream& stream, CSkipChoiceVariantHook* hook) const; void ResetLocalSkipHook(CObjectIStream& stream) const; void SetPathSkipHook(CObjectIStream* stream, const string& path, CSkipChoiceVariantHook* hook) const; void SetLocalCopyHook(CObjectStreamCopier& stream, CCopyChoiceVariantHook* hook) const; void SetGlobalCopyHook(CCopyChoiceVariantHook* hook) const; void ResetLocalCopyHook(CObjectStreamCopier& stream) const; void ResetGlobalCopyHook(void) const; void SetPathCopyHook(CObjectStreamCopier* stream, const string& path, CCopyChoiceVariantHook* hook) const; public: // mostly for internal use const CVariantInfo* GetVariantInfo(void) const; protected: void Init(const CObjectTypeInfo& info); void Init(const CObjectTypeInfo& info, TMemberIndex index); const CChoiceTypeInfo* GetChoiceTypeInfo(void) const; private: CVariantInfo* GetNCVariantInfo(void) const; }; ///////////////////////////////////////////////////////////////////////////// /// /// CConstObjectInfoMI -- /// /// Class member iterator /// provides read access to class member data. class NCBI_XSERIAL_EXPORT CConstObjectInfoMI : public CObjectTypeInfoMI { typedef CObjectTypeInfoMI CParent; public: CConstObjectInfoMI(void); CConstObjectInfoMI(const CConstObjectInfo& object); CConstObjectInfoMI(const CConstObjectInfo& object, TMemberIndex index); /// Get containing class data const CConstObjectInfo& GetClassObject(void) const; CConstObjectInfoMI& operator=(const CConstObjectInfo& object); /// Is member assigned a value bool IsSet(void) const; /// Get class member data CConstObjectInfo GetMember(void) const; /// Get class member data CConstObjectInfo operator*(void) const; bool CanGet(void) const; private: pair<TConstObjectPtr, TTypeInfo> GetMemberPair(void) const; CConstObjectInfo m_Object; }; ///////////////////////////////////////////////////////////////////////////// /// /// CObjectInfoMI -- /// /// Class member iterator /// provides read/write access to class member data. class NCBI_XSERIAL_EXPORT CObjectInfoMI : public CObjectTypeInfoMI { typedef CObjectTypeInfoMI CParent; public: CObjectInfoMI(void); CObjectInfoMI(const CObjectInfo& object); CObjectInfoMI(const CObjectInfo& object, TMemberIndex index); /// Get containing class data const CObjectInfo& GetClassObject(void) const; CObjectInfoMI& operator=(const CObjectInfo& object); /// Is member assigned a value bool IsSet(void) const; /// Get class member data CObjectInfo GetMember(void) const; /// Get class member data CObjectInfo operator*(void) const; /// Erase types enum EEraseFlag { eErase_Optional, ///< default - erase optional member only eErase_Mandatory ///< allow erasing mandatory members, may be dangerous! }; /// Erase member value void Erase(EEraseFlag flag = eErase_Optional); /// Reset value of member to default state void Reset(void); bool CanGet(void) const; private: pair<TObjectPtr, TTypeInfo> GetMemberPair(void) const; CObjectInfo m_Object; }; ///////////////////////////////////////////////////////////////////////////// /// /// CObjectTypeInfoCV -- /// /// Choice variant /// provides access to the data type information. class NCBI_XSERIAL_EXPORT CObjectTypeInfoCV { public: CObjectTypeInfoCV(void); CObjectTypeInfoCV(const CObjectTypeInfo& info); CObjectTypeInfoCV(const CObjectTypeInfo& info, TMemberIndex index); CObjectTypeInfoCV(const CConstObjectInfo& object); /// Get index of the variant in the choice TMemberIndex GetVariantIndex(void) const; const string& GetAlias(void) const; bool Valid(void) const; DECLARE_OPERATOR_BOOL(Valid()); bool operator==(const CObjectTypeInfoCV& iter) const; bool operator!=(const CObjectTypeInfoCV& iter) const; CObjectTypeInfoCV& operator=(const CObjectTypeInfo& info); CObjectTypeInfoCV& operator=(const CConstObjectInfo& object); /// Get containing choice CObjectTypeInfo GetChoiceType(void) const; /// Get variant data type CObjectTypeInfo GetVariantType(void) const; /// Get variant data type CObjectTypeInfo operator*(void) const; void SetLocalReadHook(CObjectIStream& stream, CReadChoiceVariantHook* hook) const; void SetGlobalReadHook(CReadChoiceVariantHook* hook) const; void ResetLocalReadHook(CObjectIStream& stream) const; void ResetGlobalReadHook(void) const; void SetPathReadHook(CObjectIStream* stream, const string& path, CReadChoiceVariantHook* hook) const; void SetLocalWriteHook(CObjectOStream& stream, CWriteChoiceVariantHook* hook) const; void SetGlobalWriteHook(CWriteChoiceVariantHook* hook) const; void ResetLocalWriteHook(CObjectOStream& stream) const; void ResetGlobalWriteHook(void) const; void SetPathWriteHook(CObjectOStream* stream, const string& path, CWriteChoiceVariantHook* hook) const; void SetLocalCopyHook(CObjectStreamCopier& stream, CCopyChoiceVariantHook* hook) const; void SetGlobalCopyHook(CCopyChoiceVariantHook* hook) const; void ResetLocalCopyHook(CObjectStreamCopier& stream) const; void ResetGlobalCopyHook(void) const; void SetPathCopyHook(CObjectStreamCopier* stream, const string& path, CCopyChoiceVariantHook* hook) const; public: // mostly for internal use const CVariantInfo* GetVariantInfo(void) const; protected: const CChoiceTypeInfo* GetChoiceTypeInfo(void) const; void Init(const CObjectTypeInfo& info); void Init(const CObjectTypeInfo& info, TMemberIndex index); void Init(const CConstObjectInfo& object); private: const CChoiceTypeInfo* m_ChoiceTypeInfo; TMemberIndex m_VariantIndex; private: CVariantInfo* GetNCVariantInfo(void) const; }; ///////////////////////////////////////////////////////////////////////////// /// /// CConstObjectInfoCV -- /// /// Choice variant /// provides read access to the variant data. class NCBI_XSERIAL_EXPORT CConstObjectInfoCV : public CObjectTypeInfoCV { typedef CObjectTypeInfoCV CParent; public: CConstObjectInfoCV(void); CConstObjectInfoCV(const CConstObjectInfo& object); CConstObjectInfoCV(const CConstObjectInfo& object, TMemberIndex index); /// Get containing choice const CConstObjectInfo& GetChoiceObject(void) const; CConstObjectInfoCV& operator=(const CConstObjectInfo& object); /// Get variant data CConstObjectInfo GetVariant(void) const; /// Get variant data CConstObjectInfo operator*(void) const; private: pair<TConstObjectPtr, TTypeInfo> GetVariantPair(void) const; CConstObjectInfo m_Object; TMemberIndex m_VariantIndex; }; ///////////////////////////////////////////////////////////////////////////// /// /// CObjectInfoCV -- /// /// Choice variant /// provides read/write access to the variant data. class NCBI_XSERIAL_EXPORT CObjectInfoCV : public CObjectTypeInfoCV { typedef CObjectTypeInfoCV CParent; public: CObjectInfoCV(void); CObjectInfoCV(const CObjectInfo& object); CObjectInfoCV(const CObjectInfo& object, TMemberIndex index); /// Get containing choice const CObjectInfo& GetChoiceObject(void) const; CObjectInfoCV& operator=(const CObjectInfo& object); /// Get variant data CObjectInfo GetVariant(void) const; /// Get variant data CObjectInfo operator*(void) const; private: pair<TObjectPtr, TTypeInfo> GetVariantPair(void) const; CObjectInfo m_Object; }; /* @} */ #include <serial/impl/objectiter.inl> END_NCBI_SCOPE #endif /* OBJECTITER__HPP */
30.321951
80
0.673155
OpenHero
f79e4d3d0d08758c029c1a0777b72963507d59c7
480
cpp
C++
abc073/abc073_c.cpp
crazystylus/AtCoderPractice
8e0f56a9b3905e11f83f351af66af5bfed8606b2
[ "MIT" ]
null
null
null
abc073/abc073_c.cpp
crazystylus/AtCoderPractice
8e0f56a9b3905e11f83f351af66af5bfed8606b2
[ "MIT" ]
null
null
null
abc073/abc073_c.cpp
crazystylus/AtCoderPractice
8e0f56a9b3905e11f83f351af66af5bfed8606b2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define rep(i, n) for (int i = 0; i < n; i++) const int mod = 1e9 + 7; // 10^9 + 7; const int N = 1e5 + 1; /////////////////// int n; void solve() { int a; unordered_map<int, bool> hm; cin >> n; rep(i, n) { cin >> a; if (hm.find(a) == hm.end()) hm[a] = true; else hm.erase(a); } cout << hm.size() << "\n"; } int main() { solve(); return 0; }
17.777778
45
0.50625
crazystylus
f7a1768f3a9de02f8d54c2d4d98edc0f542d978a
38,078
cpp
C++
OCVWarp.cpp
hn-88/OCVWarp
8cae8dc544bad18bc91a2c6635b6edb96985b4bc
[ "MIT" ]
2
2020-04-01T02:43:13.000Z
2020-06-28T13:52:03.000Z
OCVWarp.cpp
hn-88/OCVWarp
8cae8dc544bad18bc91a2c6635b6edb96985b4bc
[ "MIT" ]
13
2020-04-01T08:06:50.000Z
2021-01-16T15:47:15.000Z
OCVWarp.cpp
hn-88/OCVWarp
8cae8dc544bad18bc91a2c6635b6edb96985b4bc
[ "MIT" ]
null
null
null
#ifdef _WIN64 #include "windows.h" #endif /* * OCVWarp.cpp * * Warps video files using the OpenCV framework. * Appends F to the filename and saves as default codec (DIVX avi) in the same folder. * * first commit: * Hari Nandakumar * 25 Jan 2020 * * */ //#define _WIN64 //#define __unix__ // references // http://paulbourke.net/geometry/transformationprojection/ // equations in figure at http://paulbourke.net/dome/dualfish2sphere/ // http://paulbourke.net/dome/dualfish2sphere/diagram.pdf // http://www.fmwconcepts.com/imagemagick/fisheye2pano/index.php // http://www.fmwconcepts.com/imagemagick/pano2fisheye/index.php // // https://docs.opencv.org/3.4/d8/dfe/classcv_1_1VideoCapture.html // https://docs.opencv.org/3.4/d7/d9e/tutorial_video_write.html // https://docs.opencv.org/3.4.9/d1/da0/tutorial_remap.html // https://stackoverflow.com/questions/60221/how-to-animate-the-command-line // https://stackoverflow.com/questions/11498169/dealing-with-angle-wrap-in-c-code // https://blog.kowalczyk.info/article/j/guide-to-predefined-macros-in-c-compilers-gcc-clang-msvc-etc..html // Pertinent equations from pano2fisheye: // fov=180 for fisheye // fov=2*phimax or phimax=fov/2 // note rmax=N/2; N=height of input // linear: r=f*phi; f=rmax/phimax; f=(N/2)/((fov/2)*(pi/180))=N*180/(fov*pi) // substitute fov=180 // linear: f=N/pi // linear: phi=r*pi/N // https://stackoverflow.com/questions/46883320/conversion-from-dual-fisheye-coordinates-to-equirectangular-coordinates // taking Paul's page as ref, http://paulbourke.net/dome/dualfish2sphere/diagram.pdf /* // 2D fisheye to 3D vector phi = r * aperture / 2 theta = atan2(y, x) // 3D vector to longitude/latitude longitude = atan2(Py, Px) latitude = atan2(Pz, (Px^2 + Py^2)^(0.5)) // 3D vector to 2D equirectangular x = longitude / PI y = 2 * latitude / PI * ***/ /* * https://groups.google.com/forum/#!topic/hugin-ptx/wB-4LJHH5QI * panotools code * */ #include <stdio.h> #include <stdlib.h> #ifdef __unix__ #include <unistd.h> #endif #include <string.h> #include <time.h> //#include <sys/stat.h> // this is for mkdir #include <opencv2/opencv.hpp> #include "tinyfiledialogs.h" #define CV_PI 3.1415926535897932384626433832795 using namespace cv; // some global variables std::string strpathtowarpfile; Mat meshu, meshv, meshx, meshy, meshi, I; Mat map2x, map2y; float maxx=0, minx=0; float maxu=0, minu=0, maxv=0, minv=0; // meshx is in the range [-aspectratio, aspectratio] // we assume meshy is in the range [-1,1] // meshu and meshv in [0,1] bool ReadMesh(std::string strpathtowarpfile) { //from https://github.com/hn-88/GL_warp2Avi/blob/master/GL2AviView.cpp // and http://paulbourke.net/dataformats/meshwarp/ FILE *input = NULL; input = fopen(strpathtowarpfile.c_str(), "r"); /* Set rows and columns to 2 initially, as this is the size of the default mesh. */ int dummy, rows = 2, cols = 2; if (input != NULL) { fscanf(input, " %d %d %d ", &dummy, &cols, &rows) ; float x, y, u, v, l; //meshrows=rows; //meshcolumns=cols; meshx = Mat(Size(cols,rows), CV_32FC1); meshy = Mat(Size(cols,rows), CV_32FC1); meshu = Mat(Size(cols,rows), CV_32FC1); meshv = Mat(Size(cols,rows), CV_32FC1); meshi = Mat(Size(cols,rows), CV_32FC1); for (int r = 0; r < rows ; r++) { for (int c = 0; c < cols ; c++) { fscanf(input, "%f %f %f %f %f", &x, &y, &u, &v, &l) ; if (x<minx) minx = x; else if (x>maxx) maxx = x; if (u<minu) minu = u; else if (u>maxu) maxu = u; if (v<minv) minv = v; else if (v>maxv) maxv = v; //~ mesh[cols*r+c].x = x; //~ mesh[cols*r+c].y = y; //~ mesh[cols*r+c].u = u; //~ mesh[cols*r+c].v = v; //~ mesh[cols*r+c].i = l; meshx.at<float>(r,c) = x; meshy.at<float>(r,c) = y; meshu.at<float>(r,c) = u; meshv.at<float>(r,c) = v; meshi.at<float>(r,c) = l; } } } else // unable to read mesh { std::cout << "Unable to read mesh data file (similar to EP_xyuv_1920.map), exiting!" << std::endl; exit(0); } return 1; } void update_map( double anglex, double angley, Mat &map_x, Mat &map_y, int transformtype ) { // explanation comments are most verbose in the last // default (transformtype == 0) section switch (transformtype) { case 5: // 360 to 180 fisheye and then to warped //if (transformtype == 5) { // create temp maps to the texture and then map from texture to output // this will need 2 remaps at the output side // and two sets of map files // the map file for the first remap has to change with change of anglex angley // the second one, for fisheye to warped, doesn't need to be recalculated. // so, update_map is called first to initialize map_x and map_y // using transformtype = 4 // and later, and at all other times, only the map to the texture is updated. update_map( anglex, angley, map2x, map2y, 1 ); } break; case 4: //if (transformtype == 4) // fisheye to warped { // similar to TGAWarp at http://paulbourke.net/dome/tgawarp/ // Mat U, V, X, Y, IC1; Mat indexu, indexv, indexx, indexy, temp; ReadMesh(strpathtowarpfile); //resize(meshx, X, map_x.size(), INTER_LINEAR); //resize(meshy, Y, map_x.size(), INTER_LINEAR); //debug - changed INTER_LINEAR to INTER_LANCZOS4 and later INTER_CUBIC // not much of a penalty, so we leave it in. // discard the top/bottom line of U and V, since they cause // the bottom of the image to be repeats of the same //~ Mat meshub, meshvb; //~ meshu(cv::Rect(0,0,meshu.cols,(meshu.rows-1))).copyTo(meshub); //~ meshv(cv::Rect(0,0,meshv.cols,(meshv.rows-1))).copyTo(meshvb); // this doesn't work // for per pixel equivalence with GL_warp, the following seems to be needed int extrarows = map_x.rows / meshu.rows ; int extracols = map_x.cols / meshu.cols; resize(meshu, U, Size(map_x.cols+extracols, (map_x.rows+extrarows)), INTER_CUBIC); resize(meshv, V, Size(map_x.cols+extracols, (map_x.rows+extrarows)), INTER_CUBIC); //resize(meshu, U, map_x.size(), INTER_CUBIC); //resize(meshv, V, map_x.size(), INTER_CUBIC); resize(meshi, IC1, map_x.size(), INTER_CUBIC); // I.convertTo(I, CV_32FC3); //this doesn't work //convert to 3 channel Mat, for later multiplication // https://stackoverflow.com/questions/23303305/opencv-element-wise-matrix-multiplication/23310109 Mat t[] = {IC1, IC1, IC1}; merge(t, 3, I); // map the values which are [minx,maxx] to [0,map_x.cols-1] //~ temp = (map_x.cols-1)*(X - minx)/(maxx-minx); //~ temp.convertTo(indexx, CV_32S); // this does the rounding to int //~ temp = (map_x.rows-1)*(Y+1)/2; // assuming miny=-1, maxy=1 //~ temp.convertTo(indexy, CV_32S); temp = (map_x.cols-1)*U; // assuming minu=0, maxu=1 temp.convertTo(indexu, CV_32S); // this does the rounding to int temp = (map_x.rows-1)*V; // assuming minv=0, maxv=1 //~ temp = (map_x.rows)*(V-minv)/(maxv-minv); temp.convertTo(indexv, CV_32S); int linestodiscard = map_x.rows / meshu.rows / 2; int colstodiscard = map_x.cols / meshu.cols / 2; for ( int i = 0; i < (map_x.rows); i++ ) // here, i is for y and j is for x { for ( int j = 0; j < map_x.cols; j++ ) { //~ map_x.at<float>(i, j) = (float)(j); // this just maps input to output //~ map_y.at<float>(i, j) = (float)(i); // in the following, we assume indexx.at<int>(i,j) = j // and indexy.at<int>(i,j) = i // otherwise, a mesh effect due to discontinuities in indexx and indexy. map_x.at<float>(i,j) = (float) indexu.at<int>(i+linestodiscard,j+colstodiscard); map_y.at<float>(i,j) = (float) indexv.at<int>(i+linestodiscard,j+colstodiscard); } //end for j } //end for i return; } break; case 3: //if (transformtype == 3) // fisheye to Equirectangular - dual output - using parallel projection { // int xcd = floor(map_x.cols/2) - 1 + anglex; // this just 'pans' the view // int ycd = floor(map_x.rows/2) - 1 + angley; int xcd = floor(map_x.cols/2) - 1 ; int ycd = floor(map_x.rows/2) - 1 ; float px_per_theta = map_x.cols * 2 / (2*CV_PI); // src width = map_x.cols * 2 float px_per_phi = map_x.rows / CV_PI; // src height = PI for equirect 360 float rad_per_px = CV_PI / map_x.rows; float theta; float longi, lat, Px, Py, Pz, R; // X and Y are map_x and map_y float PxR, PyR, PzR; float aperture = CV_PI; // this is the only change between type 2 & 3 float angleyrad = -angley*CV_PI/180; // made these minus for more intuitive feel float anglexrad = -anglex*CV_PI/180; for ( int i = 0; i < map_x.rows; i++ ) // here, i is for y and j is for x { for ( int j = 0; j < map_x.cols; j++ ) { longi = (CV_PI ) * (j - xcd) / (map_x.cols/2); // longi = x.pi for 360 image lat = (CV_PI / 2) * (i - ycd) / (map_x.rows/2); // lat = y.pi/2 Px = cos(lat)*cos(longi); Py = cos(lat)*sin(longi); Pz = sin(lat); if(angley!=0 || anglex!=0) { // cos(angleyrad), 0, sin(angleyrad), 0, 1, 0, -sin(angleyrad), 0, cos(angleyrad)); PxR = Px; PyR = cos(angleyrad) * Py - sin(angleyrad) * Pz; PzR = sin(angleyrad) * Py + cos(angleyrad) * Pz; Px = cos(anglexrad) * PxR - sin(anglexrad) * PyR; Py = sin(anglexrad) * PxR + cos(anglexrad) * PyR; Pz = PzR; } if (Px == 0 && Py == 0 && Pz == 0) R = 0; else R = 2 * atan2(sqrt(Px*Px + Pz*Pz), Py) / aperture; if (Px == 0 && Pz ==0) theta = 0; else theta = atan2(Pz, Px); // map_x.at<float>(i, j) = R * cos(theta); this maps to [-1, 1] //map_x.at<float>(i, j) = R * cos(theta) * map_x.cols / 2 + xcd; map_x.at<float>(i, j) = - Px * map_x.cols / 2 + xcd; // this gives two copies in final output, top one reasonably correct // map_y.at<float>(i, j) = R * sin(theta); this maps to [-1, 1] //map_y.at<float>(i, j) = R * sin(theta) * map_x.rows / 2 + ycd; map_y.at<float>(i, j) = Py * map_x.rows / 2 + ycd; } // for j } // for i } break; case 2: //if (transformtype == 2) // 360 degree fisheye to Equirectangular 360 { // int xcd = floor(map_x.cols/2) - 1 + anglex; // this just 'pans' the view // int ycd = floor(map_x.rows/2) - 1 + angley; int xcd = floor(map_x.cols/2) - 1 ; int ycd = floor(map_x.rows/2) - 1 ; float px_per_theta = map_x.cols / (2*CV_PI); // width = map_x.cols float px_per_phi = map_x.rows / CV_PI; // height = PI for equirect 360 float rad_per_px = CV_PI / map_x.rows; float theta; float longi, lat, Px, Py, Pz, R; // X and Y are map_x and map_y float PxR, PyR, PzR; float aperture = 2*CV_PI; float angleyrad = -angley*CV_PI/180; // made these minus for more intuitive feel float anglexrad = -anglex*CV_PI/180; for ( int i = 0; i < map_x.rows; i++ ) // here, i is for y and j is for x { for ( int j = 0; j < map_x.cols; j++ ) { longi = (CV_PI ) * (j - xcd) / (map_x.cols/2); // longi = x.pi for 360 image lat = (CV_PI / 2) * (i - ycd) / (map_x.rows/2); // lat = y.pi/2 Px = cos(lat)*cos(longi); Py = cos(lat)*sin(longi); Pz = sin(lat); if(angley!=0 || anglex!=0) { // cos(angleyrad), 0, sin(angleyrad), 0, 1, 0, -sin(angleyrad), 0, cos(angleyrad)); PxR = Px; PyR = cos(angleyrad) * Py - sin(angleyrad) * Pz; PzR = sin(angleyrad) * Py + cos(angleyrad) * Pz; Px = cos(anglexrad) * PxR - sin(anglexrad) * PyR; Py = sin(anglexrad) * PxR + cos(anglexrad) * PyR; Pz = PzR; } if (Px == 0 && Py == 0 && Pz == 0) R = 0; else R = 2 * atan2(sqrt(Px*Px + Py*Py), Pz) / aperture; // exchanged Py and Pz from Paul's co-ords, // from Perspective projection the wrong imaging model 10.1.1.52.8827.pdf // http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.52.8827&rep=rep1&type=pdf // Or else, Africa ends up sideways, and with the far east and west streched out on top and bottom if (Px == 0 && Pz ==0) theta = 0; else theta = atan2(Py, Px); // map_x.at<float>(i, j) = R * cos(theta); this maps to [-1, 1] map_x.at<float>(i, j) = R * cos(theta) * map_x.cols / 2 + xcd; // currently upside down // map_y.at<float>(i, j) = R * sin(theta); this maps to [-1, 1] map_y.at<float>(i, j) = R * sin(theta) * map_x.rows / 2 + ycd; } // for j } // for i } break; case 1: //if (transformtype == 1) // Equirectangular 360 to 180 degree fisheye { // using the transformations at // http://paulbourke.net/dome/dualfish2sphere/diagram.pdf int xcd = floor(map_x.cols/2) - 1 ; int ycd = floor(map_x.rows/2) - 1 ; float halfcols = map_x.cols/2; float halfrows = map_x.rows/2; float longi, lat, Px, Py, Pz, theta; // X and Y are map_x and map_y float xfish, yfish, rfish, phi, xequi, yequi; float PxR, PyR, PzR; float aperture = CV_PI; float angleyrad = -angley*CV_PI/180; // made these minus for more intuitive feel float anglexrad = -anglex*CV_PI/180; //Mat inputmatrix, rotationmatrix, outputmatrix; // https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations //rotationmatrix = (Mat_<float>(3,3) << cos(angleyrad), 0, sin(angleyrad), 0, 1, 0, -sin(angleyrad), 0, cos(angleyrad)); //y //rotationmatrix = (Mat_<float>(3,3) << 1, 0, 0, 0, cos(angleyrad), -sin(angleyrad), 0, sin(angleyrad), cos(angleyrad)); //x //rotationmatrix = (Mat_<float>(3,3) << cos(angleyrad), -sin(angleyrad), 0, sin(angleyrad), cos(angleyrad), 0, 0, 0, 1); //z for ( int i = 0; i < map_x.rows; i++ ) // here, i is for y and j is for x { for ( int j = 0; j < map_x.cols; j++ ) { // normalizing to [-1, 1] xfish = (j - xcd) / halfcols; yfish = (i - ycd) / halfrows; rfish = sqrt(xfish*xfish + yfish*yfish); theta = atan2(yfish, xfish); phi = rfish*aperture/2; // Paul's co-ords - this is suitable when phi=0 is Pz=0 //Px = cos(phi)*cos(theta); //Py = cos(phi)*sin(theta); //Pz = sin(phi); // standard co-ords - this is suitable when phi=pi/2 is Pz=0 Px = sin(phi)*cos(theta); Py = sin(phi)*sin(theta); Pz = cos(phi); if(angley!=0 || anglex!=0) { // cos(angleyrad), 0, sin(angleyrad), 0, 1, 0, -sin(angleyrad), 0, cos(angleyrad)); PxR = Px; PyR = cos(angleyrad) * Py - sin(angleyrad) * Pz; PzR = sin(angleyrad) * Py + cos(angleyrad) * Pz; Px = cos(anglexrad) * PxR - sin(anglexrad) * PyR; Py = sin(anglexrad) * PxR + cos(anglexrad) * PyR; Pz = PzR; } longi = atan2(Py, Px); lat = atan2(Pz,sqrt(Px*Px + Py*Py)); // this gives south pole centred, ie yequi goes from [-1, 0] // Made into north pole centred by - (minus) in the final map_y assignment xequi = longi / CV_PI; // this maps to [-1, 1] yequi = 2*lat / CV_PI; // this maps to [-1, 0] for south pole //if (rfish <= 1.0) // outside that circle, let it be black // removed the black circle to help transformtype=5 // avoid bottom pixels black { map_x.at<float>(i, j) = abs(xequi * map_x.cols / 2 + xcd); //map_y.at<float>(i, j) = yequi * map_x.rows / 2 + ycd; // this gets south pole centred view // the abs is to correct for -0.5 xequi value at longi=0 map_y.at<float>(i, j) = yequi * map_x.rows / 2 + ycd; //debug //~ if (rfish <= 1.0/500) //if ((longi==0)||(longi==CV_PI)||(longi==-CV_PI)) //if (lat==0) // since these are floats, probably doesn't work //~ { //~ std::cout << "i,j,mapx,mapy="; //~ std::cout << i << ", "; //~ std::cout << j << ", "; //~ std::cout << map_x.at<float>(i, j) << ", "; //~ std::cout << map_y.at<float>(i, j) << std::endl; //~ } } } // for j } // for i } break; case 0: default: //else //if (transformtype == 0) // the default // Equirectangular 360 to 360 degree fisheye { // using code adapted from http://www.fmwconcepts.com/imagemagick/pano2fisheye/index.php // set destination (output) centers //~ // changing this to code based on Paul's diagram in version 2.1 // so that anglex and angley both work ////////////////////////////////////////////////////////////// //~ int xcd = floor(map_x.cols/2) - 1; //~ int ycd = floor(map_x.rows/2) - 1; //~ int xd, yd; //~ //define destination (output) coordinates center relative xd,yd //~ // "xd= x - xcd;" //~ // "yd= y - ycd;" //~ // compute input pixels per angle in radians //~ // theta ranges from -180 to 180 = 360 = 2*pi //~ // phi ranges from 0 to 90 = pi/2 //~ float px_per_theta = map_x.cols / (2*CV_PI); //~ float px_per_phi = map_x.rows / (CV_PI/2); //~ // compute destination radius and theta //~ float rd; // = sqrt(x^2+y^2); //~ // set theta so original is north rather than east //~ float theta; //= atan2(y,x); //~ // convert radius to phiang according to fisheye mode //~ //if projection is linear then //~ // destination output diameter (dimensions) corresponds to 180 deg = pi (fov); angle is proportional to radius //~ float rad_per_px = CV_PI / map_x.rows; //~ float phiang; // = rad_per_px * rd; //~ // convert theta to source (input) xs and phi to source ys //~ // -rotate 90 aligns theta=0 with north and is faster than including in theta computation //~ // y corresponds to h-phi, so that bottom of the input is center of output //~ // xs = width + theta * px_per_theta; //~ // ys = height - phiang * px_per_phi; //~ for ( int i = 0; i < map_x.rows; i++ ) // here, i is for y and j is for x //~ { //~ for ( int j = 0; j < map_x.cols; j++ ) //~ { //~ xd = j - xcd; //~ yd = i - ycd; //~ if (xd == 0 && yd == 0) //~ { //~ theta = 0 + anglex*CV_PI/180; //~ rd = 0; //~ } //~ else //~ { //~ //theta = atan2(float(yd),float(xd)); // this sets orig to east //~ // so America, at left of globe, becomes centred //~ theta = atan2(xd,yd) + anglex*CV_PI/180;; // this sets orig to north //~ // makes the fisheye left/right flipped if atan2(-xd,yd) //~ // so that Africa is centred when anglex = 0. //~ rd = sqrt(float(xd*xd + yd*yd)); //~ } //~ // move theta to [-pi, pi] //~ theta = fmod(theta+CV_PI, 2*CV_PI); //~ if (theta < 0) //~ theta = theta + CV_PI; //~ theta = theta - CV_PI; //~ //phiang = rad_per_px * rd + angley*CV_PI/180; // this zooms in/out, not rotate cam //~ phiang = rad_per_px * rd; //~ map_x.at<float>(i, j) = (float)round((map_x.cols/2) + theta * px_per_theta); //~ //map_y.at<float>(i, j) = (float)round((map_x.rows) - phiang * px_per_phi); //~ // this above makes the south pole the centre. //~ map_y.at<float>(i, j) = phiang * px_per_phi; //~ // this above makes the north pole the centre of the fisheye //~ // map_y.at<float>(i, j) = phiang * px_per_phi - angley; //this just zooms out //~ // the following test mapping just makes the src upside down in dst //~ // map_x.at<float>(i, j) = (float)j; //~ // map_y.at<float>(i, j) = (float)( i); //~ } // for j //~ } // for i ////////////////////////////////////// // the following code is similar to transformtype=1 code // with only the "aperture" changed to 2pi int xcd = floor(map_x.cols/2) - 1 ; int ycd = floor(map_x.rows/2) - 1 ; float halfcols = map_x.cols/2; float halfrows = map_x.rows/2; float longi, lat, Px, Py, Pz, theta; // X and Y are map_x and map_y float xfish, yfish, rfish, phi, xequi, yequi; float PxR, PyR, PzR; float aperture = 2*CV_PI; float angleyrad = -angley*CV_PI/180; // made these minus for more intuitive feel float anglexrad = -anglex*CV_PI/180; //Mat inputmatrix, rotationmatrix, outputmatrix; // https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations //rotationmatrix = (Mat_<float>(3,3) << cos(angleyrad), 0, sin(angleyrad), 0, 1, 0, -sin(angleyrad), 0, cos(angleyrad)); //y //rotationmatrix = (Mat_<float>(3,3) << 1, 0, 0, 0, cos(angleyrad), -sin(angleyrad), 0, sin(angleyrad), cos(angleyrad)); //x //rotationmatrix = (Mat_<float>(3,3) << cos(angleyrad), -sin(angleyrad), 0, sin(angleyrad), cos(angleyrad), 0, 0, 0, 1); //z for ( int i = 0; i < map_x.rows; i++ ) // here, i is for y and j is for x { for ( int j = 0; j < map_x.cols; j++ ) { // normalizing to [-1, 1] xfish = (j - xcd) / halfcols; yfish = (i - ycd) / halfrows; rfish = sqrt(xfish*xfish + yfish*yfish); theta = atan2(yfish, xfish); phi = rfish*aperture/2; // Paul's co-ords - this is suitable when phi=0 is Pz=0 //Px = cos(phi)*cos(theta); //Py = cos(phi)*sin(theta); //Pz = sin(phi); // standard co-ords - this is suitable when phi=pi/2 is Pz=0 Px = sin(phi)*cos(theta); Py = sin(phi)*sin(theta); Pz = cos(phi); if(angley!=0 || anglex!=0) { // cos(angleyrad), 0, sin(angleyrad), 0, 1, 0, -sin(angleyrad), 0, cos(angleyrad)); PxR = Px; PyR = cos(angleyrad) * Py - sin(angleyrad) * Pz; PzR = sin(angleyrad) * Py + cos(angleyrad) * Pz; Px = cos(anglexrad) * PxR - sin(anglexrad) * PyR; Py = sin(anglexrad) * PxR + cos(anglexrad) * PyR; Pz = PzR; } longi = atan2(Py, Px); lat = atan2(Pz,sqrt(Px*Px + Py*Py)); // this gives south pole centred, ie yequi goes from [-1, 0] // Made into north pole centred by - (minus) in the final map_y assignment xequi = longi / CV_PI; // this maps to [-1, 1] yequi = 2*lat / CV_PI; // this maps to [-1, 0] for south pole //if (rfish <= 1.0) // outside that circle, let it be black // removed the black circle to help transformtype=5 // avoid bottom pixels black { map_x.at<float>(i, j) = abs(xequi * map_x.cols / 2 + xcd); //map_y.at<float>(i, j) = yequi * map_x.rows / 2 + ycd; // this gets south pole centred view // the abs is to correct for -0.5 xequi value at longi=0 map_y.at<float>(i, j) = yequi * map_x.rows / 2 + ycd; } } // for j } // for i } // end of if transformtype == 0 } // end switch case } // end function updatemap std::string escaped(const std::string& input) { // https://stackoverflow.com/questions/48260879/how-to-replace-with-in-c-string std::string output; output.reserve(input.size()); for (const char c: input) { switch (c) { case '\a': output += "\\a"; break; case '\b': output += "\\b"; break; case '\f': output += "\\f"; break; case '\n': output += "\\n"; break; case '\r': output += "\\r"; break; case '\t': output += "\\t"; break; case '\v': output += "\\v"; break; default: output += c; break; } } return output; } int main(int argc,char *argv[]) { //////////////////////////////////////////////////////////////////// // Initializing variables //////////////////////////////////////////////////////////////////// bool doneflag = 0, interactivemode = 0; bool showdisplay = 1; double anglex = 0; double angley = 0; int outputw = 1920; int outputh = 1080; int texturew = 2048; std::string tempstring; //std::string strpathtowarpfile; making this a global var strpathtowarpfile = "EP_xyuv_1920.map"; char anglexstr[40]; char angleystr[40]; char outputfourccstr[40]; // leaving extra chars for not overflowing too easily outputfourccstr[0] = 'N'; outputfourccstr[1] = 'U'; outputfourccstr[2] = 'L'; outputfourccstr[3] = 'L'; //const bool askOutputType = argv[3][0] =='Y'; // If false it will use the inputs codec type // this line above causes the windows build to not run! although it compiles ok. // askOutputType=1 works only on Windows (vfw?) currently const bool askOutputType = 0; std::ifstream infile("OCVWarp.ini"); int transformtype = 0; // 0 = Equirectangular to 360 degree fisheye // 1 = Equirectangular to 180 degree fisheye int ind = 1; // inputs from ini file if (infile.is_open()) { infile >> tempstring; infile >> tempstring; infile >> tempstring; // first three lines of ini file are comments infile >> anglexstr; infile >> tempstring; infile >> angleystr; infile >> tempstring; infile >> outputw; infile >> tempstring; infile >> outputh; infile >> tempstring; infile >> transformtype; infile >> tempstring; infile >> outputfourccstr; infile >> tempstring; infile >> strpathtowarpfile; infile.close(); anglex = atof(anglexstr); angley = atof(angleystr); } else std::cout << "Unable to open ini file, using defaults." << std::endl; std::cout << "Output codec type: " << outputfourccstr << std::endl; namedWindow("Display", WINDOW_NORMAL | WINDOW_KEEPRATIO); // 0 = WINDOW_NORMAL resizeWindow("Display", round((float)(outputw)/(float)(outputh)*600), 600); // this doesn't work? moveWindow("Display", 0, 0); char const * FilterPatterns[2] = { "*.avi","*.*" }; char const * OpenFileName = tinyfd_openFileDialog( "Open a video file", "", 2, FilterPatterns, NULL, 0); if (! OpenFileName) { tinyfd_messageBox( "Error", "No file chosen. ", "ok", "error", 1); return 1 ; } // reference: // https://docs.opencv.org/3.4/d7/d9e/tutorial_video_write.html #ifdef __unix__ VideoCapture inputVideo(OpenFileName); // Open input #else // #ifdef _WIN64 assuming Windows // otherwise, multiple definitions when building on Windows x64 // Here, OpenCV on Windows needs escaped file paths. // https://stackoverflow.com/questions/48260879/how-to-replace-with-in-c-string std::string escapedpath = escaped(std::string(OpenFileName)); VideoCapture inputVideo(escapedpath.c_str()); // Open input #endif //~ #ifdef _WIN32 //~ // Here, OpenCV on Windows needs escaped file paths. //~ // https://stackoverflow.com/questions/48260879/how-to-replace-with-in-c-string //~ std::string escapedpath = escaped(std::string(OpenFileName)); //~ VideoCapture inputVideo(escapedpath.c_str()); // Open input //~ #endif //~ #ifdef __MINGW32__ //~ // Here, OpenCV on Windows needs escaped file paths. //~ // https://stackoverflow.com/questions/48260879/how-to-replace-with-in-c-string //~ std::string escapedpath = escaped(std::string(OpenFileName)); //~ VideoCapture inputVideo(escapedpath.c_str()); // Open input //~ #endif //~ #ifdef __MINGW64__ //~ // Here, OpenCV on Windows needs escaped file paths. //~ // https://stackoverflow.com/questions/48260879/how-to-replace-with-in-c-string //~ std::string escapedpath = escaped(std::string(OpenFileName)); //~ VideoCapture inputVideo(escapedpath.c_str()); // Open input //~ #endif if (!inputVideo.isOpened()) { std::cout << "Could not open the input video: " << OpenFileName << std::endl; return -1; } #ifdef __unix__ std::string OpenFileNamestr = OpenFileName; #else //#ifdef _WIN64 // Here, OpenCV on Windows needs escaped file paths. std::string OpenFileNamestr = escapedpath; #endif //~ #ifdef _WIN32 //~ // Here, OpenCV on Windows needs escaped file paths. //~ std::string OpenFileNamestr = escapedpath; //~ #endif //~ #ifdef __MINGW32__ //~ // Here, OpenCV on Windows needs escaped file paths. //~ std::string OpenFileNamestr = escapedpath; //~ #endif //~ #ifdef __MINGW64__ //~ // Here, OpenCV on Windows needs escaped file paths. //~ std::string OpenFileNamestr = escapedpath; //~ #endif std::string::size_type pAt = OpenFileNamestr.find_last_of('.'); // Find extension point std::string NAME = OpenFileNamestr.substr(0, pAt) + "F" + ".avi"; // Form the new name with container // here, we give an option for the user to choose the output file // path as well as type (container, like mp4, mov, avi). char const * SaveFileName = tinyfd_saveFileDialog( "Now enter the output video file name, like output.mp4", "", 0, NULL, NULL); if (! SaveFileName) { tinyfd_messageBox( "No output file chosen.", "Will be saved as inputfilename + F.avi", "ok", "info", 1); } else { #ifdef __unix__ NAME = std::string(SaveFileName); #else // for Windows, escape the \ characters in the path escapedpath = escaped(std::string(SaveFileName)); NAME = escapedpath; #endif } int ex = static_cast<int>(inputVideo.get(CAP_PROP_FOURCC)); // Get Codec Type- Int form // Transform from int to char via Bitwise operators char EXT[] = {(char)(ex & 0XFF) , (char)((ex & 0XFF00) >> 8),(char)((ex & 0XFF0000) >> 16),(char)((ex & 0XFF000000) >> 24), 0}; Size S = Size((int) inputVideo.get(CAP_PROP_FRAME_WIDTH), // Acquire input size (int) inputVideo.get(CAP_PROP_FRAME_HEIGHT)); Size Sout = Size(outputw,outputh); VideoWriter outputVideo; // Open the output //#ifdef _WIN64 // OpenCV on Windows can ask for a suitable fourcc. //outputVideo.open(NAME, -1, inputVideo.get(CAP_PROP_FPS), Sout, true); // this doesn't work well with the ffmpeg dll - don't use this. //#endif if (!(outputfourccstr[0] == 'N' && outputfourccstr[1] == 'U' && outputfourccstr[2] == 'L' && outputfourccstr[3] == 'L')) outputVideo.open(NAME, outputVideo.fourcc(outputfourccstr[0], outputfourccstr[1], outputfourccstr[2], outputfourccstr[3]), inputVideo.get(CAP_PROP_FPS), Sout, true); else outputVideo.open(NAME, ex, inputVideo.get(CAP_PROP_FPS), Sout, true); if (!outputVideo.isOpened()) { std::cout << "Could not open the output video for write: " << NAME << std::endl; return -1; } std::cout << "Input frame resolution: Width=" << S.width << " Height=" << S.height << " of nr#: " << inputVideo.get(CAP_PROP_FRAME_COUNT) << std::endl; std::cout << "Input codec type: " << EXT << std::endl; int fps, key; int t_start, t_end; unsigned long long framenum = 0; Mat src, res, tmp; Mat dstfloat, dstmult, dstres, dstflip; std::vector<Mat> spl; Mat dst(Sout, CV_8UC3); // S = src.size, and src.type = CV_8UC3 Mat dst2; // temp dst, for double remap Mat map_x, map_y; if ((transformtype == 4) || (transformtype == 5) ) { //~ map_x = Mat(Size(outputw*2,outputh*2), CV_32FC1); // for 2x resampling //~ map_y = Mat(Size(outputw*2,outputh*2), CV_32FC1); // the above code causes gridlines to appear in output if (outputw<961) //1K texturew = 1024; // debug //texturew = outputw; else if (outputw<1921) //2K texturew = 2048; else if (outputw<3841) //4K texturew = 4096; else // (outputw<7681) //8K texturew = 8192; // debug - had set Size to outputw,h map_x = Mat(Size(texturew,texturew), CV_32FC1); // for upsampling map_y = Mat(Size(texturew,texturew), CV_32FC1); if (transformtype == 5) { dst2 = Mat(Size(texturew,texturew), CV_32FC1); } } else { map_x = Mat(Sout, CV_32FC1); map_y = Mat(Sout, CV_32FC1); } Mat dst_x, dst_y; // Mat map2x, map2y // these are made global vars Mat dst2x, dst2y; // for transformtype=5, double remap if (transformtype == 5) { map2x = Mat(Size(texturew,texturew), CV_32FC1); map2y = Mat(Size(texturew,texturew), CV_32FC1); map2x = Scalar((texturew+texturew)*10); map2y = Scalar((texturew+texturew)*10); // initializing so that it points outside the image // so that unavailable pixels will be black } map_x = Scalar((outputw+outputh)*10); map_y = Scalar((outputw+outputh)*10); // initializing so that it points outside the image // so that unavailable pixels will be black if (transformtype == 5) { update_map(anglex, angley, map_x, map_y, 4); // first initialize map_x and map_y for final warp, // which is exactly like transformtype=4 update_map(anglex, angley, map2x, map2y, 5); convertMaps(map_x, map_y, dst_x, dst_y, CV_16SC2); // supposed to make it faster to remap convertMaps(map2x, map2y, dst2x, dst2y, CV_16SC2); } else { update_map(anglex, angley, map_x, map_y, transformtype); // debug //~ dst_x = map_x; //~ dst_y = map_y; convertMaps(map_x, map_y, dst_x, dst_y, CV_16SC2); // supposed to make it faster to remap } t_start = time(NULL); fps = 0; for(;;) { inputVideo >> src; // read if (src.empty()) break; // check if at end //imshow("Display",src); key = waitKey(10); if(interactivemode) { if (transformtype==5) { // only map2 needs to be updated update_map(anglex, angley, map2x, map2y, 5); convertMaps(map2x, map2y, dst2x, dst2y, CV_16SC2); // supposed to make it faster to remap } else { update_map(anglex, angley, map_x, map_y, transformtype); convertMaps(map_x, map_y, dst_x, dst_y, CV_16SC2); // supposed to make it faster to remap } interactivemode = 0; } switch (transformtype) { case 5: // 360 to 180 fisheye and then to warped resize( src, res, Size(texturew, texturew), 0, 0, INTER_CUBIC); break; case 4: // 180 fisheye to warped // the transform needs a flipped source image, flipud flip(src, src, 0); // because the mesh assumes 0,0 is bottom left //debug - had changed to outputw, h resize( src, res, Size(texturew, texturew), 0, 0, INTER_CUBIC); break; case 3: // 360 fisheye to Equirect resize( src, res, Size(outputw, outputh), 0, 0, INTER_CUBIC); break; case 2: // 360 fisheye to Equirect resize( src, res, Size(outputw, outputh), 0, 0, INTER_CUBIC); break; case 1: // Equirect to 180 fisheye resize( src, res, Size(outputw, outputh), 0, 0, INTER_CUBIC); break; default: case 0: // Equirect to 360 fisheye resize( src, res, Size(outputw, outputh), 0, 0, INTER_CUBIC); break; } if (transformtype == 5) { // here we have two remaps remap( res, dst2, dst2x, dst2y, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 0) ); // the second remap needs flipping, like transformtype=4 flip(dst2, dst2, 0); // because the mesh assumes 0,0 is bottom left remap( dst2, dst, dst_x, dst_y, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 0) ); } else { remap( res, dst, dst_x, dst_y, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 0) ); } if ((transformtype == 4) || (transformtype == 5) ) { // multiply by the intensity Mat dst.convertTo(dstfloat, CV_32FC3); multiply(dstfloat, I, dstmult); //debug //dstmult = dstfloat; dstmult.convertTo(dstres, CV_8UC3); // this transform is 2x2 oversampled resize(dstres, dstflip, Size(outputw,outputh), 0, 0, INTER_AREA); flip(dstflip, dst, 0); // flip up down again } if(showdisplay) imshow("Display", dst); printf("\r"); fps++; t_end = time(NULL); if (t_end - t_start >= 5) { printf("Frame: %llu x: %.0f y: %.0f fps: %.1f \r", framenum++, anglex, angley, float(fps)/5 ); // extra spaces to delete previous line's characters if any fflush(stdout); t_start = time(NULL); fps = 0; } else { printf("Frame: %llu x: %.0f y: %.0f \r", framenum++, anglex, angley ); fflush(stdout); } //outputVideo.write(res); //save or outputVideo << dst; switch (key) { case 27: //ESC key case 'x': case 'X': doneflag = 1; break; case 'u': case '+': case '=': // increase angley angley = angley + 1.0; interactivemode = 1; break; case 'm': case '-': case '_': // decrease angley angley = angley - 1.0; interactivemode = 1; break; case 'k': case '}': case ']': // increase anglex anglex = anglex + 1.0; interactivemode = 1; break; case 'h': case '{': case '[': // decrease anglex anglex = anglex - 1.0; interactivemode = 1; break; case 'U': // increase angley angley = angley + 10.0; interactivemode = 1; break; case 'M': // decrease angley angley = angley - 10.0; interactivemode = 1; break; case 'K': // increase anglex anglex = anglex + 10.0; interactivemode = 1; break; case 'H': // decrease anglex anglex = anglex - 10.0; interactivemode = 1; break; case 'D': case 'd': // toggle display if(showdisplay) showdisplay=0; else showdisplay=1; break; default: break; } if (doneflag == 1) { break; } } // end for(;;) loop std::cout << std::endl << "Finished writing" << std::endl; return 0; } // end main
31.391591
131
0.582489
hn-88
f7a80c45731ec94d5a40e0d75f2160402e045f44
35,386
hpp
C++
src/include/core/smileComponent.hpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
245
2020-10-24T16:27:13.000Z
2022-03-31T03:01:11.000Z
src/include/core/smileComponent.hpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
41
2021-01-13T11:30:42.000Z
2022-01-14T14:36:11.000Z
src/include/core/smileComponent.hpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
43
2020-12-11T15:28:19.000Z
2022-03-20T11:55:58.000Z
/*F*************************************************************************** * This file is part of openSMILE. * * Copyright (c) audEERING GmbH. All rights reserved. * See the file COPYING for details on license terms. ***************************************************************************E*/ #ifndef __SMILE_COMPONENT_HPP #define __SMILE_COMPONENT_HPP #include <core/smileCommon.hpp> #include <core/configManager.hpp> #include <smileutil/JsonClasses.hpp> #include <chrono> #include <string> #define COMPONENT_DESCRIPTION_XXXX "example description" #define COMPONENT_NAME_XXXX "exampleName" #undef class class DLLEXPORT cComponentManager; class DLLEXPORT cSmileComponent; #define CMSG_textLen 64 #define CMSG_typenameLen 32 #define CMSG_nUserData 8 typedef enum { CUSTDATA_BINARY = 0, // unknown binary data CUSTDATA_TEXT = 100, // null terminated string CUSTDATA_JSONTEXT = 110, // json encoded as text CUSTDATA_CHAR = 110, // char array (size given in bytes by custDataSize) CUSTDATA_INT = 200, // array of ints (size given in bytes by custDataSize) CUSTDATA_FLOAT = 300, // array of floats (size given in bytes by custDataSize) CUSTDATA_DOUBLE = 400, // array of doubles (size given in bytes by custDataSize) CUSTDATA_FLOAT_DMEM = 500, // array of float_dmem (size given in bytes by custDataSize) CUSTDATA_CONTAINER = 1000 // container for object such as a JSON document, msgName will reveal details } eSmileMessageCustDataType; class DLLEXPORT cComponentMessage { public: // Note: since instances of this class may be accessed from other languages via the SMILEapi, // all fields must have types with fixed sizes on all supported platforms (e.g. use int instead of long). char msgtype[CMSG_typenameLen]; // message type name (used by receiver to identify message), set by constructor char msgname[CMSG_typenameLen]; // custom message name const char * sender; // name of sender component (filled in by sendComponentMessage in cSmileComponent) double smileTime; // seconds (accurate up to milliseconds) since componentManager startup (filled in by componentManager, TODO!) double userTime1; // user defined time double userTime2; // user defined time double readerTime; // readerTime in seconds (derived from vec->tmeta->vIdx and reader period in the tick the message ist sent), can also be -1.0 if not used! int msgid; // custom message id // -- message data -- double floatData[CMSG_nUserData]; // 8 freely usable doubles for message data, initialized with 0 int intData[CMSG_nUserData]; // 8 freely usable ints char msgtext[CMSG_textLen]; // 64 characters for message text, freely usable, initialized with all 0 int userflag1, userflag2, userflag3; void * custData; // pointer to custom message data (allocated by sender, to be freed by sender after call to sendComponentMessage) void * custData2; // pointer to custom message data (allocated by sender, to be freed by sender after call to sendComponentMessage) int custDataSize, custData2Size; // size (in bytes) of custData arrays. Used for network message senders (TODO: implement this properly in all components that allocate custData!) eSmileMessageCustDataType custDataType, custData2Type; // Type of custData arrays. Used for network message senders (TODO: implement this properly in all components that allocate custData!) cComponentMessage() { memset(this, 0, sizeof(cComponentMessage)); } cComponentMessage(const char *type, const char *name=NULL) : msgid(-1), sender(NULL), userflag1(0), userflag2(0), userflag3(0), smileTime(0.0), readerTime(-1.0), userTime1(0.0), userTime2(0.0), custData(NULL), custData2(NULL), custDataSize(0), custData2Size(0), custDataType(CUSTDATA_BINARY), custData2Type(CUSTDATA_BINARY) { if (type == NULL) memset(msgtype, 0, sizeof(char) * CMSG_typenameLen); else strncpy(msgtype, type, CMSG_typenameLen); if (name == NULL) memset(msgname, 0, sizeof(char) * CMSG_typenameLen); else strncpy(msgname, name, CMSG_typenameLen); memset(floatData, 0, sizeof(double) * CMSG_nUserData); memset(intData, 0, sizeof(int) * CMSG_nUserData); memset(msgtext, 0, sizeof(char) * CMSG_textLen); //printf("XXX: msgtype = '%s'\n", msgtype); //printf("XXX: msgname = '%s'\n", msgname); } char * createCustDataString(void * myCustData, int mySize, eSmileMessageCustDataType myType) { char * custDataText = NULL; if (myCustData != NULL) { if (myType == CUSTDATA_TEXT) { int strLength = mySize > 0 ? mySize : strlen((const char *)myCustData); custDataText = (char *)calloc(1, sizeof(char) * (strLength + 1)); strncpy(custDataText, (char *)myCustData, sizeof(char) * strLength); } else if (myType == CUSTDATA_CHAR) { custDataText = (char *)calloc(1, sizeof(char) * (mySize + 1)); strncpy(custDataText, (char *)myCustData, sizeof(char) * mySize); } else if (myType == CUSTDATA_FLOAT_DMEM) { std::string custDataFloats = "[ "; const FLOAT_DMEM *cdFloat = (const FLOAT_DMEM *)myCustData; int nSize = mySize / sizeof(FLOAT_DMEM); for (int i = 0; i < nSize - 1; i++) { char *tmp = myvprint("%f,", cdFloat[i]); custDataFloats += tmp; free(tmp); } if (nSize > 0) { char *tmp = myvprint("%f", cdFloat[nSize - 1]); custDataFloats += tmp; free(tmp); } custDataFloats += " ]"; custDataText = (char *)calloc(1, sizeof(char) * (custDataFloats.length() + 2) ); strncpy(custDataText, custDataFloats.c_str(), custDataFloats.length()); } } return custDataText; } // this function is outdated and will be removed in future releases... // it is advised to migrate to the new class // cSmileTcpJsonMessageFunctions /* * detail: * 0: print fewer fields, floatData 0 and intData 0 only * 10: print fewer fields, floatData 0-3 and intData 0-3 only * 20: print fewer field, float/int full * 30: print all fields, custData null * 40: print all fields, include custData */ // returned string must be freed by caller char * serializeToJson(int detail = 99, const char *recepient = NULL) { char msgtypeNullterminated[CMSG_typenameLen + 1]; char msgnameNullterminated[CMSG_typenameLen + 1]; strncpy(msgtypeNullterminated, msgtype, CMSG_typenameLen); strncpy(msgnameNullterminated, msgname, CMSG_typenameLen); msgtypeNullterminated[CMSG_typenameLen] = 0; msgnameNullterminated[CMSG_typenameLen] = 0; rapidjson::Document doc; doc.SetObject(); rapidjson::Document::AllocatorType &allocator = doc.GetAllocator(); if (recepient != NULL) { doc.AddMember("recepient", rapidjson::Value(recepient, allocator), allocator); } doc.AddMember("msgtype", rapidjson::Value(&msgtypeNullterminated[0], allocator), allocator); doc.AddMember("msgname", rapidjson::Value(&msgnameNullterminated[0], allocator), allocator); doc.AddMember("sender", rapidjson::Value(sender, allocator), allocator); doc.AddMember("smileTime", smileTime, allocator); doc.AddMember("userTime1", userTime1, allocator); if (detail >= 30) { doc.AddMember("userTime2", userTime2, allocator); doc.AddMember("readerTime", readerTime, allocator); } doc.AddMember("msgid", msgid, allocator); rapidjson::Value floatDataValue(rapidjson::kObjectType); for (int i = 0; i < CMSG_nUserData; i++) { std::string index = std::to_string(i); floatDataValue.AddMember(rapidjson::Value(index.c_str(), allocator).Move(), floatData[i], allocator); } doc.AddMember("floatData", floatDataValue, allocator); rapidjson::Value intDataValue(rapidjson::kObjectType); for (int i = 0; i < CMSG_nUserData; i++) { std::string index = std::to_string(i); intDataValue.AddMember(rapidjson::Value(index.c_str(), allocator).Move(), intData[i], allocator); } doc.AddMember("intData", intDataValue, allocator); doc.AddMember("msgtext", rapidjson::Value(msgtext, allocator), allocator); if (detail >= 30) { doc.AddMember("userflag1", userflag1, allocator); doc.AddMember("userflag2", userflag2, allocator); doc.AddMember("userflag3", userflag3, allocator); char *custDataText; char *custData2Text; if (detail >= 40) { custDataText = createCustDataString(custData, custDataSize, custDataType); // may return null custData2Text = createCustDataString(custData2, custData2Size, custData2Type); // may return null } else { custDataText = NULL; custData2Text = NULL; } if (custDataText != NULL) { doc.AddMember("custData", rapidjson::Value(custDataText, allocator), allocator); free(custDataText); } else { doc.AddMember("custData", rapidjson::Value(rapidjson::kNullType), allocator); } if (custData2Text != NULL) { doc.AddMember("custData2", rapidjson::Value(custData2Text, allocator), allocator); free(custData2Text); } else { doc.AddMember("custData2", rapidjson::Value(rapidjson::kNullType), allocator); } } rapidjson::StringBuffer str; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(str); writer.SetIndent(' ', 2); doc.Accept(writer); const char *jsonString = str.GetString(); return strdup(jsonString); } }; class DLLEXPORT sComponentInfo { public: int registerAgain; const char *componentName; const char *description; int abstract; // flag that indicates whether component is 'abstract' only (i.e. without practical functionality) int noDmem; int builtIn; // 1= built in component ; 0= dynamically linked component cSmileComponent * (*create) (const char *_instname); sComponentInfo * next; }; // create for a real class (which implements myFetchConfig() ) #define SMILECOMPONENT_CREATE(TP) cSmileComponent * TP::create(const char*_instname) { \ cSmileComponent *c = new TP(_instname); \ if (c!=NULL) c->setComponentInfo(scname,sdescription); \ return c; \ } // create for an abstract class #define SMILECOMPONENT_CREATE_ABSTRACT(TP) cSmileComponent * TP::create(const char*_instname) { return NULL; } // static declaration in Cpp file of derived class #define SMILECOMPONENT_STATICS(TP) const char *TP::scname; \ const char *TP::sdescription; // static declarations in derived class (public) #define SMILECOMPONENT_STATIC_DECL static sComponentInfo * registerComponent(cConfigManager *_confman, cComponentManager *_compman); \ static cSmileComponent * create(const char *_instname); // static declarations in derived class (protected) #define SMILECOMPONENT_STATIC_DECL_PR static const char *scname; \ static const char *sdescription; #define SMILECOMPONENT_REGCOMP(TP) sComponentInfo * TP::registerComponent(cConfigManager *_confman, cComponentManager *_compman) #define SMILECOMPONENT_REGCOMP_INIT if (_confman == NULL) return NULL; \ int rA = 0; #define SMILECOMPONENT_CREATE_CONFIGTYPE ConfigType *ct = new ConfigType(scname); \ if (ct == NULL) OUT_OF_MEMORY; #define SMILECOMPONENT_INHERIT_CONFIGTYPE(configtype) ConfigType *ct = NULL; \ const ConfigType *r = _confman->getTypeObj(configtype); \ if (r == NULL) { \ SMILE_WRN(4,"%s config Type not found!","configtype"); \ rA=1; \ } else { \ ct = new ConfigType( *(r) , scname ); \ } #define SMILECOMPONENT_REGISTER_CONFIGTYPE if (rA==0) { \ ConfigInstance *Tdflt = new ConfigInstance( scname, ct, 1 ); \ _confman->registerType(Tdflt); \ } #define SMILECOMPONENT_IFNOTREGAGAIN_BEGIN if (rA==0) { #define SMILECOMPONENT_IFNOTREGAGAIN_END SMILECOMPONENT_REGISTER_CONFIGTYPE } #define SMILECOMPONENT_IFNOTREGAGAIN(__code__) SMILECOMPONENT_IFNOTREGAGAIN_BEGIN __code__ ; SMILECOMPONENT_IFNOTREGAGAIN_END #define SMILECOMPONENT_MAKEINFO(TP) if ((rA!=0)&&(ct!=NULL)) delete ct; \ return makeInfo(_confman, scname, sdescription, TP::create, rA) #define SMILECOMPONENT_MAKEINFO_ABSTRACT(TP) if ((rA!=0)&&(ct!=NULL)) delete ct; \ return makeInfo(_confman, scname, sdescription, TP::create, rA, 1, 1) // make info for non-datamemory components (e.g. the cFunctionalXXXX components), e.g. components that are sub-components of other components #define SMILECOMPONENT_MAKEINFO_NODMEM(TP) if ((rA!=0)&&(ct!=NULL)) delete ct; \ return makeInfo(_confman, scname, sdescription, TP::create, rA, 0, 1) // make info for non-datamemory components (e.g. the cFunctionalXXXX components), e.g. components that are sub-components of other components #define SMILECOMPONENT_MAKEINFO_NODMEM_ABSTRACT(TP) if ((rA!=0)&&(ct!=NULL)) delete ct; \ return makeInfo(_confman, scname, sdescription, TP::create, rA, 1, 1) // return code of cSmileComponent::tick method typedef enum { TICK_INACTIVE = 0, // component did not perform any work in its tick method. If all other components also did not perform any work, component manager will exit the current tick loop TICK_SUCCESS = 1, // component did perform work. The tick loop is guaranteed to continue. TICK_SOURCE_NOT_AVAIL = 2, // component could not perform any work because it could not read required data from a source data memory level TICK_EXT_SOURCE_NOT_AVAIL = 3, // component could not perform any work because it could not read required data from an external source (e.g. sound device, network stream, etc.) TICK_DEST_NO_SPACE = 4, // component could not perform any work because there is not enough space in a destination data memory level where it could write its output TICK_EXT_DEST_NO_SPACE = 5 // component could not perform any work because there is not enough space in an external destination where it could write its output } eTickResult; constexpr int NUM_TICK_RESULTS = 6; // returns string representation of an eTickResult value const char *tickResultStr(eTickResult res); #undef class class DLLEXPORT cSmileComponent { private: int id_; // component ID in componentManager int EOI_; // EOI counter, 0 only in first loop, then +1 for every nonEOI/EOI loop pair int EOIcondition_; // flag that indicates end of input // i.e. if EOI is 1, myTick should show a different behaviour // esp. dataReaders should return right padded matrices, in getMatrix , getNextMatrix etc.. int EOIlevel_; // If set to >= 1, the isEOI will report EOI condition true only if EOI_ == EOIlevel_ ; int paused_; // flag that indicates whether processing (the tick loop) has been paused or is active smileMutex messageMtx_; cComponentManager *compman_; // pointer to component manager this component instance belongs to cSmileComponent *parent_; // pointer to parent component (for dataReaders, etc.) char *iname_; // name of component instance char *cfname_; // name of config instance associated with this component instance // variables used for component profiling int doProfile_, printProfile_; double profileCur_, profileSum_; // exec. time of last tick, exec time total std::chrono::time_point<std::chrono::high_resolution_clock> startTime_; std::chrono::time_point<std::chrono::high_resolution_clock> endTime_; eTickResult lastTickResult_; // return value of last call of myTick long lastNrun_; // the number of nRun in the last tick loop iteration protected: SMILECOMPONENT_STATIC_DECL_PR cConfigManager *confman_; // pointer to configManager const char *cname_; // name of the component (type) const char *description_; // component description and usage information // component state variables int isRegistered_, isConfigured_, isFinalised_, isReady_; int runMe_; int manualConfig_; int override_; static sComponentInfo * makeInfo(cConfigManager *_confman, const char *_name, const char *_description, cSmileComponent * (*create) (const char *_instname), int regAgain=0, int _abstract=0, int _nodmem=0); // Gets a pointer to the component instance *name via the component manager. cSmileComponent * getComponentInstance(const char * name) const; // Gets the component instance type of the instance *name as string via the component manager. const char * getComponentInstanceType(const char * name) const; // Create a component instance of given type with instance name "name" in the component manager. cSmileComponent * createComponent(const char *name, const char *component_type); // Gets the number of components ran during the last tick. long getLastNrun() const { return lastNrun_; } // Functions to get config values from the config manager from our config instance. // The _f functions internally free the string *name. Use these in conjunction with myvprint()... // NOTE: Yes, this is ineffective. TODO: smile memory manager, and fixed length text buffer which can be reused (can also grow if needed). void * getExternalPointer(const char *name) const { if (confman_ != NULL) { return confman_->getExternalPointer(name); } else { return NULL; } } void addExternalPointer(const char *name, void * ptr) { if (confman_ != NULL) { confman_->addExternalPointer(name, ptr); } } double getDouble(const char*name) const { return confman_->getDouble_f(myvprint("%s.%s",cfname_,name)); } double getDouble_f(char*name) const { double d = getDouble(name); if (name!=NULL) free(name); return d; } int getInt(const char*name) const { return confman_->getInt_f(myvprint("%s.%s",cfname_,name)); } int getInt_f(char*name) const { int d = getInt(name); if (name!=NULL) free(name); return d; } const char *getStr(const char*name) const { return confman_->getStr_f(myvprint("%s.%s",cfname_,name)); } const char * getStr_f(char*name) const { const char * s = getStr(name); if (name!=NULL) free(name); return s; } char getChar(const char*name) const { return confman_->getChar_f(myvprint("%s.%s",cfname_,name)); } const char getChar_f(char*name) const { const char c = getChar(name); if (name!=NULL) free(name); return c; } const ConfigValue *getValue(const char*name) const { return confman_->getValue_f(myvprint("%s.%s",cfname_,name)); } const ConfigValue * getValue_f(char*name) const { const ConfigValue * v = getValue(name); if (name!=NULL) free(name); return v; } const ConfigValueArr *getArray(const char*name) const { return (ConfigValueArr *)(confman_->getValue_f(myvprint("%s.%s",cfname_,name))); } const ConfigValueArr * getArray_f(char*name) const { const ConfigValueArr * a = getArray(name); if (name!=NULL) free(name); return a; } int getArraySize(const char*name) const { return (confman_->getArraySize_f(myvprint("%s.%s",cfname_,name))); } int getArraySize_f(char*name) const { int s = getArraySize(name); if (name!=NULL) free(name); return s; } char **getArrayKeys(const char*name, int*N = NULL) const { return confman_->getArrayKeys_f(myvprint("%s.%s",cfname_,name), N); } char **getArrayKeys_f(char*name, int*N = NULL) const { char **k = confman_->getArrayKeys(name, N); if (name!=NULL) free(name); return k; } int isSet(const char*name) const { return (confman_->isSet_f(myvprint("%s.%s",cfname_,name))); } int isSet_f(char*name) const { int s = isSet(name); if (name!=NULL) free(name); return s; } // Returns 1 if we are in an abort state (user requested abort). int isAbort() const; // Function that is called during initialisation. It should be used to fetch config variables // from the config manager and store them in local variables. // Each derived class is responsible for fetching configuration from confman or setting it manually BEFORE configureInstance is called! virtual void myFetchConfig() { } // Functions to be implemented by derived classes: // Sets the environment (pointers to parent, component manager, config manager). virtual void mySetEnvironment() { } // Registers the component instance after creation (by the component Manager). virtual int myRegisterInstance(int *runMe=NULL) { return 1; } // Configures the component instance. Data-memory levels and level parameters such as T are created and set here. virtual int myConfigureInstance() { return 1; } // Finalises the component instance. Data-memory level names (fields and elements) are set here. virtual int myFinaliseInstance() { return 1; } // Holds the actual implementation of the tick loop code for the derived component. // This function should return TICK_SUCCESS if the component did process data, // otherwise it should return the appropriate result code (see eTickResult definition). // If all components return non-success codes, the component manager will switch // to the EOI (end-of-input) state (or advance to the next tick loop iteration). virtual eTickResult myTick(long long t) { return TICK_INACTIVE; } // Called by the component manager when the tick loop is to be paused. // If the component needs to reject the pausing of the tick loop, it should return 0, otherwise always 1! virtual int pauseEvent() { return 1; } // Called by the component manager when the tick loop is to be resumed. virtual void resumeEvent() { } // Signals the component manager that this component has more data available to process. // If the tick loop is currently in a waiting state, this will wake it up to continue // processing. void signalDataAvailable(); // Checks if the given component message is of type "msgtype" (string name). int isMessageType(const cComponentMessage *msg, const char * msgtype) const { if (msg != NULL) { return (!strncmp(msg->msgtype, msgtype, CMSG_typenameLen)); } else { return 0; } } // Functions for component message handling. // Note on data synchronisation for messages: The messages can arrive at any time, if // they are sent from another thread. Thus, a mutex is used to prevent collision when // accessing variables from processComponentMessage and the rest of the component code // (especially myTick). The mutex is automatically locked before processComponentMessage // is called, and unlocked afterwards. In the rest of the code, however, lockMessageMemory() // and unlockMessageMemory() must be used. // This function is called by the component manager, if there is a new message for this component. // A derived component must override this to receive and process messages. // Do NOT call lockMessageMemory() in this function! The *msg pointer is always valid. // Return value: 0, message was not processed; != 0, message was processed. // The return value will be passed on to the sender (?). // NOTE: the custData pointer in cComponentMessage (as well as the whole cComponentMessage object) // is valid ONLY until processComponentMessage() returns! // Thus, you are advised to copy data to local memory // NOTE2: This function is called directly from the context of another component/thread. // Do NOT do anything here that is time consuming. It will block the other thread // or the execution of the tick loop. Esp. don't wait here until your own myTick() is called. // In single threaded mode this will never happen! // Always, only accept the message data and put it into a buffer. Process the buffer in myTick() // or in a background thread. virtual int processComponentMessage(cComponentMessage *msg) { return 0; } // this function forwards the message to the componentMananger and sets the *sender pointer correctly // Return value: 0, message was not processed; != 0, message was processed. // TODO: return value passing for multiple recepients? int sendComponentMessage(const char *recepient, cComponentMessage *msg); int sendJsonComponentMessage(const char * recepient, const rapidjson::Document& doc); char * jsonMessageToString(const rapidjson::Document& doc); rapidjson::Document * parseJsonMessage(const char *text, rapidjson::Document::AllocatorType * allocator); // Checks if the incoming message is a container for a JSON object message // and if yes, returns the JSON object message // otherwise, it returns NULL. rapidjson::Document * receiveJsonComponentMessage( cComponentMessage *msg); // Locks the "message memory" (variables that are accessed by processComponentMessage). // You must call this function prior to accessing variables you are accessing in processComponentMessage(). // Do not use this function in processComponentMessage() itself, though! void lockMessageMemory() { smileMutexLock(messageMtx_); } // Unlocks the "message memory" (variables that are accessed by processComponentMessage). void unlockMessageMemory() { smileMutexUnlock(messageMtx_); } // Gets the smile time from the component manager (time since start of the system). double getSmileTime() const; // Returns 1 if we are in an end-of-input condition. int isEOI() const { return EOIcondition_; } // Get the EOI counter, i.e. the number of repeated tick loop sequences. int getEOIcounter() const { return EOI_; } // Request stopping of processing in tickLoop of component manager. // Calling this will make openSMILE stop the processing. virtual void abortProcessing(); public: // Statics: // these two must be overridden in a base class: //static sComponentInfo * registerComponent(cConfigManager *_confman); //static cSmileComponent * create(const char *_instname); SMILECOMPONENT_STATIC_DECL // method for setting config... a base class may implement it with arbirtrary parameters // values set will override those obtained by myFetchConfig if override=1 // if override=0, then only those which are not set are updated // void setConfig(..., int override=1); int isManualConfigSet() const { return manualConfig_; } // Returns whether the tick loop is paused (1) or running (0). int isPaused() const { return paused_; } // Gets pointer to the associated component manager object, // i.e. the object that created this smile component instance. cComponentManager *getCompMan() const { return compman_; } // Gets pointer to the cSmileLogger associated with the component manager. cSmileLogger *getLogger() const; // Constructor that creates an instance of this component with instance name "instname". cSmileComponent(const char *instname); // Sets component name and description after component creation. virtual void setComponentInfo(const char *cname, const char *description) { cname_= cname; description_ = description; } // Sets component manager pointer and the component ID, as used by the component manager. // Called by the creator component (parent) or directly by the component manager. virtual void setComponentEnvironment(cComponentManager *compman, int id, cSmileComponent *parent=NULL); // Sets the name of the associated config instance this component instance is linked to. void setConfigInstanceName(const char *cfname) { if (cfname != NULL) { if ((cfname_ != NULL) && (cfname_ != iname_)) { free(cfname_); cfname_ = NULL; } cfname_ = strdup(cfname); } } // Gets the name of the associated config instance. const char * getConfigInstanceName() const { return cfname_; } void fetchConfig() { myFetchConfig(); } // Performs component specific register operation, e.g. write/read requests with dataMemory.. // *runMe return value for component manager : 0, don't call my tick of this component, 1, call myTick int registerInstance(int *runMe=NULL) { if (runMe != NULL) *runMe = runMe_; if (isRegistered_) return 1; isRegistered_ = myRegisterInstance(runMe); if (runMe != NULL) runMe_ = *runMe; return isRegistered_; } int isRegistered() const { return isRegistered_; } // Performs component configuration (data memory level configuration, creation of readers/writers etc.). int configureInstance() { if (isConfigured_) return 1; isConfigured_ = myConfigureInstance(); return isConfigured_; } int isConfigured() const { return isConfigured_; } // Performs component finalisation (loading of models, opening of files, data memory level names, ...). int finaliseInstance(); int isFinalised() const { return isFinalised_; } // Returns 1, if component has been finalised and is ready for the tick loop. Returns 0 otherwise. int isReady() const { return isReady_; } // This provides the possibility for components to indicate that they // are waiting for data (e.g. in live or streaming modes) and also // execute a sleep() or wait() in this method. // When an empty tick loop is encountered (all components return 0 in // componentManager), then this function is called for all components. // Normally the componentManager tick loop will exit in this case, and // the processing will enter the EOI (end of input) state. // If at least one component returns true, the tick loop will not enter EOI state // but continue as normal. Thus, the default is to return false. virtual bool notifyEmptyTickloop() { return false; } // The tick() function. This is called by the component manager, and internally executes myTick(), eTickResult tick(long long t, int EOIcond=0, long _lastNrun=-1) { lastNrun_ = _lastNrun; if (EOIcond) { if (!isEOI()) { setEOI(); return TICK_SUCCESS; // one "successful" tick to set up all components in EOI state } } else { unsetEOI(); } if (!isReady_) { return TICK_INACTIVE; } if (doProfile_) { startProfile(t, EOIcondition_); } lastTickResult_ = myTick(t); if (doProfile_) { endProfile(t, EOIcondition_); } return lastTickResult_; } eTickResult getLastTickResult() const { return lastTickResult_; } // Configures profiling (measuring of the time spent in each tick). void setProfiling(int enable=1, int print=0) { doProfile_ = enable; printProfile_ = print; } // Starts time measurement (called at the beginning of the tick). void startProfile(long long t, int EOI); // Ends time measurement (called at the end of the tick). void endProfile(long long t, int EOI); // Gets the current profiling statistics. // If sum == 1, it returns the accumulated run-time in seconds // (i.e. the time spent in tick() by this component). // If sum == 0, the duration of the last tick() is returned. // NOTE: For multi-threaded code this method of profiling is not exact. // The tick() function can be interrupted by other threads, but // time measurement is done via the system timer from start to end of tick(). double getProfile(int sum=1) const { if (!sum) return profileCur_; else return profileSum_; } // Gets the component instance name. const char *getInstName() const { return iname_; } // Gets the component type name. const char *getTypeName() const { return cname_; } // Sets the EOI counter. Used by the component manager once a new tick loop with EOIcondition=1 starts. // NOTE: it would be possible for the components to manage their own EOI counters, however, like this we ensure sync and better performance. // If derived components create sub-components internally (without tick function - e.g. dataReaders/Writers), // they must override this, in order to properly set the EOI status in the sub-components. virtual int setEOIcounter(int cnt) { EOI_ = cnt; return cnt; } // Sets and unsets the EOIcondition variable. This is called internally from tick() only. // If derived components create sub-components internally (without tick function - e.g. dataReaders/Writers), // they must override this, in order to properly set the EOI status in the sub-components. virtual void setEOI() { EOIcondition_ = 1; } virtual void unsetEOI() { EOIcondition_ = 0; } virtual void setEOIlevel(int level) { EOIlevel_ = level; } virtual int EOIlevelIsMatch() const { if (EOIlevel_ == EOI_ || EOIlevel_ <= 0) { return 1; } return 0; } virtual int getEOIlevel() const { return EOIlevel_; } // Called by the component manager. Notifies this component about a tick loop pause. virtual int pause() { if (!paused_) { paused_ = 1; return pauseEvent(); } return 1; } // Called by the component manager. Notifies this component about a tick loop resume. virtual void resume() { if (paused_) { paused_ = 0; resumeEvent(); } } // This function is called externally by the component manager, // if another component calls sendComponentMessage. // It receives the message, takes care of memory access synchronisation, and processes the message. int receiveComponentMessage(cComponentMessage *msg) { int ret = 0; if (msg != NULL) { lockMessageMemory(); ret = processComponentMessage(msg); unlockMessageMemory(); } return ret; } virtual ~cSmileComponent(); }; #endif //__SMILE_COMPONENT_HPP
44.122195
196
0.667072
elinjammal
f7ac1e5c5a31bd4a849b3f88bd138a9e3dcc5a8b
2,065
cpp
C++
Camera.cpp
KarmaiSAYIn/recapp
c1a968214b4cf1b4d8befd1c72bedf64e1fc0813
[ "BSD-3-Clause" ]
null
null
null
Camera.cpp
KarmaiSAYIn/recapp
c1a968214b4cf1b4d8befd1c72bedf64e1fc0813
[ "BSD-3-Clause" ]
null
null
null
Camera.cpp
KarmaiSAYIn/recapp
c1a968214b4cf1b4d8befd1c72bedf64e1fc0813
[ "BSD-3-Clause" ]
null
null
null
#include "Camera.h" #include "Graphics.h" #include "Mouse.h" #include "Keyboard.h" #include "Math.h" Camera::Camera(CoordinateTransformer& transformer) : transformer(transformer) { } Camera::Camera(CoordinateTransformer& transformer, float initScale, float fScaleRate) : scale(initScale), fScaleRate(fScaleRate), transformer(transformer) { } Vec2 Camera::GetPos() const { return pos; } float Camera::GetScale() const { return scale; } Rectf Camera::GetRect() const { const float zoom = 1.0f / scale; //This commented area would be the way to get the rect of the camera, but it requires a proper arbitrary rotation Rect implementation which is hard asf; put that shit off until later. //auto rect = Rectf({0.0f, 0.0f}, Graphics::ScreenWidth * zoom, Graphics::ScreenHeight * zoom).Rotate(rotation); //rect.Translate(pos); auto rect = Rectf(pos, Graphics::ScreenWidth * zoom, Graphics::ScreenHeight * zoom); return rect; } void Camera::SetPos(const Vec2& pos) { this->pos = pos; } void Camera::SetScale(float scale) { this->scale = scale; } void Camera::Translate(const Vec2& offset) { pos += offset; } void Camera::Update(const float fElapsedTime, const Mouse& mouse, const Keyboard& keyboard) { if (mouse.LeftDownEvent()) { lastMousePos = mouse.GetPos(); lastMousePos.y = -lastMousePos.y; } if (mouse.LeftIsPressed()) { Vec2 currMousePos = mouse.GetPos(); currMousePos.y = -currMousePos.y; Translate((lastMousePos - currMousePos) / GetScale()); lastMousePos = currMousePos; } if (mouse.WheelUp() || keyboard.KeyIsPressed(Key::UP)) SetScale(GetScale() + fScaleRate * fElapsedTime); if (mouse.WheelDown() || keyboard.KeyIsPressed(Key::DOWN)) SetScale(std::max(0.01f, GetScale() - fScaleRate * fElapsedTime)); } void Camera::Draw(Drawable& draw) const { draw.Transform( Mat3::Scale(scale) * Mat3::Translate((Vec3)-pos) ); transformer.Draw(draw); }
24.011628
187
0.658596
KarmaiSAYIn
f7ae0c8fd7880c2d6ad29f9153352aa439f2413f
5,073
cpp
C++
comms/Cluster.cpp
dehilsterlexis/eclide-1
0c1685cc7165191b5033d450c59aec479f01010a
[ "Apache-2.0" ]
8
2016-08-29T13:34:18.000Z
2020-12-04T15:20:36.000Z
comms/Cluster.cpp
dehilsterlexis/eclide-1
0c1685cc7165191b5033d450c59aec479f01010a
[ "Apache-2.0" ]
221
2016-06-20T19:51:48.000Z
2022-03-29T20:46:46.000Z
comms/Cluster.cpp
dehilsterlexis/eclide-1
0c1685cc7165191b5033d450c59aec479f01010a
[ "Apache-2.0" ]
13
2016-06-24T15:59:31.000Z
2022-01-01T11:48:20.000Z
#include "StdAfx.h" #include "cluster.h" #include "dali.h" #include "SoapUtil.h" #include "clib.h" #include "cache.h" #include "logger.h" #if _COMMS_VER < 68200 using namespace WsTopology; #elif _COMMS_VER < 700000 #else using namespace WsEnvironment; #endif namespace Topology { class CCluster : public ICluster, public CUnknown { protected: std::_tstring m_Name; std::_tstring m_Queue; std::_tstring m_Url; std::_tstring m_TypeStr; CLUSTERTYPE m_Type; std::_tstring m_Directory; std::_tstring m_Desc; std::_tstring m_Prefix; std::_tstring m_Path; std::_tstring m_DataModel; public: IMPLEMENT_CUNKNOWN; CCluster(const std::_tstring & url, const std::_tstring & name, const std::_tstring & queue = _T("")) : m_Url(url), m_Name(name), m_Queue(queue), m_Type(CLUSTERTYPE_UNKNOWN) { } virtual ~CCluster() { } const TCHAR *GetID() const { return m_Name.c_str(); } const TCHAR * GetCacheID() const { return m_Name.c_str(); } const TCHAR *GetName() const { return m_Name.c_str(); } const TCHAR *GetQueue() const { return m_Queue.c_str(); } CLUSTERTYPE GetType() const { return m_Type; } const TCHAR *GetTypeStr() const { return m_TypeStr.c_str(); } const TCHAR *GetDirectory() const { return m_Directory.c_str(); } const TCHAR *GetDesc() const { return m_Desc.c_str(); } const TCHAR *GetPrefix() const { return m_Prefix.c_str(); } const TCHAR *GetPath() const { return m_Path.c_str(); } const TCHAR *GetDataModel() const { return m_DataModel.c_str(); } #if _COMMS_VER < 68200 void Update(const TpLogicalCluster * c) { m_Name = CW2T(c->Name, CP_UTF8); #if _COMMS_VER < 55100 #else if(c->Queue) { m_Queue = CW2T(c->Queue, CP_UTF8); } #endif Refresh(); } void Update(const TpCluster * c) { m_Name = CW2T(c->Name, CP_UTF8); m_Type = CW2T(c->Type, CP_UTF8); m_Directory = CW2T(c->Directory, CP_UTF8); m_Desc = CW2T(c->Desc, CP_UTF8); m_Prefix = CW2T(c->Prefix, CP_UTF8); m_Path = CW2T(c->Path, CP_UTF8); m_DataModel = CW2T(c->DataModel, CP_UTF8); Refresh(); } #elif _COMMS_VER < 604000 void Update(const ns5__TpLogicalCluster * c) { SAFE_ASSIGN(m_Name, c->Name); SAFE_ASSIGN(m_Queue, c->Queue); Refresh(); } #elif _COMMS_VER < 700000 void Update(const ns5__TpLogicalCluster * c) { SAFE_ASSIGN(m_Name, c->Name); SAFE_ASSIGN(m_Queue, c->Queue); SAFE_ASSIGN(m_TypeStr, c->Type); if (boost::algorithm::iequals(m_TypeStr, _T("hthor"))) { m_Type = CLUSTERTYPE_HTHOR; } else if (boost::algorithm::iequals(m_TypeStr, _T("thor"))) { m_Type = CLUSTERTYPE_THOR; } else if (boost::algorithm::iequals(m_TypeStr, _T("roxie"))) { m_Type = CLUSTERTYPE_ROXIE; } else { m_Type = CLUSTERTYPE_UNKNOWN; } Refresh(); } #else void Update(const LogicalCluster * c) { m_Name = CW2T(c->Name, CP_UTF8); if(c->Queue) { m_Queue = CW2T(c->Queue, CP_UTF8); } Refresh(); } #endif void Refresh() { } }; CacheT<std::_tstring, CCluster> ClusterCache; void ClearClusterCache() { ClusterCache.Clear(); } CCluster * CreateClusterRaw(const CString & url, const CString & name, const std::_tstring & queue = _T("")) { return ClusterCache.Get(new CCluster(static_cast<const TCHAR *>(url), static_cast<const TCHAR *>(name), queue)); } #if _COMMS_VER < 68200 ICluster * CreateCluster(const CString & url, const TpLogicalCluster * data) { CCluster * attr = CreateClusterRaw(url, data->Name); ATLASSERT(attr); attr->Update(data); return attr; } ICluster * CreateCluster(const CString & url, const TpCluster * data) { ATLASSERT(!"This is not used any more - please tell Gordon"); //CCluster * attr = CreateClusterRaw(url, data->Name); //ATLASSERT(attr); //attr->Update(data); return NULL;//attr; } #elif _COMMS_VER < 700000 ICluster * CreateCluster(const CString & url, const ns5__TpLogicalCluster * data) { CCluster * attr = CreateClusterRaw(url, data->Name->c_str()); ATLASSERT(attr); attr->Update(data); return attr; } #else ICluster * CreateCluster(const CString & url, const LogicalCluster * data) { CCluster * attr = CreateClusterRaw(url, data->Name); ATLASSERT(attr); attr->Update(data); return attr; } ICluster * CreateCluster(const CString & url, const Cluster * data) { ATLASSERT(!"This is not used any more - please tell Gordon"); //CCluster * attr = CreateClusterRaw(url, data->Name); //ATLASSERT(attr); //attr->Update(data); return NULL;//attr; } #endif void ClearClusterSingletons() { ClusterCache.clear(); } }
23.705607
177
0.609698
dehilsterlexis
f7aff1b047ae5b6528120ba97234e36b3b80cd50
1,073
cpp
C++
leetcode/25-reverse-nodes-in-k-group.cpp
01nomagic/Algorithms
b184aa12141f5127baa55502d3ea47ccd1f97ba8
[ "MIT" ]
2
2021-03-27T03:23:20.000Z
2021-08-11T12:54:17.000Z
leetcode/25-reverse-nodes-in-k-group.cpp
01nomagic/Algorithms
b184aa12141f5127baa55502d3ea47ccd1f97ba8
[ "MIT" ]
null
null
null
leetcode/25-reverse-nodes-in-k-group.cpp
01nomagic/Algorithms
b184aa12141f5127baa55502d3ea47ccd1f97ba8
[ "MIT" ]
null
null
null
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {} }; class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { if (k <= 1) { return head; } int count = 0; ListNode* prev = nullptr; ListNode* curr = head; ListNode* start = nullptr; ListNode* end = nullptr; while (curr != nullptr) { count += 1; if (count == 1) { start = curr; } if (count == k) { end = curr; curr = curr->next; ListNode* next = end->next; ListNode* curr1 = start; // 反转 while (true) { ListNode* temp = curr1->next; curr1->next = next; if (curr1 == end) { break; } next = curr1; curr1 = temp; } if (prev == nullptr) { head = end; prev = start; } else { prev->next = end; prev = start; } count = 0; } else { curr = curr->next; } } return head; } };
20.634615
50
0.444548
01nomagic
fc92921f2bf8f6aa4b09393a636bf28f83f695f5
3,415
cpp
C++
Sources/Commands/command_gpt.cpp
c3358/ntfstool
08d6efc1298cb223fe9f24c3849e1aad08c5a45f
[ "MIT" ]
1
2021-07-28T12:54:08.000Z
2021-07-28T12:54:08.000Z
Sources/Commands/command_gpt.cpp
c3358/ntfstool
08d6efc1298cb223fe9f24c3849e1aad08c5a45f
[ "MIT" ]
null
null
null
Sources/Commands/command_gpt.cpp
c3358/ntfstool
08d6efc1298cb223fe9f24c3849e1aad08c5a45f
[ "MIT" ]
null
null
null
#include "Utils/buffer.h" #include "Drive/disk.h" #include "Utils/utils.h" #include "Utils/table.h" #include "options.h" #include "Utils/constant_names.h" #include <intrin.h> #include <distorm.h> #include <algorithm> #include <cstdint> #include <string> #include <iostream> #include <iomanip> #include <memory> #include <stdexcept> namespace commands { namespace gpt { int print_gpt(std::shared_ptr<Options> opts) { std::ios_base::fmtflags flag_backup(std::cout.flags()); std::shared_ptr<Disk> disk = get_disk(opts); if (disk != nullptr) { PGPT_HEADER pgpt = disk->gpt(); if (disk->has_protective_mbr()) { utils::ui::title("GPT from " + disk->name()); std::vector<GPT_PARTITION_ENTRY> gpt_entries = disk->gpt_entries(); std::cout << "Signature : " << pgpt->magic << std::endl; std::cout << "Revision : " << pgpt->revision_high << "." << pgpt->revision_low << std::endl; std::cout << "Header Size : " << pgpt->header_size << std::endl; std::cout << "Header CRC32 : " << std::setfill('0') << std::setw(8) << std::hex << _byteswap_ulong(pgpt->header_crc32) << std::endl; std::cout << "Reserved : " << std::setfill('0') << std::setw(8) << std::hex << pgpt->reserved1 << std::endl; std::cout << std::dec << std::setw(0); std::cout << "Current LBA : " << pgpt->current_lba << std::endl; std::cout << "Backup LBA : " << pgpt->backup_lba << std::endl; std::cout << "First Usable LBA : " << pgpt->first_usable_lba << std::endl; std::cout << "Last Usable LBA : " << pgpt->last_usable_lba << std::endl; std::cout << "GUID : " << utils::id::guid_to_string(pgpt->disk_guid) << std::endl; std::cout << "Entry LBA : " << pgpt->partition_entry_lba << std::endl; std::cout << "Entries Num : " << pgpt->num_partition_entries << std::endl; std::cout << "Entries Size : " << pgpt->sizeof_partition_entry << std::endl; std::cout << "Partitions CRC32 : " << std::setfill('0') << std::setw(8) << std::hex << _byteswap_ulong(pgpt->partition_entry_array_crc32) << std::endl; std::shared_ptr<utils::ui::Table> partitions = std::make_shared<utils::ui::Table>(); partitions->add_header_line("Id"); partitions->add_header_line("Name"); partitions->add_header_line("GUID"); partitions->add_header_line("First sector"); partitions->add_header_line("Last sector"); partitions->add_header_line("Flags"); unsigned int n_partitions = 0; for (GPT_PARTITION_ENTRY& entry : gpt_entries) { n_partitions++; partitions->add_item_line(std::to_string(n_partitions)); partitions->add_item_line(utils::strings::to_utf8(entry.PartitionName)); partitions->add_item_line(utils::id::guid_to_string(entry.UniquePartitionGUID)); partitions->add_item_line(std::to_string(entry.StartingLBA)); partitions->add_item_line(std::to_string(entry.EndingLBA)); partitions->add_item_line(utils::format::hex(entry.Attributes)); partitions->new_line(); } std::cout << std::endl << "Partition table : " << gpt_entries.size() << " entries" << std::endl; partitions->render(std::cout); std::cout << std::endl; } else { std::cerr << "[!] Invalid or non-GPT partition table"; return 1; } } std::cout.flags(flag_backup); return 0; } } }
39.252874
156
0.619619
c3358
fca2d673f1bd6033962931ca4fb614844d32c1cb
1,203
cpp
C++
Advanced/AA1112/AA1112/main.cpp
Eric-Ma-C/PAT-Advanced
ea8b46a780a04b46ab35ebd06c4bf19c3a664380
[ "MIT" ]
null
null
null
Advanced/AA1112/AA1112/main.cpp
Eric-Ma-C/PAT-Advanced
ea8b46a780a04b46ab35ebd06c4bf19c3a664380
[ "MIT" ]
null
null
null
Advanced/AA1112/AA1112/main.cpp
Eric-Ma-C/PAT-Advanced
ea8b46a780a04b46ab35ebd06c4bf19c3a664380
[ "MIT" ]
null
null
null
#include<stdio.h> #include<string.h> #include<vector> #include<map> #include<algorithm> using namespace std; //33min typedef struct item{ int id; char c; }item; map<char,item> m; bool cmp(item i1,item i2){ return i1.id<i2.id; } int main(){ int k; scanf("%d",&k); char c[1100]; scanf("%s",c); int len=strlen(c); int index=0; for(int i=0;i<len;){ int count=0; for(int j=i;j<len&&c[j]==c[i];j++) count++; bool broken=false; if(count%k==0)broken=true; if(m.find(c[i])==m.end()){ item it; it.c=c[i]; if(broken) it.id=index++; else it.id=-1; m[c[i]]=it; }else{ if(m[c[i]].id>0&&!broken){ m[c[i]].id=-1; } } i+=count; } char ac[1100]={0}; int tmp=0; for(int i=0;i<len;){ int count=0; for(int j=i;j<len&&c[j]==c[i];j++) count++; if(m[c[i]].id<0){ for(int j=0;j<count;j++) ac[tmp++]=c[i]; }else{ for(int j=0;j<count/k;j++) ac[tmp++]=c[i]; } i+=count; } vector<item> ans; for(auto it=m.begin();it!=m.end();it++){ if(it->second.id>=0) ans.push_back(it->second); } sort(ans.begin(),ans.end(),cmp); for(int i=0;i<ans.size();i++){ printf("%c",ans[i].c); } printf("\n%s",ac); getchar(); getchar(); return 0; }
16.256757
41
0.545303
Eric-Ma-C
fca5f7db5e1d0888f1f6cb018a432e69d0cbae84
4,161
cpp
C++
pwiz/analysis/peakdetect/FeatureDetectorPeakel.cpp
edyp-lab/pwiz-mzdb
d13ce17f4061596c7e3daf9cf5671167b5996831
[ "Apache-2.0" ]
11
2015-01-08T08:33:44.000Z
2019-07-12T06:14:54.000Z
pwiz/analysis/peakdetect/FeatureDetectorPeakel.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
61
2015-05-27T11:20:11.000Z
2019-12-20T15:06:21.000Z
pwiz/analysis/peakdetect/FeatureDetectorPeakel.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
4
2016-02-03T09:41:16.000Z
2021-08-01T18:42:36.000Z
// // $Id: FeatureDetectorPeakel.cpp 2051 2010-06-15 18:39:13Z chambm $ // // // Original author: Darren Kessner <[email protected]> // // Copyright 2009 Center for Applied Molecular Medicine // University of Southern California, Los Angeles, CA // // 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. // #define PWIZ_SOURCE #include "FeatureDetectorPeakel.hpp" #include "pwiz/analysis/passive/MSDataCache.hpp" #include "pwiz/utility/misc/Std.hpp" namespace pwiz { namespace analysis { using namespace pwiz::msdata; shared_ptr<FeatureDetectorPeakel> FeatureDetectorPeakel::create(FeatureDetectorPeakel::Config config) { // note: config passed by value, allowing us to propagate the log pointers if (config.log) { config.peakFinder_SNR.log = config.log; config.peakelGrower_Proximity.log = config.log; config.peakelPicker_Basic.log = config.log; } shared_ptr<NoiseCalculator> noiseCalculator( new NoiseCalculator_2Pass(config.noiseCalculator_2Pass)); shared_ptr<PeakFinder> peakFinder(new PeakFinder_SNR(noiseCalculator, config.peakFinder_SNR)); shared_ptr<PeakFitter> peakFitter(new PeakFitter_Parabola(config.peakFitter_Parabola)); shared_ptr<PeakExtractor> peakExtractor(new PeakExtractor(peakFinder, peakFitter)); shared_ptr<PeakelGrower> peakelGrower(new PeakelGrower_Proximity(config.peakelGrower_Proximity)); shared_ptr<PeakelPicker> peakelPicker(new PeakelPicker_Basic(config.peakelPicker_Basic)); return shared_ptr<FeatureDetectorPeakel>( new FeatureDetectorPeakel(peakExtractor, peakelGrower, peakelPicker)); } FeatureDetectorPeakel::FeatureDetectorPeakel(shared_ptr<PeakExtractor> peakExtractor, shared_ptr<PeakelGrower> peakelGrower, shared_ptr<PeakelPicker> peakelPicker) : peakExtractor_(peakExtractor), peakelGrower_(peakelGrower), peakelPicker_(peakelPicker) { if (!peakExtractor.get() || !peakelGrower.get() || !peakelPicker.get()) throw runtime_error("[FeatureDetectorPeakel] Null pointer"); } namespace { struct SetPeakMetadata { const SpectrumInfo& spectrumInfo; SetPeakMetadata(const SpectrumInfo& _spectrumInfo) : spectrumInfo(_spectrumInfo) {} void operator()(Peak& peak) { peak.id = spectrumInfo.scanNumber; peak.retentionTime = spectrumInfo.retentionTime; } }; vector< vector<Peak> > extractPeaks(const MSData& msd, const PeakExtractor& peakExtractor) { MSDataCache msdCache; msdCache.open(msd); const size_t spectrumCount = msdCache.size(); vector< vector<Peak> > result(spectrumCount); for (size_t index=0; index<spectrumCount; index++) { const SpectrumInfo& spectrumInfo = msdCache.spectrumInfo(index, true); vector<Peak>& peaks = result[index]; peakExtractor.extractPeaks(spectrumInfo.data, peaks); for_each(peaks.begin(), peaks.end(), SetPeakMetadata(spectrumInfo)); /* TODO: logging if (os_) { *os_ << "index: " << index << endl; *os_ << "peaks: " << peaks.size() << endl; copy(peaks.begin(), peaks.end(), ostream_iterator<Peak>(*os_, "\n")); } */ } return result; } } // namespace void FeatureDetectorPeakel::detect(const MSData& msd, FeatureField& result) const { vector< vector<Peak> > peaks = extractPeaks(msd, *peakExtractor_); PeakelField peakelField; peakelGrower_->sowPeaks(peakelField, peaks); peakelPicker_->pick(peakelField, result); } } // namespace analysis } // namespace pwiz
30.372263
101
0.703677
edyp-lab
fcaa3a2c93594ac917a81701873ba6034802252b
605
cpp
C++
HurdleRace.cpp
d3cod3monk78/hackerrank
8f3174306754d04d07b42d5c7a95ab32abf17fa1
[ "MIT" ]
null
null
null
HurdleRace.cpp
d3cod3monk78/hackerrank
8f3174306754d04d07b42d5c7a95ab32abf17fa1
[ "MIT" ]
null
null
null
HurdleRace.cpp
d3cod3monk78/hackerrank
8f3174306754d04d07b42d5c7a95ab32abf17fa1
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <vector> #include <cstdlib> #include <string> #include <string.h> using namespace std; int getDose(vector<int> arr , int k) { int n = (int)arr.size(); sort(arr.begin() , arr.end()); int dose = 0; if(arr[n-1] < k) { return 0; } for(int i = 0; i < n; i++) { if(arr[i] > k && dose < arr[i] - k) { dose = arr[i] - k; } } return dose; } int main(int argc, char const *argv[]) { int n; int k; cin >> n >> k; vector<int> arr(n); int temp; for(int i = 0; i < n; i++) { cin >> temp; arr[i] = temp; } cout << getDose(arr , k) << endl; return 0; }
15.921053
40
0.538843
d3cod3monk78
fcab4e92faabc89cc4c415859b2405ba992271b6
475
cpp
C++
src/customlabel.cpp
cvlabbonn/hand_2d_gt_viewer
457e0929fdeee740b8940a791299ed8541124a83
[ "MIT" ]
1
2018-03-16T22:40:16.000Z
2018-03-16T22:40:16.000Z
src/customlabel.cpp
cvlabbonn/hand_2d_gt_viewer
457e0929fdeee740b8940a791299ed8541124a83
[ "MIT" ]
null
null
null
src/customlabel.cpp
cvlabbonn/hand_2d_gt_viewer
457e0929fdeee740b8940a791299ed8541124a83
[ "MIT" ]
3
2015-10-05T22:48:40.000Z
2018-06-28T11:51:09.000Z
#include "customlabel.h" CustomLabel::CustomLabel( QWidget *parent ) : QLabel( parent ){ } void CustomLabel::mouseMoveEvent( QMouseEvent *ev ){ this->mouse_X = ev->x(); this->mouse_Y = ev->y(); emit mouse_position(); } void CustomLabel::mousePressEvent( QMouseEvent *ev ){ emit mouse_pressed(); } void CustomLabel::leaveEvent( QEvent * ){ emit mouse_left(); } void CustomLabel::mouseReleaseEvent( QMouseEvent * ){ emit mouse_release(); }
16.964286
53
0.671579
cvlabbonn
fcabd41951052a1b7b4bbac628f49aa173b2857c
2,901
cpp
C++
src/tests/merger_tests/handleInputs.cpp
danguenther/spfe-framework
f1f91330e136727edc12b8b0a07723a4059fa039
[ "MIT" ]
null
null
null
src/tests/merger_tests/handleInputs.cpp
danguenther/spfe-framework
f1f91330e136727edc12b8b0a07723a4059fa039
[ "MIT" ]
null
null
null
src/tests/merger_tests/handleInputs.cpp
danguenther/spfe-framework
f1f91330e136727edc12b8b0a07723a4059fa039
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <merger.h> #include <fstream> #define OUTPUT_FILE_HANDLE_INPUTS "src/tests/merger_tests/test_files/output.txt" using namespace std; /** * tests if the testInputs function writes the correct line in the file on the given parameters * @param current S if it is Server input, C if it is Client input * @param iss stream of the range of the input numbers * @param minValue smalles wire id of the input * @param maxValue highest wire id of the input * @param filename name of the file * @param counter current number of wires * @param wires mapping from the wires in the mering file to the wires in the ABY format file (updated in this function) */ void testInputs(string current, istringstream &iss, int minValue, int maxValue, string filename, uint32_t counter, map<uint32_t, uint32_t> &wires) { fstream file(filename, ios::out); handleInputs(current, iss, file, wires, counter); file.close(); fstream file2(filename, ios::in); string line; getNextLine(file2, line); istringstream is(line); string cur; is >> cur; EXPECT_EQ(cur, current); for (int i = minValue; i <= maxValue; i++) { EXPECT_EQ(wires[i], i); is >> cur; EXPECT_TRUE(isNumber(cur)); long lvalue = stoul(cur, nullptr, 10); auto value = static_cast<uint32_t>(lvalue); EXPECT_EQ(value, i); } file2.close(); } /* * Tests for handleInputs() function */ /* * test for only client inputs */ TEST (handleInputs, clientInput) { string current = "C"; istringstream iss("[ 0 4 ]"); map<uint32_t, uint32_t> wires; testInputs(current, iss, 0, 4, OUTPUT_FILE_HANDLE_INPUTS, 0, wires); } /* * test for only server inputs */ TEST (handleInputs, serverInput) { string current = "S"; istringstream iss("[ 0 12 ]"); map<uint32_t, uint32_t> wires; testInputs(current, iss, 0, 12, OUTPUT_FILE_HANDLE_INPUTS, 0, wires); } /* * tests for client and server inputs. Client's inputs are specified first */ TEST (handleInputs, clientAndServerInput) { string current = "C"; istringstream iss("[ 0 5 ]"); map<uint32_t, uint32_t> wires; testInputs(current, iss, 0, 5, OUTPUT_FILE_HANDLE_INPUTS, 0, wires); current = "S"; istringstream iss2("[ 6 18 ]"); testInputs(current, iss2, 6, 18, OUTPUT_FILE_HANDLE_INPUTS, 6, wires); } /* * tests for server and client inputs. Server's inputs are specified first */ TEST (handleInputs, serverAndClientInput) { string current = "S"; istringstream iss("[ 0 5 ]"); map<uint32_t, uint32_t> wires; testInputs(current, iss, 0, 5, OUTPUT_FILE_HANDLE_INPUTS, 0, wires); current = "C"; istringstream iss2("[ 6 18 ]"); testInputs(current, iss2, 6, 18, OUTPUT_FILE_HANDLE_INPUTS, 6, wires); }
29.30303
120
0.653223
danguenther
fcad23e944161f11f6431ff1e042c7a230780bf4
1,576
cc
C++
Boss2D/addon/webrtc-jumpingyang001_for_boss/audio/time_interval_unittest.cc
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
Boss2D/addon/webrtc-jumpingyang001_for_boss/audio/time_interval_unittest.cc
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
Boss2D/addon/webrtc-jumpingyang001_for_boss/audio/time_interval_unittest.cc
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
/* * Copyright 2017 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include BOSS_WEBRTC_U_audio__time_interval_h //original-code:"audio/time_interval.h" #include BOSS_WEBRTC_U_api__units__time_delta_h //original-code:"api/units/time_delta.h" #include BOSS_WEBRTC_U_rtc_base__fakeclock_h //original-code:"rtc_base/fakeclock.h" #include "test/gtest.h" namespace webrtc { TEST(TimeIntervalTest, TimeInMs) { rtc::ScopedFakeClock fake_clock; TimeInterval interval; interval.Extend(); fake_clock.AdvanceTime(TimeDelta::ms(100)); interval.Extend(); EXPECT_EQ(interval.Length(), 100); } TEST(TimeIntervalTest, Empty) { TimeInterval interval; EXPECT_TRUE(interval.Empty()); interval.Extend(); EXPECT_FALSE(interval.Empty()); interval.Extend(200); EXPECT_FALSE(interval.Empty()); } TEST(TimeIntervalTest, MonotoneIncreasing) { const size_t point_count = 7; const int64_t interval_points[] = {3, 2, 5, 0, 4, 1, 6}; const int64_t interval_differences[] = {0, 1, 3, 5, 5, 5, 6}; TimeInterval interval; EXPECT_TRUE(interval.Empty()); for (size_t i = 0; i < point_count; ++i) { interval.Extend(interval_points[i]); EXPECT_EQ(interval_differences[i], interval.Length()); } } } // namespace webrtc
32.163265
88
0.73731
Yash-Wasalwar-07
fcafece3bb6298fe79c3e6612780ec3dd6896c44
6,687
cpp
C++
src/shell/main.cpp
georgebrock/task
00204e01912aeb9e39b94ac7ba16562fdd5b5f2c
[ "MIT" ]
1
2017-10-13T06:00:59.000Z
2017-10-13T06:00:59.000Z
src/shell/main.cpp
georgebrock/task
00204e01912aeb9e39b94ac7ba16562fdd5b5f2c
[ "MIT" ]
null
null
null
src/shell/main.cpp
georgebrock/task
00204e01912aeb9e39b94ac7ba16562fdd5b5f2c
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006-2014, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <algorithm> #include <fstream> #include <iostream> #include <cstring> #include <string.h> #include <text.h> #include <i18n.h> #include <Color.h> #include <Context.h> #include <Readline.h> Context context; #define MAX_ARGUMENTS 256 //////////////////////////////////////////////////////////////////////////////// int main (int argc, const char** argv) { bool read_from_file = false; if (argc > 2) { std::cout << STRING_SHELL_USAGE << "\n"; return -1; } else if (argc == 2) { if (!strcmp (argv[1], "--version")) { std::cout << VERSION << "\n"; return 0; } else if (!strcmp (argv[1], "--help")) { std::cout << STRING_SHELL_USAGE << "\n"; return 0; } else { // The user has given tasksh a task commands file to execute File input_file = File (argv[1]); if (!input_file.exists ()) { std::cout << STRING_SHELL_NO_FILE; std::cout << STRING_SHELL_USAGE << "\n"; return -1; } read_from_file = true; } } // If a file is given, read from it std::ifstream fin; if (read_from_file) { fin.open (argv[1]); } // Commands may be redirected too std::istream &in = read_from_file ? fin : std::cin; if (Readline::interactiveMode (in)) { // Begining initilaization if (context.initialize (0, NULL)) { return -1; } // Display some kind of welcome message. Color bold (Color::nocolor, Color::nocolor, false, true, false); std::cout << (context.color () ? bold.colorize (PACKAGE_STRING) : PACKAGE_STRING) << " shell\n\n" << STRING_CMD_SHELL_HELP1 << '\n' << STRING_CMD_SHELL_HELP2 << '\n' << STRING_CMD_SHELL_HELP3 << "\n\n"; } // Make a copy because context.clear will delete them. std::string permanent_overrides; std::vector <Arg>::iterator i; for (i = context.a3.begin (); i != context.a3.end (); ++i) { if (i->_category == Arg::cat_rc || i->_category == Arg::cat_override) { if (i != context.a3.begin ()) permanent_overrides += " "; permanent_overrides += i->_raw; } } std::string input; std::vector <std::string> quit_commands; quit_commands.push_back ("quit"); quit_commands.push_back ("exit"); quit_commands.push_back ("bye"); // The event loop. while (in) { std::string prompt (context.config.get ("shell.prompt") + " "); context.clear (); if (Readline::interactiveMode (in)) { input = Readline::gets (prompt); // if a string has nothing but whitespaces, ignore it if (input.find_first_not_of (" \t") == std::string::npos) continue; } else { std::getline (in, input); // if a string has nothing but whitespaces, ignore it if (input.find_first_not_of (" \t") == std::string::npos) continue; std::cout << prompt << input << '\n'; } try { #ifdef HAVE_WORDEXP std::string command = "task " + trim (input + permanent_overrides); // Escape special chars. size_t i = 0; while ((i = command.find_first_of ("$*?!|&;<>(){}~#@", i)) != std::string::npos) { command.insert(i, 1, '\\'); i += 2; } // Perform expansion. wordexp_t p; wordexp (command.c_str (), &p, 0); char** w = p.we_wordv; for (int i = 0; i < p.we_wordc; ++i) { if (std::find (quit_commands.begin (), quit_commands.end (), lowerCase (w[i])) != quit_commands.end ()) { context.clearMessages (); return 0; } } // External calls. if (strcmp (w[1], "xc") == 0 && p.we_wordc > 2) { std::string combined = ""; for (int i = 2; i < p.we_wordc - 1 ; ++i) { combined += std::string (w[i]) + " "; } combined += w[p.we_wordc - 1]; // last goes without a blank system (combined.c_str ()); // not checked continue; } int status = context.initialize (p.we_wordc, (const char**)p.we_wordv); wordfree(&p); #else std::string command = "task " + trim (input + permanent_overrides); int arg_count = 0; char* arg_vector[MAX_ARGUMENTS]; char* arg = strtok ((char*)command.c_str (), " "); while (arg && arg_count < MAX_ARGUMENTS) { arg_vector[arg_count++] = arg; arg = strtok (0, " "); } for (int i = 1; i < arg_count; ++i) { if (std::find (quit_commands.begin (), quit_commands.end (), lowerCase (arg_vector[i])) != quit_commands.end ()) { context.clearMessages (); return 0; } } int status = context.initialize (arg_count, (const char**) arg_vector); #endif if (status == 0) context.run (); } catch (const std::string& error) { std::cerr << error << '\n'; return -1; } catch (...) { std::cerr << STRING_UNKNOWN_ERROR << '\n'; return -2; } } return 0; } ////////////////////////////////////////////////////////////////////////////////
27.072874
86
0.546583
georgebrock
fcb2af36e9fbc3010949d35ecbaf2a91c66f9b99
6,668
hpp
C++
Yannq/GroundState/SRMat.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
Yannq/GroundState/SRMat.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
Yannq/GroundState/SRMat.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <Eigen/Core> #include <Eigen/Dense> #include <Eigen/IterativeLinearSolvers> #include <tbb/tbb.h> #include "Utilities/Utility.hpp" #include "Observables/Energy.hpp" #include "./utils.hpp" namespace yannq { template<typename Machine, typename Hamiltonian> class SRMat; } //namespace yannq namespace Eigen { //namespace Eigen namespace internal { template<typename Machine, typename Hamiltonian> struct traits<yannq::SRMat<Machine, Hamiltonian> > : public Eigen::internal::traits<Eigen::SparseMatrix<typename Machine::Scalar> > {}; } }// namespace Eigen; namespace yannq { //! \addtogroup GroundState //! \ingroup GroundState //! This class that generates the quantum Fisher matrix for the stochastic reconfiguration (SR) method. template<typename Machine, typename Hamiltonian> class SRMat : public Eigen::EigenBase<SRMat<Machine, Hamiltonian> > { public: using Scalar = typename Machine::Scalar; using RealScalar = typename remove_complex<Scalar>::type; using Matrix = typename Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>; using Vector = typename Eigen::Matrix<Scalar, Eigen::Dynamic, 1>; using VectorConstRef = typename Eigen::Ref<const Vector>; using RealMatrix = typename Eigen::Matrix<RealScalar, Eigen::Dynamic, Eigen::Dynamic>; using RealVector = typename Eigen::Matrix<RealScalar, Eigen::Dynamic, 1>; using StorageIndex = uint32_t; enum { ColsAtCompileTime = Eigen::Dynamic, MaxColsAtCompileTime = Eigen::Dynamic, IsRowMajor = false }; private: uint32_t n_; const Machine& qs_; const Hamiltonian& ham_; Energy<Scalar, Hamiltonian> energy_; RealScalar shift_; Matrix deltas_; Vector deltaMean_; Vector energyGrad_; Vector weights_; public: //! \param qs Machine that describes quantum states //! \param ham Hamiltonian for SR SRMat(const Machine& qs, const Hamiltonian& ham) : n_{qs.getN()}, qs_(qs), ham_(ham), energy_(ham) { } Eigen::Index rows() const { return qs_.getDim(); } Eigen::Index cols() const { return qs_.getDim(); } template<typename Rhs> Eigen::Product<SRMat<Machine, Hamiltonian>, Rhs, Eigen::AliasFreeProduct> operator*(const Eigen::MatrixBase<Rhs>& x) const { return Eigen::Product<SRMat<Machine, Hamiltonian>, Rhs, Eigen::AliasFreeProduct>(*this, x.derived()); } //! \param rs Sampling results obtained from samplers. template<class SamplingResult> void constructFromSamples(SamplingResult&& sr) { weights_.resize(0); int nsmp = sr.size(); constructDelta(qs_, sr, deltas_); constructObs(qs_, sr, energy_); deltaMean_ = deltas_.colwise().mean(); deltas_ = deltas_.rowwise() - deltaMean_.transpose(); energyGrad_ = deltas_.adjoint() * energy_.elocs(); energyGrad_ /= nsmp; } template<class SamplingResult> void constructFromWeightSamples(const Eigen::Ref<const RealVector>& weights, SamplingResult&& sr) { weights_ = weights; constructDelta(qs_, sr, deltas_); constructObsWeights(qs_, std::forward<SamplingResult>(sr), weights, energy_); deltaMean_ = weights.transpose()*deltas_; deltas_ = deltas_.rowwise() - deltaMean_.transpose(); energyGrad_ = deltas_.adjoint() * weights.asDiagonal() * energy_.elocs(); } void setShift(RealScalar shift) { shift_ = shift; } RealScalar getShift() const { return shift_; } //! return \f$\langle \nabla_{\theta} \psi_\theta(\sigma) \rangle\f$ const Vector& oloc() const& { return deltaMean_; } Vector oloc() && { return deltaMean_; } Matrix corrMat() { int nsmp = deltas_.rows(); if(weights_.size() == 0) return (deltas_.adjoint() * deltas_)/nsmp; else return (deltas_.adjoint() * weights_.asDiagonal() * deltas_); } RealScalar eloc() const { return std::real(energy_.eloc()); } Scalar elocVar() const { return std::real(energy_.elocVar()); } const Vector& energyGrad() const& { return energyGrad_; } Vector energyGrad() && { return energyGrad_; } Vector apply(const Vector& rhs) const { assert(rhs.size() == qs_.getDim()); Vector r = deltas_*rhs; Vector res; if(weights_.size() == 0) { r /= r.rows(); res = deltas_.adjoint()*r; } else { r.array() *= weights_.array(); res = deltas_.adjoint() * r; } return res + Scalar(shift_)*rhs; } /*! \brief Use conjugate gradient solover to solve the optimizing vector. * * We solve \f$ (S + \epsilon \mathbb{1})v = f \f$ where \f$ f \f$ is the gradient of the energy expectation values. * \param shift \f$ \epsilon \f$ that controls regularization * \param tol tolerance for CG solver */ Vector solveCG(RealScalar shift, RealScalar tol = 1e-4) { setShift(shift); Eigen::ConjugateGradient< SRMat<Machine, Hamiltonian>, Eigen::Lower|Eigen::Upper, Eigen::IdentityPreconditioner> cg; cg.compute(*this); cg.setTolerance(tol); return cg.solve(energyGrad_); } /** * Solve S^{-1}vec using conjugate gradient method */ Vector solveCG(const VectorConstRef& vec, double shift, double tol = 1e-4) { setShift(shift); Eigen::ConjugateGradient< SRMat<Machine, Hamiltonian>, Eigen::Lower|Eigen::Upper, Eigen::IdentityPreconditioner> cg; cg.compute(*this); cg.setTolerance(tol); return cg.solve(vec); } /*! \brief Solve the optimizing vector by solving the linear equation exactly.. * * We solve \f$ (S + \epsilon \mathbb{1})v = f \f$ where \f$ f \f$ is the gradient of the energy expectation values. * \param shift \f$ \epsilon \f$ that controls regularization */ Vector solveExact(RealScalar shift) { Matrix mat = corrMat(); mat += shift*Matrix::Identity(mat.rows(),mat.cols()); Eigen::LLT<Matrix> llt{mat}; return llt.solve(energyGrad_); } }; } //namespace yannq namespace Eigen { namespace internal { template<typename Rhs, typename Machine, typename Hamiltonian> struct generic_product_impl<yannq::SRMat<Machine, Hamiltonian>, Rhs, SparseShape, DenseShape, GemvProduct> // GEMV stands for matrix-vector : generic_product_impl_base<yannq::SRMat<Machine, Hamiltonian>, Rhs, generic_product_impl<yannq::SRMat<Machine, Hamiltonian>, Rhs> > { typedef typename Product<yannq::SRMat<Machine, Hamiltonian>, Rhs>::Scalar Scalar; template<typename Dest> static void scaleAndAddTo(Dest& dst, const yannq::SRMat<Machine, Hamiltonian>& lhs, const Rhs& rhs, const Scalar& alpha) { // This method should implement "dst += alpha * lhs * rhs" inplace, // however, for iterative solvers, alpha is always equal to 1, so let's not bother about it. assert(alpha==Scalar(1) && "scaling is not implemented"); EIGEN_ONLY_USED_FOR_DEBUG(alpha); dst += lhs.apply(rhs); } }; } //namespace internal } //namespace Eigen
25.257576
140
0.704109
cecri
fcb7afc3dd48dec66ac6bd54cf2bfb8bdf601d19
4,311
hh
C++
FTPD.hh
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
1
2017-09-14T13:31:16.000Z
2017-09-14T13:31:16.000Z
FTPD.hh
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
null
null
null
FTPD.hh
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
5
2015-04-11T02:59:06.000Z
2021-03-03T19:45:39.000Z
// // Copyright 2009-2017 M. Shulhan ([email protected]). All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef _LIBVOS_FTP_DAEMON_HH #define _LIBVOS_FTP_DAEMON_HH 1 #include <signal.h> #include "List.hh" #include "FTPD_client.hh" #include "FTPD_user.hh" namespace vos { #define FTPD_DEF_ADDRESS "0.0.0.0" #define FTPD_DEF_PORT 21 #define FTPD_DEF_PATH "./" enum _FTP_reply_msg_idx { CODE_150 = 0 , CODE_200 , CODE_211 , CODE_213 , CODE_215 , CODE_220 , CODE_221 , CODE_226 , CODE_227 , CODE_230 , CODE_250 , CODE_257 , CODE_331 , CODE_350 , CODE_421 , CODE_425 , CODE_450 , CODE_451 , CODE_501 , CODE_502 , CODE_503 , CODE_530 , CODE_550 , CODE_553 , N_REPLY_CODE }; extern const char* _FTP_reply_msg[N_REPLY_CODE]; enum _FTP_add_reply_msg { NODE_NOT_FOUND = 0 , NODE_IS_DIR , NODE_IS_NOT_DIR , TYPE_ALWAYS_BIN , MODE_ALWAYS_STREAM , STRU_ALWAYS_FILE , N_ADD_REPLY_MSG }; extern const char* _FTP_add_reply_msg[N_ADD_REPLY_MSG]; enum _FTP_auth_mode { AUTH_NOLOGIN = 0 , AUTH_LOGIN , N_FTP_MODE }; extern const char* _FTP_month[12]; /** * @class : FTPD * @attr : * - _running : flag for checking if server still running. * - _auth_mode : authentication mode, login or without login. * - _maxfd : maximum file descriptor, used by 'select()'. * - _path : the real path to directory that the server serve to * the networks. * - _dir : Dir object, contain cache of all files in 'path'. * - _fd_all : all file descriptor in the server, used by * 'select()'. * - _fd_read : the change descriptor, file descriptor that has the * change flag on after 'select()'. * - _clients : list of all server client. * - _users : list of all server account. * @desc : * A simple FTP server module for serving a file system to the network. */ class FTPD : public SockServer { public: FTPD(); ~FTPD(); int init(const char* address = FTPD_DEF_ADDRESS , const uint16_t port = FTPD_DEF_PORT , const char* path = FTPD_DEF_PATH , const int auth_mode = AUTH_NOLOGIN); int user_add(const char* name, const char* pass); int user_is_exist(const char* name, const char* pass = NULL); int add_command(const int code, const char* cmd_name , void (*callback)(FTPD*, FTPD_client*)); int set_path(const char* path); void set_default_callback(); int set_callback(const int code, void (*callback)(FTPD*, FTPD_client*)); int run(); void client_process(); int client_get_command(Socket* c, FTPD_cmd* ftp_cmd); void client_add(FTPD_client* c); void client_del(FTPD_client *c); int client_get_path(FTPD_client* c, int check_parm = 1); int client_get_parent_path(FTPD_client* c); int _running; int _auth_mode; int _maxfd; Buffer _path; Dir _dir; fd_set _fd_all; fd_set _fd_read; List _clients; List _users; List _cmds; static void on_cmd_USER(FTPD* s, FTPD_client* c); static void on_cmd_PASS(FTPD* s, FTPD_client* c); static void on_cmd_SYST(FTPD* s, FTPD_client* c); static void on_cmd_TYPE(FTPD* s, FTPD_client* c); static void on_cmd_MODE(FTPD* s, FTPD_client* c); static void on_cmd_STRU(FTPD* s, FTPD_client* c); static void on_cmd_FEAT(FTPD* s, FTPD_client* c); static void on_cmd_SIZE(FTPD* s, FTPD_client* c); static void on_cmd_MDTM(FTPD* s, FTPD_client* c); static void on_cmd_CWD(FTPD* s, FTPD_client* c); static void on_cmd_CDUP(FTPD* s, FTPD_client* c); static void on_cmd_PWD(FTPD* s, FTPD_client* c); static uint16_t GET_PASV_PORT(); static void on_cmd_PASV(FTPD* s, FTPD_client* c); static void on_cmd_LIST(FTPD* s, FTPD_client* c); static void on_cmd_NLST(FTPD* s, FTPD_client* c); static void on_cmd_RETR(FTPD* s, FTPD_client* c); static void on_cmd_STOR(FTPD* s, FTPD_client* c); static void on_cmd_DELE(FTPD* s, FTPD_client* c); static void on_cmd_RNFR(FTPD* s, FTPD_client* c); static void on_cmd_RNTO(FTPD* s, FTPD_client* c); static void on_cmd_RMD(FTPD* s, FTPD_client* c); static void on_cmd_MKD(FTPD* s, FTPD_client* c); static void on_cmd_QUIT(FTPD* s, FTPD_client* c); static void on_cmd_unknown(FTPD_client* c); static const char* __cname; private: FTPD(const FTPD&); void operator=(const FTPD&); }; } /* namespace::vos */ #endif // vi: ts=8 sw=8 tw=78:
26.127273
73
0.714683
shuLhan
fcbd46787c604435feefb34f3e5d2956c2767a25
1,251
hpp
C++
samal_lib/include/samal_lib/Forward.hpp
VayuDev/samal
edb67289b7a1160f917be9bd44cd734f9d865460
[ "MIT" ]
2
2021-02-26T07:39:08.000Z
2021-03-30T21:13:47.000Z
samal_lib/include/samal_lib/Forward.hpp
VayuDev/samal
edb67289b7a1160f917be9bd44cd734f9d865460
[ "MIT" ]
null
null
null
samal_lib/include/samal_lib/Forward.hpp
VayuDev/samal
edb67289b7a1160f917be9bd44cd734f9d865460
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <map> #include <string> namespace samal { class ASTNode; class DeclarationNode; class ModuleRootNode; class IdentifierNode; class ExpressionNode; class FunctionDeclarationNode; class ScopeNode; class BinaryExpressionNode; class IfExpressionNode; class FunctionCallExpressionNode; class FunctionChainExpressionNode; class TupleCreationNode; class TupleAccessExpressionNode; class AssignmentExpression; class LambdaCreationNode; class StackInformationTree; class CallableDeclarationNode; class NativeFunctionDeclarationNode; class ListCreationNode; class ListPropertyAccessExpression; class StructCreationNode; class StructFieldAccessExpression; class TailCallSelfStatementNode; class MatchExpression; class MoveToHeapExpression; class MoveToStackExpression; class CallableDeclarationNode; struct Parameter; using StructField = Parameter; struct EnumField; class Compiler; class Datatype; class ExternalVMValue; class VM; class Stack; struct Program; class VariableSearcher; class Parser; struct VMParameters; enum class CheckTypeRecursively; struct UndeterminedIdentifierReplacementMapValue; using UndeterminedIdentifierReplacementMap = std::map<std::string, UndeterminedIdentifierReplacementMapValue>; }
22.339286
110
0.86251
VayuDev
fcc1c532c62e71f6a7d57621b2ea985d06e10195
503
cpp
C++
contest/yukicoder/117.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
7
2018-04-14T14:55:51.000Z
2022-01-31T10:49:49.000Z
contest/yukicoder/117.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
5
2018-04-14T14:28:49.000Z
2019-05-11T02:22:10.000Z
contest/yukicoder/117.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
null
null
null
#include "math/combination.hpp" #include "math/mint.hpp" int main() { Combination<Mint> comb(2000000); int t(in); for (int i = 0; i < t; ++i) { char c(in); in.ignore(); int n(in); in.ignore(); int k(in); in.ignore(); switch (c) { case 'C': cout << comb.combination(n, k) << endl; break; case 'P': cout << comb.partial_permutation(n, k) << endl; break; case 'H': cout << comb.repetition(n, k) << endl; break; } } }
18.62963
53
0.506958
not522
fcca9422e1650a79a21ea1229a005305f60a50a6
1,112
cpp
C++
volume_I/acm_1010.cpp
raidenluikang/acm.timus.ru
9b7c99eb03959acff9dd96326eec642a2c31ed04
[ "MIT" ]
null
null
null
volume_I/acm_1010.cpp
raidenluikang/acm.timus.ru
9b7c99eb03959acff9dd96326eec642a2c31ed04
[ "MIT" ]
null
null
null
volume_I/acm_1010.cpp
raidenluikang/acm.timus.ru
9b7c99eb03959acff9dd96326eec642a2c31ed04
[ "MIT" ]
null
null
null
// acm.timus.ru 1010. Discrete Function. #include <cstdio> char buffer[ (1 << 21) ]; char const * o ; void initRead() { unsigned n; n = fread(buffer, 1, sizeof(buffer ) - 2, stdin); buffer[n] = '\0'; o = buffer; } unsigned readInt() { unsigned u = 0; while(*o && *o <= 32)++o; while(*o >='0' && *o <= '9') u = (u<<3) + (u<<1) + *o++ -'0'; return u; } int readInt_s() { unsigned u = 0, s = 0; while(*o && *o <= 32) ++o; if (*o == '+') ++o; else if (*o == '-') ++o, s = ~0; while(*o>='0' && *o <='9') u = (u<<3) + (u<<1) + *o++ -'0'; return (u ^ s ) + !!s; } int solve() { unsigned n; long long a, b, c, d = -1000000000000000000LL; unsigned j = 0; initRead(); n = readInt(); a = readInt_s(); for(unsigned i = 1; i != n; ++i, a = b) { b = readInt_s(); c = (b-a); if ( c > d ) { j = i; d = c; } else if (-c > d) { j = i; d = -c; } } printf("%u %u\n",j,j+1); return 0; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r", stdin); freopen("output.txt","w",stdout); #endif solve(); return 0; }
13.39759
62
0.455036
raidenluikang
fcdddbe53f12e9c893f9c69c6640f84b8ee5bdc3
8,490
cpp
C++
source/deps/illa/filter_bilinear.cpp
poppeman/Pictus
0e58285b89292d0b221ab4d09911ef439711cc59
[ "MIT" ]
73
2015-01-19T17:38:26.000Z
2022-02-15T06:16:08.000Z
source/deps/illa/filter_bilinear.cpp
poppeman/Pictus
0e58285b89292d0b221ab4d09911ef439711cc59
[ "MIT" ]
75
2015-01-01T17:32:24.000Z
2018-10-18T08:19:08.000Z
source/deps/illa/filter_bilinear.cpp
poppeman/Pictus
0e58285b89292d0b221ab4d09911ef439711cc59
[ "MIT" ]
18
2015-01-05T04:57:18.000Z
2022-03-06T01:35:10.000Z
#include "filter_bilinear.h" #include "filter_int.h" #define BSHIFT 11 #define BSHIFTx2 22 #define BMUL 2048 namespace Filter { namespace Scale { using namespace Geom; namespace Internal { void set_contrib(std::vector<Contrib>& contrib, uint32_t i, uint32_t max_i, uint32_t max_coord, uint32_t ofs) { uint32_t floor = ofs >> BSHIFT; if (i < max_i) { contrib[i].floor = floor; if ((contrib[i].floor + 1) >= max_coord) { contrib[i].floor = std::max<uint32_t>(2, max_coord) - 2; ofs = (contrib[i].floor << BSHIFT) + BMUL - 2; } } contrib[i].frac = ofs - (contrib[i].floor << BSHIFT); contrib[i].frac_inv = BMUL - contrib[i].frac; } } struct PaletteToDWord { PaletteToDWord(const Img::Palette& p) :m_p(p) {} uint32_t Assemble(uint8_t ul, uint32_t fUL, uint8_t ur, uint32_t fUR, uint8_t bl, uint32_t fBL, uint8_t br, uint32_t fBR) const { const Img::Color& cUL = m_p.Color(ul); const Img::Color& cUR = m_p.Color(ur); const Img::Color& cBL = m_p.Color(bl); const Img::Color& cBR = m_p.Color(br); uint32_t A = (cUL.A * fUL + cUR.A * fUR + cBL.A * fBL + cBR.A * fBR) >> BSHIFTx2; uint32_t R = (cUL.R * fUL + cUR.R * fUR + cBL.R * fBL + cBR.R * fBR) >> BSHIFTx2; uint32_t G = (cUL.G * fUL + cUR.G * fUR + cBL.G * fBL + cBR.G * fBR) >> BSHIFTx2; uint32_t B = (cUL.B * fUL + cUR.B * fUR + cBL.B * fBL + cBR.B * fBR) >> BSHIFTx2; return Img::ToARGBDWORD(A, R, G, B); } const Img::Palette& m_p; void operator=(const PaletteToDWord&) = delete; }; template <typename T, class U> void performBilinear(const FilterBuffer& source, FilterBuffer& dest, const Geom::RectInt& region, float zoom, U pixelConverter) { int width = region.Width(); int height = region.Height(); using namespace Internal; // Precalculate stuff std::vector<Contrib> x_contrib(width); std::vector<Contrib> y_contrib(height); for(int i = 0; i < width; ++i) { set_contrib(x_contrib, i, width, source.Dimensions.Width, static_cast<uint32_t>(((region.Left() + i + 0.25f) / zoom) * BMUL)); } for(int i = 0; i < height; ++i) { set_contrib(y_contrib, i, height, source.Dimensions.Height, static_cast<uint32_t>(((region.Top() + i + 0.25f) / zoom) * BMUL)); } uint8_t* destCurrentScanlinePtr = dest.BufferData; int rw = region.Width(); for (int y = 0; y < region.Height(); ++y) { uint32_t floorY = y_contrib[y].floor; uint32_t iFracY = y_contrib[y].frac; uint32_t iFracYinv = y_contrib[y].frac_inv; const T* currSourceScanUpper = reinterpret_cast<T*>(source.BufferData + floorY * source.Stride); const T* currSourceScanLower = reinterpret_cast<T*>(source.BufferData + (floorY + 1) * source.Stride); uint32_t* currDestPixel = reinterpret_cast<uint32_t*>(destCurrentScanlinePtr); for(int x = 0; x < rw; ++x) { uint32_t iFracX = x_contrib[x].frac; uint32_t iFracXinv = x_contrib[x].frac_inv; uint32_t fUL = (iFracXinv * iFracYinv); uint32_t fUR = (iFracX * iFracYinv); uint32_t fBL = (iFracXinv * iFracY); uint32_t fBR = (iFracX * iFracY); *(currDestPixel++) = pixelConverter.Assemble( currSourceScanUpper[x_contrib[x].floor], fUL, currSourceScanUpper[x_contrib[x].floor + 1], fUR, currSourceScanLower[x_contrib[x].floor], fBL, currSourceScanLower[x_contrib[x].floor + 1], fBR); } destCurrentScanlinePtr += dest.Stride; } } void Bilinear(const FilterBuffer& source, FilterBuffer& dest, const Geom::RectInt& region, Img::Format format, float zoom) { if (format == Img::Format::XRGB8888) { struct DWordToDWord { uint32_t Assemble(uint32_t ul, uint32_t fUL, uint32_t ur, uint32_t fUR, uint32_t bl, uint32_t fBL, uint32_t br, uint32_t fBR) const { return Img::ToARGBDWORD( 0xff, (Img::ChannelARGB8888Red(ul) * fUL + Img::ChannelARGB8888Red(ur) * fUR + Img::ChannelARGB8888Red(bl) * fBL + Img::ChannelARGB8888Red(br) * fBR) >> BSHIFTx2, (Img::ChannelARGB8888Green(ul) * fUL + Img::ChannelARGB8888Green(ur) * fUR + Img::ChannelARGB8888Green(bl) * fBL + Img::ChannelARGB8888Green(br) * fBR) >> BSHIFTx2, (Img::ChannelARGB8888Blue(ul) * fUL + Img::ChannelARGB8888Blue(ur) * fUR + Img::ChannelARGB8888Blue(bl) * fBL + Img::ChannelARGB8888Blue(br) * fBR) >> BSHIFTx2); } }; performBilinear<uint32_t>(source, dest, region, zoom, DWordToDWord()); } else if (format == Img::Format::ARGB8888) { struct DWordToDWord { uint32_t Assemble(uint32_t ul, uint32_t fUL, uint32_t ur, uint32_t fUR, uint32_t bl, uint32_t fBL, uint32_t br, uint32_t fBR) const { return Img::ToARGBDWORD( (Img::ChannelARGB8888Alpha(ul) * fUL + Img::ChannelARGB8888Alpha(ur) * fUR + Img::ChannelARGB8888Alpha(bl) * fBL + Img::ChannelARGB8888Alpha(br) * fBR) >> BSHIFTx2, (Img::ChannelARGB8888Red(ul) * fUL + Img::ChannelARGB8888Red(ur) * fUR + Img::ChannelARGB8888Red(bl) * fBL + Img::ChannelARGB8888Red(br) * fBR) >> BSHIFTx2, (Img::ChannelARGB8888Green(ul) * fUL + Img::ChannelARGB8888Green(ur) * fUR + Img::ChannelARGB8888Green(bl) * fBL + Img::ChannelARGB8888Green(br) * fBR) >> BSHIFTx2, (Img::ChannelARGB8888Blue(ul) * fUL + Img::ChannelARGB8888Blue(ur) * fUR + Img::ChannelARGB8888Blue(bl) * fBL + Img::ChannelARGB8888Blue(br) * fBR) >> BSHIFTx2); } }; performBilinear<uint32_t>(source, dest, region, zoom, DWordToDWord()); } else if (format == Img::Format::XRGB1555) { struct WordToDWord { uint32_t Assemble(uint16_t ul, uint32_t fUL, uint16_t ur, uint32_t fUR, uint16_t bl, uint32_t fBL, uint16_t br, uint32_t fBR) const { return Img::ToARGBDWORD( 0xff, ((Img::ChannelARGB1555Red(ul) * fUL + Img::ChannelARGB1555Red(ur) * fUR + Img::ChannelARGB1555Red(bl) * fBL + Img::ChannelARGB1555Red(br) * fBR) >> BSHIFTx2) << 3, ((Img::ChannelARGB1555Green(ul) * fUL + Img::ChannelARGB1555Green(ur) * fUR + Img::ChannelARGB1555Green(bl) * fBL + Img::ChannelARGB1555Green(br) * fBR) >> BSHIFTx2) << 3, ((Img::ChannelARGB1555Blue(ul) * fUL + Img::ChannelARGB1555Blue(ur) * fUR + Img::ChannelARGB1555Blue(bl) * fBL + Img::ChannelARGB1555Blue(br) * fBR) >> BSHIFTx2) << 3); } }; performBilinear<uint16_t>(source, dest, region, zoom, WordToDWord()); } else if (format == Img::Format::ARGB1555) { struct WordToDWord { uint32_t Assemble(uint16_t ul, uint32_t fUL, uint16_t ur, uint32_t fUR, uint16_t bl, uint32_t fBL, uint16_t br, uint32_t fBR) const { return Img::ToARGBDWORD( 255 * ((Img::ChannelARGB1555Alpha(ul) * fUL + Img::ChannelARGB1555Alpha(ur) * fUR + Img::ChannelARGB1555Alpha(bl) * fBL + Img::ChannelARGB1555Alpha(br) * fBR) >> BSHIFTx2), ((Img::ChannelARGB1555Red(ul) * fUL + Img::ChannelARGB1555Red(ur) * fUR + Img::ChannelARGB1555Red(bl) * fBL + Img::ChannelARGB1555Red(br) * fBR) >> BSHIFTx2) << 3, ((Img::ChannelARGB1555Green(ul) * fUL + Img::ChannelARGB1555Green(ur) * fUR + Img::ChannelARGB1555Green(bl) * fBL + Img::ChannelARGB1555Green(br) * fBR) >> BSHIFTx2) << 3, ((Img::ChannelARGB1555Blue(ul) * fUL + Img::ChannelARGB1555Blue(ur) * fUR + Img::ChannelARGB1555Blue(bl) * fBL + Img::ChannelARGB1555Blue(br) * fBR) >> BSHIFTx2) << 3); } }; performBilinear<uint16_t>(source, dest, region, zoom, WordToDWord()); } else if (format == Img::Format::RGB565) { struct WordToDWord { uint32_t Assemble(uint16_t ul, uint32_t fUL, uint16_t ur, uint32_t fUR, uint16_t bl, uint32_t fBL, uint16_t br, uint32_t fBR) const { return Img::ToARGBDWORD( 0xff, ((Img::ChannelRGB565Red(ul) * fUL + Img::ChannelRGB565Red(ur) * fUR + Img::ChannelRGB565Red(bl) * fBL + Img::ChannelRGB565Red(br) * fBR) >> BSHIFTx2) << 3, ((Img::ChannelRGB565Green(ul) * fUL + Img::ChannelRGB565Green(ur) * fUR + Img::ChannelRGB565Green(bl) * fBL + Img::ChannelRGB565Green(br) * fBR) >> BSHIFTx2) << 2, ((Img::ChannelRGB565Blue(ul) * fUL + Img::ChannelRGB565Blue(ur) * fUR + Img::ChannelRGB565Blue(bl) * fBL + Img::ChannelRGB565Blue(br) * fBR) >> BSHIFTx2)) << 3; } }; performBilinear<uint16_t>(source, dest, region, zoom, WordToDWord()); } else if (format == Img::Format::Index8) { performBilinear<uint8_t>(source, dest, region, zoom, PaletteToDWord(source.Palette)); } else DO_THROW(Err::InvalidParam, "Format not supported:" + ToAString(format)); } } }
50.236686
179
0.657362
poppeman
fce515526f796e03db673d3b9aafc044fb77f35e
233
cpp
C++
test/main.cpp
MaLarsson/umlaut
b02222127a9e7362b57403f58a8519cd8b6bf826
[ "BSL-1.0" ]
1
2018-06-24T13:47:42.000Z
2018-06-24T13:47:42.000Z
test/main.cpp
MaLarsson/umlaut
b02222127a9e7362b57403f58a8519cd8b6bf826
[ "BSL-1.0" ]
6
2018-09-25T10:56:38.000Z
2018-11-01T15:30:08.000Z
test/main.cpp
MaLarsson/umlaut
b02222127a9e7362b57403f58a8519cd8b6bf826
[ "BSL-1.0" ]
null
null
null
// Copyright Marcus Larsson 2018 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp>
29.125
81
0.772532
MaLarsson
fce574e659d0b82b5776bc44304c12270e0f1fde
598
cpp
C++
test/srpc/RpcCommandTest.cpp
mark-online/sne
92190c78a1710778acf16dd3a83af064db5c269b
[ "MIT" ]
null
null
null
test/srpc/RpcCommandTest.cpp
mark-online/sne
92190c78a1710778acf16dd3a83af064db5c269b
[ "MIT" ]
null
null
null
test/srpc/RpcCommandTest.cpp
mark-online/sne
92190c78a1710778acf16dd3a83af064db5c269b
[ "MIT" ]
null
null
null
#include "SrpcTestPCH.h" #include "DummyRpcCommand.h" #include <sne/test/StreamFixture.h> using namespace sne; using namespace sne::srpc; /** * @class RpcCommandTest * * RpcCommand test */ class RpcCommandTest : public test::BitStreamFixture { }; TEST_F(RpcCommandTest, testMarshal) { DummyRpcCommand rpcCommand(100, -100); rpcCommand.marshal(*ostream_); RRpcId id; id.serialize(*istream_); ASSERT_EQ(rpcCommand.getRpcId().get(), id.get()); int32_t p1; istream_->read(p1); ASSERT_EQ(100, p1); int32_t p2; istream_->read(p2); ASSERT_EQ(-100, p2); }
18.121212
53
0.683946
mark-online
fce84a743286189e8b4c054c752a7df8d32bb883
1,595
cpp
C++
tests/test_bhtool.cpp
butchhoward/bhtool
9d8099aafacb9aeb619298e63c5858ea1f1a5ea4
[ "MIT" ]
null
null
null
tests/test_bhtool.cpp
butchhoward/bhtool
9d8099aafacb9aeb619298e63c5858ea1f1a5ea4
[ "MIT" ]
null
null
null
tests/test_bhtool.cpp
butchhoward/bhtool
9d8099aafacb9aeb619298e63c5858ea1f1a5ea4
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include <bhtool/bhtool.hpp> #include <bhtool/stderrred.hpp> #include <bhtool/repo.hpp> #include "utils_test.hpp" using namespace bhtool; int some_command_fn(int, char *[]) { return 99; }; TEST( utilities, find_cmd_function_from_command ) { Commands cmds = { {std::string("some_command"), some_command_fn} }; auto actual = find_command("some_command", cmds); EXPECT_EQ(getStdFnAddress(actual), (size_t)&some_command_fn); } TEST( utilities, find_cmd_function_invalid_command_gives_usage ) { Commands cmds = { {std::string("some_command"), some_command_fn} }; auto actual = find_command("some_other_command", cmds); EXPECT_EQ(getStdFnAddress(actual), (size_t)&last_ditch_usage); } TEST( utilities, help_cmd_is_usage ) { auto actual = find_command("help", bhtool::command_map()); EXPECT_EQ(getStdFnAddress(actual), (size_t)&last_ditch_usage); } TEST( utilities, stderrred_cmd_is_stderrred ) { auto actual = find_command(stderrred::CMD_NAME, bhtool::command_map()); EXPECT_EQ(getStdFnAddress(actual), (size_t)&stderrred::stderrred); } TEST( utilities, repo_cmd_is_repo ) { auto actual = find_command(repo::CMD_NAME, bhtool::command_map()); EXPECT_EQ(getStdFnAddress(actual), (size_t)&repo::repo); } TEST( utilities, venv_cmd_is_not_implemented ) { auto actual = find_command("venv", bhtool::command_map()); EXPECT_EQ(getStdFnAddress(actual), (size_t)&not_implemented_yet); } TEST( bhtool, not_implemented_returns_86 ) { EXPECT_EQ(not_implemented_yet(0, nullptr), 86 ); }
26.583333
75
0.721003
butchhoward
fce867ac3e96f919d6c81e19bebcaaebaaea5805
3,790
cpp
C++
src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/symbol_tables_json_getter.cpp
lukasdurfina/retdec
7d6b8882690ff73c2bd7f209db10c5c091fa0359
[ "MIT", "Zlib", "BSD-3-Clause" ]
1
2020-03-28T02:38:53.000Z
2020-03-28T02:38:53.000Z
src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/symbol_tables_json_getter.cpp
lukasdurfina/retdec
7d6b8882690ff73c2bd7f209db10c5c091fa0359
[ "MIT", "Zlib", "BSD-3-Clause" ]
null
null
null
src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/symbol_tables_json_getter.cpp
lukasdurfina/retdec
7d6b8882690ff73c2bd7f209db10c5c091fa0359
[ "MIT", "Zlib", "BSD-3-Clause" ]
null
null
null
/** * @file src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/symbol_tables_json_getter.cpp * @brief Methods of SymbolTablesJsonGetter class. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #include "retdec/utils/string.h" #include "retdec/fileformat/utils/conversions.h" #include "fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/symbol_tables_json_getter.h" using namespace retdec::utils; using namespace retdec::fileformat; namespace fileinfo { /** * Constructor * @param fileInfo Information about file */ SymbolTablesJsonGetter::SymbolTablesJsonGetter(FileInformation &fileInfo) : IterativeSubtitleGetter(fileInfo) { numberOfStructures = fileinfo.getNumberOfStoredSymbolTables(); for(std::size_t i = 0; i < numberOfStructures; ++i) { numberOfStoredRecords.push_back(fileinfo.getNumberOfStoredSymbolsInTable(i)); const auto noOfSpecInfo = fileinfo.getSymbolTableNumberOfStoredSpecialInformation(i); numberOfExtraElements.push_back(noOfSpecInfo); std::vector<std::string> abbv; for(std::size_t j = 0; j < noOfSpecInfo; ++j) { abbv.push_back(fileinfo.getSymbolTableSpecialInformationAbbreviation(i, j)); } extraHeaderElements.push_back(abbv); } header = "symbolTables"; title = "symbolTable"; subtitle = "symbols"; commonHeaderElements.push_back("index"); commonHeaderElements.push_back("name"); commonHeaderElements.push_back("type"); commonHeaderElements.push_back("bind"); commonHeaderElements.push_back("other"); commonHeaderElements.push_back("associatedSectionIndex"); commonHeaderElements.push_back("value"); commonHeaderElements.push_back("address"); commonHeaderElements.push_back("associatedSize"); } std::size_t SymbolTablesJsonGetter::getBasicInfo(std::size_t structIndex, std::vector<std::string> &desc, std::vector<std::string> &info) const { if(structIndex >= numberOfStructures) { return 0; } desc.clear(); info.clear(); desc.push_back("name"); desc.push_back("offset"); desc.push_back("numberOfSymbols"); info.push_back(replaceNonprintableChars(fileinfo.getSymbolTableName(structIndex))); info.push_back(fileinfo.getSymbolTableOffsetStr(structIndex, hexWithPrefix)); info.push_back(fileinfo.getNumberOfDeclaredSymbolsInTableStr(structIndex)); return info.size(); } bool SymbolTablesJsonGetter::getRecord(std::size_t structIndex, std::size_t recIndex, std::vector<std::string> &record) const { if(structIndex >= numberOfStructures || recIndex >= numberOfStoredRecords[structIndex]) { return false; } record.clear(); record.push_back(fileinfo.getSymbolIndexStr(structIndex, recIndex)); record.push_back(replaceNonprintableChars(fileinfo.getSymbolName(structIndex, recIndex))); record.push_back(fileinfo.getSymbolType(structIndex, recIndex)); record.push_back(fileinfo.getSymbolBind(structIndex, recIndex)); record.push_back(fileinfo.getSymbolOther(structIndex, recIndex)); record.push_back(fileinfo.getSymbolLinkToSection(structIndex, recIndex)); record.push_back(fileinfo.getSymbolValueStr(structIndex, recIndex)); record.push_back(fileinfo.getSymbolAddressStr(structIndex, recIndex, hexWithPrefix)); record.push_back(fileinfo.getSymbolSizeStr(structIndex, recIndex)); for(std::size_t i = 0, e = numberOfExtraElements[structIndex]; i < e; ++i) { record.push_back(fileinfo.getSymbolTableSpecialInformationValue(structIndex, i, recIndex)); } return true; } bool SymbolTablesJsonGetter::getFlags(std::size_t structIndex, std::size_t recIndex, std::string &flagsValue, std::vector<std::string> &desc) const { if(structIndex >= numberOfStructures || recIndex >= numberOfStoredRecords[structIndex]) { return false; } flagsValue.clear(); desc.clear(); return true; } } // namespace fileinfo
34.144144
147
0.789446
lukasdurfina
fcf2d2fc5bb54a81ccb16b50204549b899d35625
2,752
hpp
C++
include/alflib/core/common.hpp
Alfret/AlfLibCpp
15bf07d31b0772a23904967f85495cbb2121f391
[ "MIT" ]
null
null
null
include/alflib/core/common.hpp
Alfret/AlfLibCpp
15bf07d31b0772a23904967f85495cbb2121f391
[ "MIT" ]
9
2019-06-19T19:35:34.000Z
2019-07-03T16:10:20.000Z
include/alflib/core/common.hpp
Alfret/AlfLibCpp
15bf07d31b0772a23904967f85495cbb2121f391
[ "MIT" ]
null
null
null
// MIT License // // Copyright (c) 2019 Filip Björklund // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once // ========================================================================== // // Headers // ========================================================================== // #include <cstdint> #include <string> // ========================================================================== // // Types // ========================================================================== // /** 8-bit character type **/ using char8 = char; static_assert(sizeof(char8) == 1, "Size of char8 expected to be 1"); #if defined(_WIN32) /** 16-bit character type **/ using char16 = wchar_t; #else /** 16-bit character type **/ using char16 = uint16_t; #endif static_assert(sizeof(char16) == 2, "Size of char8 expected to be 2"); /** 8-bit signed type **/ using s8 = int8_t; /** 8-bit unsigned type **/ using u8 = uint8_t; /** 16-bit signed type **/ using s16 = int16_t; /** 16-bit unsigned type **/ using u16 = uint16_t; /** 32-bit signed type **/ using s32 = int32_t; /** 32-bit unsigned type **/ using u32 = uint32_t; /** 64-bit signed type **/ using s64 = int64_t; /** 8-bit unsigned type **/ using u64 = uint64_t; /** 32-bit floating-point type **/ using f32 = float; /** 64-bit floating-point type **/ using f64 = double; // ========================================================================== // // Functions // ========================================================================== // namespace alflib { /** Returns the value of the specified bit. * \brief Returns bit value. * \param index Index of bit. * \return Value of bit. */ constexpr u64 Bit(u64 index) { return 1ull << index; } }
30.241758
80
0.583576
Alfret
fcf45f872213ed73003eda32c58d01fe6e9e9e6f
36,241
cpp
C++
gb++/src/Sharp/Sharp.cpp
dfrias100/gb-plus-plus
e5c48f18ab24315f1a5c70789cd3c1cae9428baf
[ "MIT" ]
null
null
null
gb++/src/Sharp/Sharp.cpp
dfrias100/gb-plus-plus
e5c48f18ab24315f1a5c70789cd3c1cae9428baf
[ "MIT" ]
null
null
null
gb++/src/Sharp/Sharp.cpp
dfrias100/gb-plus-plus
e5c48f18ab24315f1a5c70789cd3c1cae9428baf
[ "MIT" ]
null
null
null
#include "Sharp.hpp" #include "../Memory/Memory.hpp" #include <iostream> #include <iomanip> Sharp::Sharp(Memory* _MemoryBus) { MemoryBus = _MemoryBus; Suspended = false; HaltBug = false; // These are the register values when the PC is at // $0100 after the boot ROM is unmapped from memory PC = 0x0100; AF = 0x01B0; BC = 0x0013; DE = 0x00D8; HL = 0x014D; SP = 0xFFFE; InterruptMasterEnable = 0x01; //Log.open("execlog.txt", std::ios::trunc | std::ios::binary); } void Sharp::SetFlag(SharpFlags flag, bool set) { if (set) { F |= flag; } else { F &= ~flag; } } uint8_t Sharp::GetFlag(SharpFlags flag) { return (F & flag) > 0 ? 1 : 0; } // Helper Functions void Sharp::DecrementRegister(uint8_t& reg) { if ((reg & 0xF) == 0) { SetFlag(h, 1); } else { SetFlag(h, 0); } reg--; if (reg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 1); } void Sharp::IncrementRegister(uint8_t& reg) { if ((reg & 0xF) == 0xF) { SetFlag(h, 1); } else { SetFlag(h, 0); } reg++; if (reg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); } void Sharp::UnsignedAdd(uint8_t& dest, uint8_t src) { if (src > (0xFF - dest)) { SetFlag(c, 1); } else { SetFlag(c, 0); } temp = (dest & 0xF) + (src & 0xF); if ((temp & 0x10) == 0x10) { SetFlag(h, 1); } else { SetFlag(h, 0); } dest += src; if (dest == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); } void Sharp::UnsignedAddCarry(uint8_t& dest, uint8_t src) { temp = GetFlag(c); if (src > (0xFF - dest) || (temp && (src + dest) == 0xFF)) { SetFlag(c, 1); } else { SetFlag(c, 0); } temp2 = (dest & 0xF) + (src & 0xF) + temp; if ((temp2 & 0x10) == 0x10) { SetFlag(h, 1); } else { SetFlag(h, 0); } dest += src + temp; if (dest == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); } void Sharp::UnsignedAdd16(uint16_t& dest, uint16_t src) { if (src > (0xFFFF - dest)) { SetFlag(c, 1); } else { SetFlag(c, 0); } temp3 = (dest & 0x0FFF) + (src & 0x0FFF); if ((temp3 & 0x1000) == 0x1000) { SetFlag(h, 1); } else { SetFlag(h, 0); } dest += src; SetFlag(n, 0); } void Sharp::Subtract(uint8_t& dest, uint8_t src) { if (src > dest) { SetFlag(c, 1); } else { SetFlag(c, 0); } if ((src & 0xF) > (dest & 0xF)) { SetFlag(h, 1); } else { SetFlag(h, 0); } dest -= src; if (dest == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 1); } void Sharp::SubtractWithCarry(uint8_t& dest, uint8_t src) { temp = GetFlag(c); if (src > dest || (temp && (dest - src) == 0x0)) { SetFlag(c, 1); } else { SetFlag(c, 0); } if ((src & 0xF) > (dest & 0xF) || (temp && ((src & 0xF) - (dest & 0xF)) == 0)) { SetFlag(h, 1); } else { SetFlag(h, 0); } dest -= (src + temp); if (dest == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 1); } void Sharp::RotateLeftCircular(uint8_t& arg) { SetFlag(c, (arg & 0x80) >> 7); arg <<= 1; arg += GetFlag(c); if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); } void Sharp::RotateRightCircular(uint8_t& arg) { SetFlag(c, arg & 0x1); arg >>= 1; arg += (GetFlag(c) << 7); if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); } void Sharp::RotateLeft(uint8_t& arg) { temp2 = GetFlag(c); SetFlag(c, (arg & 0x80) >> 7); arg <<= 1; arg += temp2; if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); } void Sharp::RotateRight(uint8_t& arg) { temp2 = GetFlag(c); SetFlag(c, arg & 0x1); arg >>= 1; arg += (temp2 << 7); if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); } void Sharp::ShiftLeft(uint8_t& arg) { SetFlag(c, (arg & 0x80) >> 7); arg <<= 1; if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); } void Sharp::ShiftRightArithmetic(uint8_t& arg) { SetFlag(c, arg & 0x01); arg = (arg & 0x80) | (arg >> 1); if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); } void Sharp::ShiftRight(uint8_t& arg) { SetFlag(c, arg & 0x01); arg >>= 1; if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); } void Sharp::Swap(uint8_t& arg) { temp2 = arg & 0xF; arg &= 0xF0; arg >>= 4; arg |= (temp2 << 4); if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); SetFlag(c, 0); } void Sharp::And(uint8_t arg) { A &= arg; if (A == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 1); SetFlag(c, 0); } void Sharp::Xor(uint8_t arg) { A ^= arg; if (A == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); SetFlag(c, 0); } void Sharp::Or(uint8_t arg) { A |= arg; if (A == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); SetFlag(c, 0); } void Sharp::Bit(uint8_t pos, uint8_t arg) { SetFlag(z, ~(arg >> pos) & 0x1); SetFlag(n, 0); SetFlag(h, 1); } void Sharp::SetBit(uint8_t pos, uint8_t& arg) { arg |= 0x01 << pos; } void Sharp::ResetBit(uint8_t pos, uint8_t& arg) { arg = arg & ~(0x01 << pos); } void Sharp::UNOP() { } // Non 0xCB instructions void Sharp::NOP() { } void Sharp::LD_BC_DW() { BC = CurrOperand; } void Sharp::LD_ADDR_BC_A() { MemoryBus->WriteWord(BC, A); } void Sharp::INC_BC() { BC++; } void Sharp::INC_B() { IncrementRegister(B); } void Sharp::DEC_B() { DecrementRegister(B); } void Sharp::LD_B_W() { B = (uint8_t) CurrOperand; } void Sharp::RLCA() { RotateLeftCircular(A); SetFlag(z, 0); } void Sharp::LD_ADDR_DW_SP() { MemoryBus->WriteDoubleWord(CurrOperand, SP); } void Sharp::ADD_HL_BC() { UnsignedAdd16(HL, BC); } void Sharp::LD_A_ADDR_BC() { A = MemoryBus->ReadWord(BC); } void Sharp::DEC_BC() { BC--; } void Sharp::INC_C() { IncrementRegister(C); } void Sharp::DEC_C() { DecrementRegister(C); } void Sharp::LD_C_W() { C = (uint8_t) CurrOperand; } void Sharp::RRCA() { RotateRightCircular(A); SetFlag(z, 0); } void Sharp::STOP() { // I will ignore this instruction for now } void Sharp::LD_DE_DW() { DE = CurrOperand; } void Sharp::LD_ADDR_DE_A() { MemoryBus->WriteWord(DE, A); } void Sharp::INC_DE(){ DE++; } void Sharp::INC_D() { IncrementRegister(D); } void Sharp::DEC_D() { DecrementRegister(D); } void Sharp::LD_D_W() { D = (uint8_t) CurrOperand; } void Sharp::RLA() { RotateLeft(A); SetFlag(z, 0); } void Sharp::JR_SW() { PC = PC + (int8_t) (CurrOperand); } void Sharp::ADD_HL_DE() { UnsignedAdd16(HL, DE); } void Sharp::LD_A_ADDR_DE() { A = MemoryBus->ReadWord(DE); } void Sharp::DEC_DE() { DE--; } void Sharp::INC_E() { IncrementRegister(E); } void Sharp::DEC_E() { DecrementRegister(E); } void Sharp::LD_E_W() { E = (uint8_t) CurrOperand; } void Sharp::RRA() { RotateRight(A); SetFlag(z, 0); } void Sharp::JR_NZ_SW() { if (!GetFlag(z)) { PC += (int8_t) CurrOperand; CurrCycles += 4; } } void Sharp::LD_HL_DW() { HL = CurrOperand; } void Sharp::LD_ADDR_HL_PI_A() { MemoryBus->WriteWord(HL++, A); } void Sharp::INC_HL() { HL++; } void Sharp::INC_H() { IncrementRegister(H); } void Sharp::DEC_H() { DecrementRegister(H); } void Sharp::LD_H_W() { H = (uint8_t) CurrOperand; } void Sharp::DAA() { temp = 0x0; if (GetFlag(h) || (!GetFlag(n) && ((A & 0xF) > 0x9))) { temp |= 0x06; } if (GetFlag(c) || (!GetFlag(n) && (A > 0x99))) { temp |= 0x60; // Set the flag to 1 if and only if the previous instruction // Was an addition and either: // - A carry occurred // - Register A was bigger than 0x99 SetFlag(c, GetFlag(c) | (!GetFlag(n) && (GetFlag(c) || (A > 0x99)) ) ); } A += GetFlag(n) ? -temp : temp; if (A == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(h, 0); } void Sharp::JR_Z_SW() { if (GetFlag(z)) { PC += (int8_t) CurrOperand; CurrCycles += 4; } } void Sharp::ADD_HL_HL() { UnsignedAdd16(HL, HL); } void Sharp::LD_A_ADDR_HL_PI() { A = MemoryBus->ReadWord(HL++); } void Sharp::DEC_HL() { HL--; } void Sharp::INC_L() { IncrementRegister(L); } void Sharp::DEC_L() { DecrementRegister(L); } void Sharp::LD_L_W() { L = (uint8_t) CurrOperand; } void Sharp::CPL() { A = ~A; SetFlag(n, 1); SetFlag(h, 1); } void Sharp::JR_NC_SW() { if (!GetFlag(c)) { PC += (int8_t) CurrOperand; CurrCycles += 4; } } void Sharp::LD_SP_DW() { SP = CurrOperand; } void Sharp::LD_ADDR_HL_PD_A() { MemoryBus->WriteWord(HL--, A); } void Sharp::INC_SP() { SP++; } void Sharp::INC_ADDR_HL() { temp = MemoryBus->ReadWord(HL); IncrementRegister(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::DEC_ADDR_HL() { temp = MemoryBus->ReadWord(HL); DecrementRegister(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::LD_ADDR_HL_W() { MemoryBus->WriteWord(HL, (uint8_t) CurrOperand); } void Sharp::SCF() { SetFlag(n, 0); SetFlag(h, 0); SetFlag(c, 1); } void Sharp::JR_C_SW() { if (GetFlag(c)) { PC += (int8_t) CurrOperand; CurrCycles += 4; } } void Sharp::ADD_HL_SP() { UnsignedAdd16(HL, SP); } void Sharp::LD_A_ADDR_HL_PD() { A = MemoryBus->ReadWord(HL--); } void Sharp::DEC_SP() { SP--; } void Sharp::INC_A() { IncrementRegister(A); } void Sharp::DEC_A() { DecrementRegister(A); } void Sharp::LD_A_W() { A = (uint8_t) CurrOperand; } void Sharp::CCF() { SetFlag(n, 0); SetFlag(h, 0); SetFlag(c, !GetFlag(c)); } void Sharp::LD_B_B() { } void Sharp::LD_B_C() { B = C; } void Sharp::LD_B_D() { B = D; } void Sharp::LD_B_E() { B = E; } void Sharp::LD_B_H() { B = H; } void Sharp::LD_B_L() { B = L; } void Sharp::LD_B_ADDR_HL() { B = MemoryBus->ReadWord(HL); } void Sharp::LD_B_A() { B = A; } void Sharp::LD_C_B() { C = B; } void Sharp::LD_C_C() { } void Sharp::LD_C_D() { C = D; } void Sharp::LD_C_E() { C = E; } void Sharp::LD_C_H() { C = H; } void Sharp::LD_C_L() { C = L; } void Sharp::LD_C_ADDR_HL() { C = MemoryBus->ReadWord(HL); } void Sharp::LD_C_A() { C = A; } void Sharp::LD_D_B() { D = B; } void Sharp::LD_D_C() { D = C; } void Sharp::LD_D_D() { } void Sharp::LD_D_E() { D = E; } void Sharp::LD_D_H() { D = H; } void Sharp::LD_D_L() { D = L; } void Sharp::LD_D_ADDR_HL() { D = MemoryBus->ReadWord(HL); } void Sharp::LD_D_A() { D = A; } void Sharp::LD_E_B() { E = B; } void Sharp::LD_E_C() { E = C; } void Sharp::LD_E_D() { E = D; } void Sharp::LD_E_E() { } void Sharp::LD_E_H() { E = H; } void Sharp::LD_E_L() { E = L; } void Sharp::LD_E_ADDR_HL() { E = MemoryBus->ReadWord(HL); } void Sharp::LD_E_A() { E = A; } void Sharp::LD_H_B() { H = B; } void Sharp::LD_H_C() { H = C; } void Sharp::LD_H_D() { H = D; } void Sharp::LD_H_E() { H = E; } void Sharp::LD_H_H() { } void Sharp::LD_H_L() { H = L; } void Sharp::LD_H_ADDR_HL() { H = MemoryBus->ReadWord(HL); } void Sharp::LD_H_A() { H = A; } void Sharp::LD_L_B() { L = B; } void Sharp::LD_L_C() { L = C; } void Sharp::LD_L_D() { L = D; } void Sharp::LD_L_E() { L = E; } void Sharp::LD_L_H() { L = H; } void Sharp::LD_L_L() { } void Sharp::LD_L_ADDR_HL() { L = MemoryBus->ReadWord(HL); } void Sharp::LD_L_A() { L = A; } void Sharp::LD_ADDR_HL_B() { MemoryBus->WriteWord(HL, B); } void Sharp::LD_ADDR_HL_C() { MemoryBus->WriteWord(HL, C); } void Sharp::LD_ADDR_HL_D() { MemoryBus->WriteWord(HL, D); } void Sharp::LD_ADDR_HL_E() { MemoryBus->WriteWord(HL, E); } void Sharp::LD_ADDR_HL_H() { MemoryBus->WriteWord(HL, H); } void Sharp::LD_ADDR_HL_L() { MemoryBus->WriteWord(HL, L); } void Sharp::HALT() { // We only want to enter halt mode if the IME is enabled or we do not have a pending interrupt // Otherwise, we trigger the halt bug if (InterruptMasterEnable) { Suspended = true; } else { if ((MemoryBus->InterruptEnableRegister & *(MemoryBus->InterruptFlags) & 0x1F) == 0) { Suspended = true; } else { HaltBug = true; } } } void Sharp::LD_ADDR_HL_A() { MemoryBus->WriteWord(HL, A); } void Sharp::LD_A_B() { A = B; } void Sharp::LD_A_C() { A = C; } void Sharp::LD_A_D() { A = D; } void Sharp::LD_A_E() { A = E; } void Sharp::LD_A_H() { A = H; } void Sharp::LD_A_L() { A = L; } void Sharp::LD_A_ADDR_HL() { A = MemoryBus->ReadWord(HL); } void Sharp::LD_A_A() { } void Sharp::ADD_A_B() { UnsignedAdd(A, B); } void Sharp::ADD_A_C() { UnsignedAdd(A, C); } void Sharp::ADD_A_D() { UnsignedAdd(A, D); } void Sharp::ADD_A_E() { UnsignedAdd(A, E); } void Sharp::ADD_A_H() { UnsignedAdd(A, H); } void Sharp::ADD_A_L() { UnsignedAdd(A, L); } void Sharp::ADD_A_ADDR_HL() { temp = MemoryBus->ReadWord(HL); UnsignedAdd(A, temp); } void Sharp::ADD_A_A() { UnsignedAdd(A, A); } void Sharp::ADC_A_B() { UnsignedAddCarry(A, B); } void Sharp::ADC_A_C() { UnsignedAddCarry(A, C); } void Sharp::ADC_A_D() { UnsignedAddCarry(A, D); } void Sharp::ADC_A_E() { UnsignedAddCarry(A, E); } void Sharp::ADC_A_H() { UnsignedAddCarry(A, H); } void Sharp::ADC_A_L() { UnsignedAddCarry(A, L); } void Sharp::ADC_A_ADDR_HL() { temp = MemoryBus->ReadWord(HL); UnsignedAddCarry(A, temp); } void Sharp::ADC_A_A() { UnsignedAddCarry(A, A); } void Sharp::SUB_B() { Subtract(A, B); } void Sharp::SUB_C() { Subtract(A, C); } void Sharp::SUB_D() { Subtract(A, D); } void Sharp::SUB_E() { Subtract(A, E); } void Sharp::SUB_H() { Subtract(A, H); } void Sharp::SUB_L() { Subtract(A, L); } void Sharp::SUB_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Subtract(A, temp); } void Sharp::SUB_A() { Subtract(A, A); } void Sharp::SBC_A_B() { SubtractWithCarry(A, B); } void Sharp::SBC_A_C() { SubtractWithCarry(A, C); } void Sharp::SBC_A_D() { SubtractWithCarry(A, D); } void Sharp::SBC_A_E() { SubtractWithCarry(A, E); } void Sharp::SBC_A_H() { SubtractWithCarry(A, H); } void Sharp::SBC_A_L() { SubtractWithCarry(A, L); } void Sharp::SBC_A_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SubtractWithCarry(A, temp); } void Sharp::SBC_A_A() { SubtractWithCarry(A, A); } void Sharp::AND_B() { And(B); } void Sharp::AND_C() { And(C); } void Sharp::AND_D() { And(D); } void Sharp::AND_E() { And(E); } void Sharp::AND_H() { And(H); } void Sharp::AND_L() { And(L); } void Sharp::AND_ADDR_HL() { temp = MemoryBus->ReadWord(HL); And(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::AND_A() { And(A); } void Sharp::XOR_B() { Xor(B); } void Sharp::XOR_C() { Xor(C); } void Sharp::XOR_D() { Xor(D); } void Sharp::XOR_E() { Xor(E); } void Sharp::XOR_H() { Xor(H); } void Sharp::XOR_L() { Xor(L); } void Sharp::XOR_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Xor(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::XOR_A() { Xor(A); } void Sharp::OR_B() { Or(B); } void Sharp::OR_C() { Or(C); } void Sharp::OR_D() { Or(D); } void Sharp::OR_E() { Or(E); } void Sharp::OR_H() { Or(H); } void Sharp::OR_L() { Or(L); } void Sharp::OR_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Or(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::OR_A() { Or(A); } void Sharp::CP_B() { temp = A; Subtract(temp, B); } void Sharp::CP_C() { temp = A; Subtract(temp, C); } void Sharp::CP_D() { temp = A; Subtract(temp, D); } void Sharp::CP_E() { temp = A; Subtract(temp, E); } void Sharp::CP_H() { temp = A; Subtract(temp, H); } void Sharp::CP_L() { temp = A; Subtract(temp, L); } void Sharp::CP_ADDR_HL() { temp = A; temp2 = MemoryBus->ReadWord(HL); Subtract(temp, temp2); } void Sharp::CP_A() { temp = A; Subtract(temp, A); } void Sharp::RET_NZ() { if (!GetFlag(z)) { PC = MemoryBus->ReadDoubleWord(SP); SP += 2; CurrCycles += 12; } } void Sharp::POP_BC() { BC = MemoryBus->ReadDoubleWord(SP); SP += 2; } void Sharp::JP_NZ_ADDR_DW() { if (!GetFlag(z)) { PC = CurrOperand; CurrCycles += 4; } } void Sharp::JP_ADDR_DW() { PC = CurrOperand; } void Sharp::CALL_NZ_ADDR_DW() { if (!GetFlag(z)) { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = CurrOperand; CurrCycles += 12; } } void Sharp::PUSH_BC() { SP -= 2; MemoryBus->WriteDoubleWord(SP, BC); } void Sharp::ADD_A_W() { UnsignedAdd(A, (uint8_t) CurrOperand); } void Sharp::RST_00H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0000; } void Sharp::RET_Z() { if (GetFlag(z)) { PC = MemoryBus->ReadDoubleWord(SP); SP += 2; CurrCycles += 12; } } void Sharp::RET() { PC = MemoryBus->ReadDoubleWord(SP); SP += 2; } void Sharp::JP_Z_ADDR_DW() { if (GetFlag(z)) { PC = CurrOperand; CurrCycles += 4; } } void Sharp::PREFIX_CB() { Opcode = MemoryBus->ReadWord(PC++); DecodedInstr = SHARPINSTRS_CB[Opcode]; CurrCycles = DecodedInstr.Cycles; CurrArgSize = DecodedInstr.ArgSize; (this->*DecodedInstr.Instruction)(); } void Sharp::CALL_Z_ADDR_DW() { if (GetFlag(z)) { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = CurrOperand; CurrCycles += 12; } } void Sharp::CALL_ADDR_DW() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = CurrOperand; } void Sharp::ADC_A_W() { UnsignedAddCarry(A, (uint8_t) CurrOperand); } void Sharp::RST_08H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0008; } void Sharp::RET_NC() { if (!GetFlag(c)) { PC = MemoryBus->ReadDoubleWord(SP); SP += 2; CurrCycles += 12; } } void Sharp::POP_DE() { DE = MemoryBus->ReadDoubleWord(SP); SP += 2; } void Sharp::JP_NC_ADDR_DW() { if (!GetFlag(c)) { PC = CurrOperand; CurrCycles += 4; } } void Sharp::CALL_NC_ADDR_DW() { if (!GetFlag(c)) { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = CurrOperand; CurrCycles += 12; } } void Sharp::PUSH_DE() { SP -= 2; MemoryBus->WriteDoubleWord(SP, DE); } void Sharp::SUB_W() { Subtract(A, (uint8_t)CurrOperand); } void Sharp::RST_10H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0010; } void Sharp::RET_C() { if (GetFlag(c)) { PC = MemoryBus->ReadDoubleWord(SP); SP += 2; CurrCycles += 12; } } void Sharp::RETI() { PC = MemoryBus->ReadDoubleWord(SP); SP += 2; InterruptMasterEnable = 0x1; } void Sharp::JP_C_ADDR_DW() { if (GetFlag(c)) { PC = CurrOperand; CurrCycles += 4; } } void Sharp::CALL_C_ADDR_DW() { if (GetFlag(c)) { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = CurrOperand; CurrCycles += 12; } } void Sharp::SBC_A_W() { SubtractWithCarry(A, (uint8_t) CurrOperand); } void Sharp::RST_18H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0018; } void Sharp::LDH_ADDR_W_A() { MemoryBus->WriteWord(0xFF00 | (uint8_t)CurrOperand, A); } void Sharp::POP_HL() { HL = MemoryBus->ReadDoubleWord(SP); SP += 2; } void Sharp::LD_ADDR_C_A() { MemoryBus->WriteWord(0xFF00 | C, A); } void Sharp::PUSH_HL() { SP -= 2; MemoryBus->WriteDoubleWord(SP, HL); } void Sharp::AND_W() { And((uint8_t)CurrOperand); } void Sharp::RST_20H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0020; } void Sharp::ADD_SP_SW() { temp3 = CurrOperand & 0x80 ? 0xFF00 | CurrOperand : CurrOperand & 0xFF; if ((temp3 & 0xFF) > (0xFF - (SP & 0xFF))) { SetFlag(c, 1); } else { SetFlag(c, 0); } temp3 = (SP & 0xF) + (temp3 & 0xF); if ((temp3 & 0x10) == 0x10) { SetFlag(h, 1); } else { SetFlag(h, 0); } SP += (int8_t) CurrOperand; SetFlag(z, 0); SetFlag(n, 0); } void Sharp::JP_HL() { PC = HL; } void Sharp::LD_ADDR_DW_A() { MemoryBus->WriteWord(CurrOperand, A); } void Sharp::XOR_W() { Xor((uint8_t) CurrOperand); } void Sharp::RST_28H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0028; } void Sharp::LDH_A_ADDR_W() { A = MemoryBus->ReadWord(0xFF00 | (uint8_t) CurrOperand); } void Sharp::POP_AF() { AF = MemoryBus->ReadDoubleWord(SP) & 0xFFF0; SP += 2; } void Sharp::LD_A_ADDR_C() { A = MemoryBus->ReadWord(0xFF00 | C); } // Blargg's ROMs seem to conclude the behavior of these instructions are O.K. void Sharp::DI() { PendingIMEChange = 0x10 | 0x02; } void Sharp::PUSH_AF() { SP -= 2; MemoryBus->WriteDoubleWord(SP, AF); } void Sharp::OR_W() { Or((uint8_t) CurrOperand); } void Sharp::RST_30H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0030; } void Sharp::LD_HL_SP_PLUS_SW() { CurrOperand = CurrOperand & 0x80 ? 0xFF00 | CurrOperand : CurrOperand & 0xFF; temp = SP; UnsignedAdd(temp, CurrOperand); HL = SP + (int8_t) CurrOperand; SetFlag(z, 0); SetFlag(n, 0); } void Sharp::LD_SP_HL() { SP = HL; } void Sharp::LD_A_ADDR_DW() { A = MemoryBus->ReadWord(CurrOperand); } void Sharp::EI() { PendingIMEChange = 0x90 | 0x02; } void Sharp::CP_W() { temp = A; Subtract(temp, (uint8_t) CurrOperand); } void Sharp::RST_38H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0038; } void Sharp::RLC_B() { RotateLeftCircular(B); } void Sharp::RLC_C() { RotateLeftCircular(C); } void Sharp::RLC_D() { RotateLeftCircular(D); } void Sharp::RLC_E() { RotateLeftCircular(E); } void Sharp::RLC_H() { RotateLeftCircular(H); } void Sharp::RLC_L() { RotateLeftCircular(L); } void Sharp::RLC_ADDR_HL() { temp = MemoryBus->ReadWord(HL); RotateLeftCircular(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RLC_A() { RotateLeftCircular(A); } void Sharp::RRC_B() { RotateRightCircular(B); } void Sharp::RRC_C() { RotateRightCircular(C); } void Sharp::RRC_D() { RotateRightCircular(D); } void Sharp::RRC_E() { RotateRightCircular(E); } void Sharp::RRC_H() { RotateRightCircular(H); } void Sharp::RRC_L() { RotateRightCircular(L); } void Sharp::RRC_ADDR_HL() { temp = MemoryBus->ReadWord(HL); RotateRightCircular(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RRC_A() { RotateRightCircular(A); } void Sharp::RL_B() { RotateLeft(B); } void Sharp::RL_C() { RotateLeft(C); } void Sharp::RL_D() { RotateLeft(D); } void Sharp::RL_E() { RotateLeft(E); } void Sharp::RL_H() { RotateLeft(H); } void Sharp::RL_L() { RotateLeft(L); } void Sharp::RL_ADDR_HL() { temp = MemoryBus->ReadWord(HL); RotateLeft(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RL_A() { RotateLeft(A); } void Sharp::RR_B() { RotateRight(B); } void Sharp::RR_C() { RotateRight(C); } void Sharp::RR_D() { RotateRight(D); } void Sharp::RR_E() { RotateRight(E); } void Sharp::RR_H() { RotateRight(H); } void Sharp::RR_L() { RotateRight(L); } void Sharp::RR_ADDR_HL() { temp = MemoryBus->ReadWord(HL); RotateRight(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RR_A() { RotateRight(A); } void Sharp::SLA_B() { ShiftLeft(B); } void Sharp::SLA_C() { ShiftLeft(C); } void Sharp::SLA_D() { ShiftLeft(D); } void Sharp::SLA_E() { ShiftLeft(E); } void Sharp::SLA_H() { ShiftLeft(H); } void Sharp::SLA_L() { ShiftLeft(L); } void Sharp::SLA_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ShiftLeft(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SLA_A() { ShiftLeft(A); } void Sharp::SRA_B() { ShiftRightArithmetic(B); } void Sharp::SRA_C() { ShiftRightArithmetic(C); } void Sharp::SRA_D() { ShiftRightArithmetic(D); } void Sharp::SRA_E() { ShiftRightArithmetic(E); } void Sharp::SRA_H() { ShiftRightArithmetic(H); } void Sharp::SRA_L() { ShiftRightArithmetic(L); } void Sharp::SRA_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ShiftRightArithmetic(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SRA_A() { ShiftRightArithmetic(A); } void Sharp::SWAP_B() { Swap(B); } void Sharp::SWAP_C() { Swap(C); } void Sharp::SWAP_D() { Swap(D); } void Sharp::SWAP_E() { Swap(E); } void Sharp::SWAP_H() { Swap(H); } void Sharp::SWAP_L() { Swap(L); } void Sharp::SWAP_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Swap(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SWAP_A() { Swap(A); } void Sharp::SRL_B() { ShiftRight(B); } void Sharp::SRL_C() { ShiftRight(C); } void Sharp::SRL_D() { ShiftRight(D); } void Sharp::SRL_E() { ShiftRight(E); } void Sharp::SRL_H() { ShiftRight(H); } void Sharp::SRL_L() { ShiftRight(L); } void Sharp::SRL_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ShiftRight(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SRL_A() { ShiftRight(A); } void Sharp::BIT_0_B() { Bit(0, B); } void Sharp::BIT_0_C() { Bit(0, C); } void Sharp::BIT_0_D() { Bit(0, D); } void Sharp::BIT_0_E() { Bit(0, E); } void Sharp::BIT_0_H() { Bit(0, H); } void Sharp::BIT_0_L() { Bit(0, L); } void Sharp::BIT_0_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(0, temp); } void Sharp::BIT_0_A() { Bit(0, A); } void Sharp::BIT_1_B() { Bit(1, B); } void Sharp::BIT_1_C() { Bit(1, C); } void Sharp::BIT_1_D() { Bit(1, D); } void Sharp::BIT_1_E() { Bit(1, E); } void Sharp::BIT_1_H() { Bit(1, H); } void Sharp::BIT_1_L() { Bit(1, L); } void Sharp::BIT_1_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(1, temp); } void Sharp::BIT_1_A() { Bit(1, A); } void Sharp::BIT_2_B() { Bit(2, B); } void Sharp::BIT_2_C() { Bit(2, C); } void Sharp::BIT_2_D() { Bit(2, D); } void Sharp::BIT_2_E() { Bit(2, E); } void Sharp::BIT_2_H() { Bit(2, H); } void Sharp::BIT_2_L() { Bit(2, L); } void Sharp::BIT_2_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(2, temp); } void Sharp::BIT_2_A() { Bit(2, A); } void Sharp::BIT_3_B() { Bit(3, B); } void Sharp::BIT_3_C() { Bit(3, C); } void Sharp::BIT_3_D() { Bit(3, D); } void Sharp::BIT_3_E() { Bit(3, E); } void Sharp::BIT_3_H() { Bit(3, H); } void Sharp::BIT_3_L() { Bit(3, L); } void Sharp::BIT_3_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(3, temp); } void Sharp::BIT_3_A() { Bit(3, A); } void Sharp::BIT_4_B() { Bit(4, B); } void Sharp::BIT_4_C() { Bit(4, C); } void Sharp::BIT_4_D() { Bit(4, D); } void Sharp::BIT_4_E() { Bit(4, E); } void Sharp::BIT_4_H() { Bit(4, H); } void Sharp::BIT_4_L() { Bit(4, L); } void Sharp::BIT_4_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(4, temp); } void Sharp::BIT_4_A() { Bit(4, A); } void Sharp::BIT_5_B() { Bit(5, B); } void Sharp::BIT_5_C() { Bit(5, C); } void Sharp::BIT_5_D() { Bit(5, D); } void Sharp::BIT_5_E() { Bit(5, E); } void Sharp::BIT_5_H() { Bit(5, H); } void Sharp::BIT_5_L() { Bit(5, L); } void Sharp::BIT_5_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(5, temp); } void Sharp::BIT_5_A() { Bit(5, A); } void Sharp::BIT_6_B() { Bit(6, B); } void Sharp::BIT_6_C() { Bit(6, C); } void Sharp::BIT_6_D() { Bit(6, D); } void Sharp::BIT_6_E() { Bit(6, E); } void Sharp::BIT_6_H() { Bit(6, H); } void Sharp::BIT_6_L() { Bit(6, L); } void Sharp::BIT_6_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(6, temp); } void Sharp::BIT_6_A() { Bit(6, A); } void Sharp::BIT_7_B() { Bit(7, B); } void Sharp::BIT_7_C() { Bit(7, C); } void Sharp::BIT_7_D() { Bit(7, D); } void Sharp::BIT_7_E() { Bit(7, E); } void Sharp::BIT_7_H() { Bit(7, H); } void Sharp::BIT_7_L() { Bit(7, L); } void Sharp::BIT_7_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(7, temp); } void Sharp::BIT_7_A() { Bit(7, A); } void Sharp::RES_0_B() { ResetBit(0, B); } void Sharp::RES_0_C() { ResetBit(0, C); } void Sharp::RES_0_D() { ResetBit(0, D); } void Sharp::RES_0_E() { ResetBit(0, E); } void Sharp::RES_0_H() { ResetBit(0, H); } void Sharp::RES_0_L() { ResetBit(0, L); } void Sharp::RES_0_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(0, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_0_A() { ResetBit(0, A); } void Sharp::RES_1_B() { ResetBit(1, B); } void Sharp::RES_1_C() { ResetBit(1, C); } void Sharp::RES_1_D() { ResetBit(1, D); } void Sharp::RES_1_E() { ResetBit(1, E); } void Sharp::RES_1_H() { ResetBit(1, H); } void Sharp::RES_1_L() { ResetBit(1, L); } void Sharp::RES_1_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(1, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_1_A() { ResetBit(1, A); } void Sharp::RES_2_B() { ResetBit(2, B); } void Sharp::RES_2_C() { ResetBit(2, C); } void Sharp::RES_2_D() { ResetBit(2, D); } void Sharp::RES_2_E() { ResetBit(2, E); } void Sharp::RES_2_H() { ResetBit(2, H); } void Sharp::RES_2_L() { ResetBit(2, L); } void Sharp::RES_2_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(2, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_2_A() { ResetBit(2, A); } void Sharp::RES_3_B() { ResetBit(3, B); } void Sharp::RES_3_C() { ResetBit(3, C); } void Sharp::RES_3_D() { ResetBit(3, D); } void Sharp::RES_3_E() { ResetBit(3, E); } void Sharp::RES_3_H() { ResetBit(3, H); } void Sharp::RES_3_L() { ResetBit(3, L); } void Sharp::RES_3_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(3, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_3_A() { ResetBit(3, A); } void Sharp::RES_4_B() { ResetBit(4, B); } void Sharp::RES_4_C() { ResetBit(4, C); } void Sharp::RES_4_D() { ResetBit(4, D); } void Sharp::RES_4_E() { ResetBit(4, E); } void Sharp::RES_4_H() { ResetBit(4, H); } void Sharp::RES_4_L() { ResetBit(4, L); } void Sharp::RES_4_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(4, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_4_A() { ResetBit(4, A); } void Sharp::RES_5_B() { ResetBit(5, B); } void Sharp::RES_5_C() { ResetBit(5, C); } void Sharp::RES_5_D() { ResetBit(5, D); } void Sharp::RES_5_E() { ResetBit(5, E); } void Sharp::RES_5_H() { ResetBit(5, H); } void Sharp::RES_5_L() { ResetBit(5, L); } void Sharp::RES_5_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(5, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_5_A() { ResetBit(5, A); } void Sharp::RES_6_B() { ResetBit(6, B); } void Sharp::RES_6_C() { ResetBit(6, C); } void Sharp::RES_6_D() { ResetBit(6, D); } void Sharp::RES_6_E() { ResetBit(6, E); } void Sharp::RES_6_H() { ResetBit(6, H); } void Sharp::RES_6_L() { ResetBit(6, L); } void Sharp::RES_6_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(6, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_6_A() { ResetBit(6, A); } void Sharp::RES_7_B() { ResetBit(7, B); } void Sharp::RES_7_C() { ResetBit(7, C); } void Sharp::RES_7_D() { ResetBit(7, D); } void Sharp::RES_7_E() { ResetBit(7, E); } void Sharp::RES_7_H() { ResetBit(7, H); } void Sharp::RES_7_L() { ResetBit(7, L); } void Sharp::RES_7_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(7, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_7_A() { ResetBit(7, A); } void Sharp::SET_0_B() { SetBit(0, B); } void Sharp::SET_0_C() { SetBit(0, C); } void Sharp::SET_0_D() { SetBit(0, D); } void Sharp::SET_0_E() { SetBit(0, E); } void Sharp::SET_0_H() { SetBit(0, H); } void Sharp::SET_0_L() { SetBit(0, L); } void Sharp::SET_0_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(0, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_0_A() { SetBit(0, A); } void Sharp::SET_1_B() { SetBit(1, B); } void Sharp::SET_1_C() { SetBit(1, C); } void Sharp::SET_1_D() { SetBit(1, D); } void Sharp::SET_1_E() { SetBit(1, E); } void Sharp::SET_1_H() { SetBit(1, H); } void Sharp::SET_1_L() { SetBit(1, L); } void Sharp::SET_1_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(1, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_1_A() { SetBit(1, A); } void Sharp::SET_2_B() { SetBit(2, B); } void Sharp::SET_2_C() { SetBit(2, C); } void Sharp::SET_2_D() { SetBit(2, D); } void Sharp::SET_2_E() { SetBit(2, E); } void Sharp::SET_2_H() { SetBit(2, H); } void Sharp::SET_2_L() { SetBit(2, L); } void Sharp::SET_2_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(2, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_2_A() { SetBit(2, A); } void Sharp::SET_3_B() { SetBit(3, B); } void Sharp::SET_3_C() { SetBit(3, C); } void Sharp::SET_3_D() { SetBit(3, D); } void Sharp::SET_3_E() { SetBit(3, E); } void Sharp::SET_3_H() { SetBit(3, H); } void Sharp::SET_3_L() { SetBit(3, L); } void Sharp::SET_3_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(3, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_3_A() { SetBit(3, A); } void Sharp::SET_4_B() { SetBit(4, B); } void Sharp::SET_4_C() { SetBit(4, C); } void Sharp::SET_4_D() { SetBit(4, D); } void Sharp::SET_4_E() { SetBit(4, E); } void Sharp::SET_4_H() { SetBit(4, H); } void Sharp::SET_4_L() { SetBit(4, L); } void Sharp::SET_4_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(4, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_4_A() { SetBit(4, A); } void Sharp::SET_5_B() { SetBit(5, B); } void Sharp::SET_5_C() { SetBit(5, C); } void Sharp::SET_5_D() { SetBit(5, D); } void Sharp::SET_5_E() { SetBit(5, E); } void Sharp::SET_5_H() { SetBit(5, H); } void Sharp::SET_5_L() { SetBit(5, L); } void Sharp::SET_5_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(5, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_5_A() { SetBit(5, A); } void Sharp::SET_6_B() { SetBit(6, B); } void Sharp::SET_6_C() { SetBit(6, C); } void Sharp::SET_6_D() { SetBit(6, D); } void Sharp::SET_6_E() { SetBit(6, E); } void Sharp::SET_6_H() { SetBit(6, H); } void Sharp::SET_6_L() { SetBit(6, L); } void Sharp::SET_6_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(6, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_6_A() { SetBit(6, A); } void Sharp::SET_7_B() { SetBit(7, B); } void Sharp::SET_7_C() { SetBit(7, C); } void Sharp::SET_7_D() { SetBit(7, D); } void Sharp::SET_7_E() { SetBit(7, E); } void Sharp::SET_7_H() { SetBit(7, H); } void Sharp::SET_7_L() { SetBit(7, L); } void Sharp::SET_7_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(7, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_7_A() { SetBit(7, A); } void Sharp::INT_40() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x40; CurrCycles += 12; } void Sharp::INT_48() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x48; CurrCycles += 12; } void Sharp::INT_50() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x50; CurrCycles += 12; } void Sharp::INT_58() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x58; CurrCycles += 12; } void Sharp::INT_60() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x60; CurrCycles += 12; } Sharp::~Sharp() { Log.close(); } // This is kind of a mess, but looking past all the pointer dereferencing // we exit halt (if any) and service the ISR based on the bits set void Sharp::InterruptHandler() { if (MemoryBus->InterruptEnableRegister & *(MemoryBus->InterruptFlags) & 0x1F) { Suspended = false; } if (InterruptMasterEnable && MemoryBus->InterruptEnableRegister && *(MemoryBus->InterruptFlags)) { temp = MemoryBus->InterruptEnableRegister & *(MemoryBus->InterruptFlags) & 0x1F; if (temp & VBLANK) { *(MemoryBus->InterruptFlags) &= ~VBLANK; INT_40(); } if (temp & LCDSTAT) { *(MemoryBus->InterruptFlags) &= ~LCDSTAT; INT_48(); } if (temp & TIMER) { *(MemoryBus->InterruptFlags) &= ~TIMER; INT_50(); } if (temp & SERIAL) { *(MemoryBus->InterruptFlags) &= ~SERIAL; INT_58(); } if (temp & JOYPAD) { *(MemoryBus->InterruptFlags) &= ~JOYPAD; INT_60(); } } } void Sharp::Clock() { if (!Suspended) { if (CurrCycles == 0) { switch(HaltBug) { case false: Opcode = MemoryBus->ReadWord(PC++); break; case true: Opcode = MemoryBus->ReadWord(PC); HaltBug = false; break; } DecodedInstr = SHARPINSTRS[Opcode]; CurrCycles = DecodedInstr.Cycles; CurrArgSize = DecodedInstr.ArgSize; switch (CurrArgSize) { case 1: CurrOperand = (uint16_t) MemoryBus->ReadWord(PC++); break; case 2: CurrOperand = MemoryBus->ReadDoubleWord(PC); PC += 2; break; } (this->*DecodedInstr.Instruction)(); if ((PendingIMEChange & 0x10) && ((PendingIMEChange & 0x0F) > 0)) { PendingIMEChange--; if ((PendingIMEChange & 0x0F) == 0) { InterruptMasterEnable = (PendingIMEChange & 0x80) >> 7; PendingIMEChange = 0x00; } } } CurrCycles--; } } /*/ Should the emulator report to the CPU that it will be loading the boot ROM, these values should be zero iniialized; we will let the code from the boot ROM set the registers when as it reaches PC = $0100 */ void Sharp::SetupBootRom() { PC = 0x0000; AF = 0x0000; BC = 0x0000; DE = 0x0000; HL = 0x0000; SP = 0xFFFE; }
13.145085
99
0.603101
dfrias100
fcf7dd033191d34e26c8ff85621d5edfd177377f
178
hpp
C++
src/parser/sql-stmt/NotImplemented/CreateIndex.hpp
TrueFinch/KappaDBMS
f4f9e91c52ae33f929e6db458a713a98a9958da3
[ "Apache-2.0" ]
2
2018-10-29T05:38:27.000Z
2018-12-05T15:32:16.000Z
src/parser/sql-stmt/NotImplemented/CreateIndex.hpp
TrueFinch/KappaDBMS
f4f9e91c52ae33f929e6db458a713a98a9958da3
[ "Apache-2.0" ]
null
null
null
src/parser/sql-stmt/NotImplemented/CreateIndex.hpp
TrueFinch/KappaDBMS
f4f9e91c52ae33f929e6db458a713a98a9958da3
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Instruction.hpp" namespace cmd { class CreateIndex : public Instruction { public: CreateIndex() : Instruction(CREATE_INDEX) {} }; } // namespace cmd
12.714286
46
0.719101
TrueFinch
fcfc146114073eed0b5c33f3e1197d85925cfbad
546
cpp
C++
side_projects/meh.cpp
mohsend/Magnificent-University-projects
4b0f9df939a60ace45eeccb331db85af77d83ee9
[ "MIT" ]
null
null
null
side_projects/meh.cpp
mohsend/Magnificent-University-projects
4b0f9df939a60ace45eeccb331db85af77d83ee9
[ "MIT" ]
null
null
null
side_projects/meh.cpp
mohsend/Magnificent-University-projects
4b0f9df939a60ace45eeccb331db85af77d83ee9
[ "MIT" ]
null
null
null
/* * meh */ #include <iostream> #include <cstdint> using namespace std; int main(int argc, char **argv) { uint64_t meh = 0xFFFFFFFFFFFFFFFF; uint64_t age; cout << "meh = " << meh << endl; cout << "How old are you? "; cin >> age; cout << "meh per year = " << meh / age << endl; cout << "meh per month = " << meh / (age * 12) << endl; cout << "meh per day = " << meh / (age * 365) << endl; cout << "meh per hour = " << meh / (age * 365 * 24) << endl; cout << "meh per second = " << meh / (age * 365 * 24 * 3600) << endl; return 0; }
23.73913
70
0.540293
mohsend
fcfcb12990a02ce4a9227554af03bb56abd58491
1,223
cpp
C++
ToDoTick/MainPage.xaml.cpp
HumorLogic/To-Do-Tick
377c651f63b51f64178b42121e71961f9df26e99
[ "Apache-2.0" ]
null
null
null
ToDoTick/MainPage.xaml.cpp
HumorLogic/To-Do-Tick
377c651f63b51f64178b42121e71961f9df26e99
[ "Apache-2.0" ]
null
null
null
ToDoTick/MainPage.xaml.cpp
HumorLogic/To-Do-Tick
377c651f63b51f64178b42121e71961f9df26e99
[ "Apache-2.0" ]
null
null
null
// // MainPage.xaml.cpp // MainPage 类的实现。 // #include "pch.h" #include "MainPage.xaml.h" #include<chrono> #include<thread> using namespace ToDoTick; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; // https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x804 上介绍了“空白页”项模板 MainPage::MainPage() { InitializeComponent(); } void ToDoTick::MainPage::startPauseBtn_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { //TickTime(); //timeText->Text =time; TickTime(timeText); } void MainPage::TickTime(TextBlock^ timeText) { auto start =chrono::system_clock::now(); this_thread::sleep_for(chrono::seconds(3)); auto end = chrono::system_clock::now(); chrono::duration<double> elapsed = end - start; time = elapsed.count().ToString(); timeText->Text = time; //throw ref new Platform::NotImplementedException(); }
23.519231
109
0.740801
HumorLogic
1e01dd6fa61eee60c906dc22edb364794e675b1a
10,563
hpp
C++
src/eyelib/window/event.hpp
lucas137/eyelib
e88eaea6dd2c2e4b365d178f67869a3cd47751a5
[ "MIT" ]
null
null
null
src/eyelib/window/event.hpp
lucas137/eyelib
e88eaea6dd2c2e4b365d178f67869a3cd47751a5
[ "MIT" ]
null
null
null
src/eyelib/window/event.hpp
lucas137/eyelib
e88eaea6dd2c2e4b365d178f67869a3cd47751a5
[ "MIT" ]
null
null
null
//===========================================================================// /* MIT License Copyright (c) 2019 Nathan Lucas Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //===========================================================================// /// @file /// @brief FLTK window event. /// @author Nathan Lucas //===========================================================================// #ifndef EYLIB_WINDOW_EVENT_HPP #define EYLIB_WINDOW_EVENT_HPP #include <string> // std::string namespace eye { namespace window { /// @ingroup window /// @addtogroup event Window Events /// @{ //--------------------------------------------------------------------------- /// Event data. struct Event { // Event handler return values for FLTK static constexpr int HANDLED = 1; ///< Event was handled. static constexpr int NOT_HANDLED = 0; ///< Event was not handled. //----------------------------------------------------------- /// Key event. struct Key { /// Non-printable keys. enum class Special { unrecognized = 0x0000, ///< Unrecognized event key. button = 0xfee8, ///< Mouse button; use Fl_Button + n for button n. backspace = 0xff08, ///< Backspace key. tab = 0xff09, ///< Tab key. enter = 0xff0d, ///< Enter key. pause = 0xff13, ///< Pause key. scroll_lock = 0xff14, ///< Scroll lock key. escape = 0xff1b, ///< Escape key. home = 0xff50, ///< Home key. left = 0xff51, ///< Left arrow key. up = 0xff52, ///< Up arrow key. right = 0xff53, ///< Right arrow key. down = 0xff54, ///< Down arrow key. page_up = 0xff55, ///< Page-up key. page_down = 0xff56, ///< Page-down key. end = 0xff57, ///< End key. print = 0xff61, ///< Print (or print-screen) key. insert = 0xff63, ///< Insert key. menu = 0xff67, ///< Menu key. num_lock = 0xff7f, ///< Num lock key. keypad = 0xff80, ///< Keypad number; use FL_KP + 'n' for digit n. keypad_enter = 0xff8d, ///< Enter key on the keypad, same as Fl_KP+'\\r'. keypad_last = 0xffbd, ///< Last keypad key; use to range-check keypad. function = 0xffbd, ///< Function key; use FL_F + n for function key n. function_last = 0xffe0, ///< Last function key; use to range-check keys. shift_left = 0xffe1, ///< Lefthand shift key. shift_right = 0xffe2, ///< Righthand shift key. control_left = 0xffe3, ///< Lefthand control key. control_right = 0xffe4, ///< Righthand control key. caps_lock = 0xffe5, ///< Caps lock key. meta_left = 0xffe7, ///< Left meta/Windows key. meta_right = 0xffe8, ///< Right meta/Windows key. alt_left = 0xffe9, ///< Left alt key. alt_right = 0xffea, ///< Right alt key. delete_key = 0xffff, ///< Delete key. }; int event_code{0}; ///< Event code. int key_code{0}; ///< Valid for key events only. Key(int event_code); ///< Constructor. // Member functions ------ /// @name Key Press and Release /// @{ bool is_press() const; ///< `true` if key was pressed. bool is_release() const; ///< `true` if key was released. /// @} /// @name Inspection. /// @{ bool is_alt() const; ///< 'true' if left or right alt key. bool is_control() const; ///< 'true' if left or right control key. bool is_enter() const; ///< `true` if enter key. bool is_function() const; ///< `true` if numbered function key. bool is_meta() const; ///< 'true' if left or right meta key. bool is_numpad() const; ///< `true` if numeric keypad key. bool is_printable() const; ///< `true` if printable ASCII character. bool is_shift() const; ///< 'true' if left or right shift key. bool is_special() const; ///< `true` if printable ASCII character. /// @} /// @name Get key. /// @{ /// Return function key number, or `0` if event was not a function key. unsigned function() const; /// Return non-printable key, or Special::unrecognized. Special special() const; /// Return a string representation a key. std::string to_string() const; /// @} }; //----------------------------------------------------------- struct Mouse { /// Mouse button. enum class Button : unsigned { none = 0, left = 1, middle = 2, right = 3 }; int event_code{0}; ///< Event code. Mouse(int event_code); ///< Constructor. // Member functions ------ /// @name Mouse Button /// @{ bool is_click() const; ///< `true` if button was clicked. bool is_release() const; ///< `true` if button was released. static bool is_button_left(); ///< `true` if left button click/release. static bool is_button_middle(); ///< `true` if middle button click/release. static bool is_button_right(); ///< `true` if right button click/release. static Button button(); ///< Button that was clicked or released. static unsigned clicks(); ///< Return N-1 for N clicks. /// @} /// @name Mouse Position /// @{ bool is_drag() const; ///< `true` if moved with a button held down. bool is_move() const; ///< `true` if moved without a button held down. /// @} /// @name Mouse Scroll Wheel /// @{ bool is_scroll() const; ///< `true` if mouse scroll wheel moved. /// @} //----------------------------------------------------------- // /// @name Mouse Events // /// @{ // static constexpr int Button = 0xfee8; ///< Mouse button; use `Button` + n. // /// @} //----------------------------------------------------------- }; //----------------------------------------------------------- /// Key and mouse states during most recent event. struct State { /// Key event states. struct Key { /// @name Key event. /// @{ static bool is_key(); ///< `true` if last event was key press or release. static int key_code(); ///< Key code of last event, or `0` if no key. static bool is_press(int Key); /// `true` if pressed during last event. static bool is_press_now(int Key); /// `true` if key is held down now. /// @} /// @name Modifier keys. /// @{ static bool alt(); ///< `true` if Alt key is pressed. static bool ctrl(); ///< `true` if Ctrl key is pressed. static bool shift(); ///< `true` if Shift key is pressed. /// @} /// @name Lock keys. /// @{ static bool caps_lock(); ///< `true` if Caps Lock is on. static bool num_lock(); ///< `true` if Num Lock is on. static bool scroll_lock(); ///< `true` if Scroll Lock is on. /// @} }; /// Mouse event states. struct Mouse { /// @name Mouse buttons. /// @{ static bool button_left(); ///< `true` if left button click or release. static bool button_middle(); ///< `true` if middle button click or release. static bool button_right(); ///< `true` if right button click or release. /// @} /// @name Mouse position. /// @{ static int x_screen(); ///< Horizontal position on the screen. static int y_screen(); ///< Vertical position on the screen. static int x_window(); ///< Horizontal position relative to window. static int y_window(); ///< Vertical position relative to window. /// `true` if mouse event is inside a given rectangle. static bool is_inside(int x, int y, int w, int h); // /// `true` if mouse event is inside a given child widget. // static bool is_inside(Fl_Widget const* w); /// @} /// @name Mouse scroll. /// @{ static int scroll_dx(); ///< Horizontal scroll -- right is positive. static int scroll_dy(); ///< Vertical scroll -- down is positive. /// @} }; static std::string text(); ///< Text assocatied with event. static unsigned last_event(); ///< Return last event processed. }; //----------------------------------------------------------- // Member variables int code{0}; ///< Event code. Key key{code}; ///< Key event. Mouse mouse{code}; ///< Mouse event. std::string name{}; ///< Event name. State state{}; ///< Current event states. unsigned time_ms{0}; ///< Timestamp in milliseconds. // Constructors Event() = default; ///< Default construct event object. Event(unsigned time_ms, int code); ///< Construct event object. //----------------------------------------------------------- bool is_focus() const; ///< `true` if focus/unfocus event. bool is_key() const; ///< `true` if key was pressed or released. bool is_mouse() const; ///< `true` if mouse event occurred. }; //--------------------------------------------------------------------------- /// @} } } // eye::window #endif // EYLIB_WINDOW_EVENT_HPP //===========================================================================//
39.710526
83
0.518981
lucas137
1e03dc884a7253fb4f979fff0ade588bf574bd4b
7,292
cxx
C++
portaudio/bindings/cpp/source/portaudiocpp/System.cxx
gergocs/cpmpvoice
f438efcddf10ef3d3e0664eca5ace81367629235
[ "Apache-2.0" ]
393
2021-07-04T20:27:15.000Z
2021-09-21T10:44:47.000Z
portaudio/bindings/cpp/source/portaudiocpp/System.cxx
gergocs/cpmpvoice
f438efcddf10ef3d3e0664eca5ace81367629235
[ "Apache-2.0" ]
41
2021-07-05T17:31:57.000Z
2021-09-14T03:51:01.000Z
portaudio/bindings/cpp/source/portaudiocpp/System.cxx
gergocs/cpmpvoice
f438efcddf10ef3d3e0664eca5ace81367629235
[ "Apache-2.0" ]
32
2021-07-05T12:34:57.000Z
2021-08-15T21:18:54.000Z
#include "portaudiocpp/System.hxx" #include <cstddef> #include <cassert> #include "portaudiocpp/HostApi.hxx" #include "portaudiocpp/Device.hxx" #include "portaudiocpp/Stream.hxx" #include "portaudiocpp/Exception.hxx" #include "portaudiocpp/SystemHostApiIterator.hxx" #include "portaudiocpp/SystemDeviceIterator.hxx" namespace portaudio { // ----------------------------------------------------------------------------------- // Static members: System *System::instance_ = NULL; int System::initCount_ = 0; HostApi **System::hostApis_ = NULL; Device **System::devices_ = NULL; Device *System::nullDevice_ = NULL; // ----------------------------------------------------------------------------------- int System::version() { return Pa_GetVersion(); } const char *System::versionText() { return Pa_GetVersionText(); } void System::initialize() { ++initCount_; if (initCount_ == 1) { // Create singleton: assert(instance_ == NULL); instance_ = new System(); // Initialize the PortAudio system: { PaError err = Pa_Initialize(); if (err != paNoError) throw PaException(err); } // Create and populate device array: { int numDevices = instance().deviceCount(); devices_ = new Device*[numDevices]; for (int i = 0; i < numDevices; ++i) devices_[i] = new Device(i); } // Create and populate host api array: { int numHostApis = instance().hostApiCount(); hostApis_ = new HostApi*[numHostApis]; for (int i = 0; i < numHostApis; ++i) hostApis_[i] = new HostApi(i); } // Create null device: nullDevice_ = new Device(paNoDevice); } } void System::terminate() { PaError err = paNoError; if (initCount_ == 1) { // Destroy null device: delete nullDevice_; // Destroy host api array: { if (hostApis_ != NULL) { int numHostApis = instance().hostApiCount(); for (int i = 0; i < numHostApis; ++i) delete hostApis_[i]; delete[] hostApis_; hostApis_ = NULL; } } // Destroy device array: { if (devices_ != NULL) { int numDevices = instance().deviceCount(); for (int i = 0; i < numDevices; ++i) delete devices_[i]; delete[] devices_; devices_ = NULL; } } // Terminate the PortAudio system: assert(instance_ != NULL); err = Pa_Terminate(); // Destroy singleton: delete instance_; instance_ = NULL; } if (initCount_ > 0) --initCount_; if (err != paNoError) throw PaException(err); } System &System::instance() { assert(exists()); return *instance_; } bool System::exists() { return (instance_ != NULL); } // ----------------------------------------------------------------------------------- System::HostApiIterator System::hostApisBegin() { System::HostApiIterator tmp; tmp.ptr_ = &hostApis_[0]; // begin (first element) return tmp; } System::HostApiIterator System::hostApisEnd() { int count = hostApiCount(); System::HostApiIterator tmp; tmp.ptr_ = &hostApis_[count]; // end (one past last element) return tmp; } HostApi &System::defaultHostApi() { PaHostApiIndex defaultHostApi = Pa_GetDefaultHostApi(); if (defaultHostApi < 0) throw PaException(defaultHostApi); return *hostApis_[defaultHostApi]; } HostApi &System::hostApiByTypeId(PaHostApiTypeId type) { PaHostApiIndex index = Pa_HostApiTypeIdToHostApiIndex(type); if (index < 0) throw PaException(index); return *hostApis_[index]; } HostApi &System::hostApiByIndex(PaHostApiIndex index) { if (index < 0 || index >= hostApiCount()) throw PaException(paInternalError); return *hostApis_[index]; } int System::hostApiCount() { PaHostApiIndex count = Pa_GetHostApiCount(); if (count < 0) throw PaException(count); return count; } // ----------------------------------------------------------------------------------- System::DeviceIterator System::devicesBegin() { DeviceIterator tmp; tmp.ptr_ = &devices_[0]; return tmp; } System::DeviceIterator System::devicesEnd() { int count = deviceCount(); DeviceIterator tmp; tmp.ptr_ = &devices_[count]; return tmp; } ////// /// Returns the System's default input Device, or the null Device if none /// was available. ////// Device &System::defaultInputDevice() { PaDeviceIndex index = Pa_GetDefaultInputDevice(); return deviceByIndex(index); } ////// /// Returns the System's default output Device, or the null Device if none /// was available. ////// Device &System::defaultOutputDevice() { PaDeviceIndex index = Pa_GetDefaultOutputDevice(); return deviceByIndex(index); } ////// /// Returns the Device for the given index. /// Will throw a paInternalError equivalent PaException if the given index /// is out of range. ////// Device &System::deviceByIndex(PaDeviceIndex index) { if (index < -1 || index >= deviceCount()) { throw PaException(paInternalError); } if (index == -1) return System::instance().nullDevice(); return *devices_[index]; } int System::deviceCount() { PaDeviceIndex count = Pa_GetDeviceCount(); if (count < 0) throw PaException(count); return count; } Device &System::nullDevice() { return *nullDevice_; } // ----------------------------------------------------------------------------------- void System::sleep(long msec) { Pa_Sleep(msec); } int System::sizeOfSample(PaSampleFormat format) { PaError err = Pa_GetSampleSize(format); if (err < 0) { throw PaException(err); return 0; } return err; } // ----------------------------------------------------------------------------------- System::System() { // (left blank intentionally) } System::~System() { // (left blank intentionally) } // ----------------------------------------------------------------------------------- } // namespace portaudio
23.675325
90
0.475453
gergocs
1e0516f8ddeaf90d4434c1e03eaf9fb150c014c7
8,298
hh
C++
libsrc/pylith/fekernels/DispVel.hh
Grant-Block/pylith
f6338261b17551eba879da998a5aaf2d91f5f658
[ "MIT" ]
null
null
null
libsrc/pylith/fekernels/DispVel.hh
Grant-Block/pylith
f6338261b17551eba879da998a5aaf2d91f5f658
[ "MIT" ]
null
null
null
libsrc/pylith/fekernels/DispVel.hh
Grant-Block/pylith
f6338261b17551eba879da998a5aaf2d91f5f658
[ "MIT" ]
null
null
null
/* -*- C++ -*- * * ---------------------------------------------------------------------- * * Brad T. Aagaard, U.S. Geological Survey * Charles A. Williams, GNS Science * Matthew G. Knepley, University of Chicago * * This code was developed as part of the Computational Infrastructure * for Geodynamics (http:*geodynamics.org). * * Copyright (c) 2010-2015 University of California, Davis * * See COPYING for license information. * * ---------------------------------------------------------------------- */ /** @file libsrc/fekernels/DispVel.hh * * Kernels for time evolution equation with displacement and velocity * solution fields. * * Solution fields: [disp(dim), vel(dim, optional)] * * Auxiliary fields: [...] (not used) * * \int_V \vec{\phi}_v \cdot \left( \frac{\partial \vec{u}(t)}{\partial t} \right) \, dV = * \int_V \vec{\phi}_v \cdot \vec{v}(t) \, dV. * * LHS Residual * * f0_DispVel: \vec{f0} = \frac{\partial \vec{u}(t)}{\partial t} * * RHS Residual * * g0_DispVel: \vec{g0} = \vec{v}(t) * * LHS Jacobian * * Jf0_veldisp_DispVelImplicit: s_tshift * * Jf0_veldisp_DispVelExplicit: 0 * * RHS Jacobian * * Jg0_velvel_DispVel: +1.0 * * ====================================================================== */ #if !defined(pylith_fekernels_DispVel_hh) #define pylith_fekernels_DispVel_hh // Include directives --------------------------------------------------- #include "fekernelsfwd.hh" // forward declarations #include "pylith/utils/types.hh" class pylith::fekernels::DispVel { // PUBLIC MEMBERS /////////////////////////////////////////////////////// public: /** Kernel interface. * * @param[in] dim Spatial dimension. * @param[in] numS Number of registered subfields in solution field. * @param[in] numA Number of registered subfields in auxiliary field. * @param[in] sOff Offset of registered subfields in solution field [numS]. * @param[in] sOff_x Offset of registered subfields in gradient of the solution field [numS]. * @param[in] s Solution field with all subfields. * @param[in] s_t Time derivative of solution field. * @param[in] s_x Gradient of solution field. * @param[in] aOff Offset of registered subfields in auxiliary field [numA] * @param[in] aOff_x Offset of registered subfields in gradient of auxiliary field [numA] * @param[in] a Auxiliary field with all subfields. * @param[in] a_t Time derivative of auxiliary field. * @param[in] a_x Gradient of auxiliary field. * @param[in] t Time for residual evaluation. * @param[in] x Coordinates of point evaluation. * @param[in] numConstants Number of registered constants. * @param[in] constants Array of registered constants. * @param[out] f0 [dim]. */ /** f0 function for displacement equation: f0u = \dot{u}. * * Solution fields: [disp(dim), vel(dim)] */ static void f0u(const PylithInt dim, const PylithInt numS, const PylithInt numA, const PylithInt sOff[], const PylithInt sOff_x[], const PylithScalar s[], const PylithScalar s_t[], const PylithScalar s_x[], const PylithInt aOff[], const PylithInt aOff_x[], const PylithScalar a[], const PylithScalar a_t[], const PylithScalar a_x[], const PylithReal t, const PylithScalar x[], const PylithInt numConstants, const PylithScalar constants[], PylithScalar f0[]); /** f0 function for velocity equation: f0u = \dot{v}. * * Solution fields: [disp(dim), vel(dim)] */ static void f0v(const PylithInt dim, const PylithInt numS, const PylithInt numA, const PylithInt sOff[], const PylithInt sOff_x[], const PylithScalar s[], const PylithScalar s_t[], const PylithScalar s_x[], const PylithInt aOff[], const PylithInt aOff_x[], const PylithScalar a[], const PylithScalar a_t[], const PylithScalar a_x[], const PylithReal t, const PylithScalar x[], const PylithInt numConstants, const PylithScalar constants[], PylithScalar f0[]); /** g0 function for displacement equation: g0u = v. * * Solution fields: [disp(dim), vel(dim)] */ static void g0u(const PylithInt dim, const PylithInt numS, const PylithInt numA, const PylithInt sOff[], const PylithInt sOff_x[], const PylithScalar s[], const PylithScalar s_t[], const PylithScalar s_x[], const PylithInt aOff[], const PylithInt aOff_x[], const PylithScalar a[], const PylithScalar a_t[], const PylithScalar a_x[], const PylithReal t, const PylithScalar x[], const PylithInt numConstants, const PylithScalar constants[], PylithScalar g0[]); /** Jf0 function for displacement equation with zero values on diagonal. * * This is associated with the elasticity equation without intertia. * * Solution fields: [...] */ static void Jf0uu_zero(const PylithInt dim, const PylithInt numS, const PylithInt numA, const PylithInt sOff[], const PylithInt sOff_x[], const PylithScalar s[], const PylithScalar s_t[], const PylithScalar s_x[], const PylithInt aOff[], const PylithInt aOff_x[], const PylithScalar a[], const PylithScalar a_t[], const PylithScalar a_x[], const PylithReal t, const PylithReal s_tshift, const PylithScalar x[], const PylithInt numConstants, const PylithScalar constants[], PylithScalar Jf0[]); /** Jf0 function for displacement equation: Jf0uu = s_tshift. * * Solution fields: [disp(dim), vel(dim)] */ static void Jf0uu_stshift(const PylithInt dim, const PylithInt numS, const PylithInt numA, const PylithInt sOff[], const PylithInt sOff_x[], const PylithScalar s[], const PylithScalar s_t[], const PylithScalar s_x[], const PylithInt aOff[], const PylithInt aOff_x[], const PylithScalar a[], const PylithScalar a_t[], const PylithScalar a_x[], const PylithReal t, const PylithReal s_tshift, const PylithScalar x[], const PylithInt numConstants, const PylithScalar constants[], PylithScalar Jf0[]); /** Jg0 function for displacement equation: 1.0. * * Solution fields: [disp(dim), vel(dim)] */ static void Jg0uv(const PylithInt dim, const PylithInt numS, const PylithInt numA, const PylithInt sOff[], const PylithInt sOff_x[], const PylithScalar s[], const PylithScalar s_t[], const PylithScalar s_x[], const PylithInt aOff[], const PylithInt aOff_x[], const PylithScalar a[], const PylithScalar a_t[], const PylithScalar a_x[], const PylithReal t, const PylithReal s_tshift, const PylithScalar x[], const PylithInt numConstants, const PylithScalar constants[], PylithScalar Jg0[]); }; // DispVel #endif /* pylith_fekernels_DispVel_hh */ /* End of file */
33.595142
97
0.532056
Grant-Block
1e094e2118b8258d7b7588c3de488b00eea31286
248
cc
C++
tests/day12_tests.cc
LesnyRumcajs/advent-of-cpp-2015
3301f31fdcca3aeddae6691ce15b0eb712a7c867
[ "MIT" ]
null
null
null
tests/day12_tests.cc
LesnyRumcajs/advent-of-cpp-2015
3301f31fdcca3aeddae6691ce15b0eb712a7c867
[ "MIT" ]
null
null
null
tests/day12_tests.cc
LesnyRumcajs/advent-of-cpp-2015
3301f31fdcca3aeddae6691ce15b0eb712a7c867
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include "../src/day12.h" TEST_CASE("Day12::part1", "[]") { REQUIRE(6 == day12::sumAllNumbers("{\"a\":2,\"b\":4}")); REQUIRE(3 == day12::sumAllNumbers("{\"a\":{\"b\":4},\"c\":-1}")); }
27.555556
69
0.564516
LesnyRumcajs
1f6117402c993c00fa7ca45af41be702e691c75e
6,080
cpp
C++
examples/promps_hsmm_ball_viterbi.cpp
DiegoAE/BOSD
a7ce88462c64c540ba2922d16eb6f7eba8055b47
[ "MIT" ]
19
2019-05-03T05:31:43.000Z
2022-01-08T18:14:31.000Z
examples/promps_hsmm_ball_viterbi.cpp
DiegoAE/BOSD
a7ce88462c64c540ba2922d16eb6f7eba8055b47
[ "MIT" ]
2
2019-02-14T15:29:34.000Z
2020-06-04T10:14:54.000Z
examples/promps_hsmm_ball_viterbi.cpp
DiegoAE/BOSD
a7ce88462c64c540ba2922d16eb6f7eba8055b47
[ "MIT" ]
1
2019-07-01T07:44:09.000Z
2019-07-01T07:44:09.000Z
#include <armadillo> #include <boost/program_options.hpp> #include <HSMM.hpp> #include <json.hpp> #include <ProMPs_emission.hpp> using namespace arma; using namespace hsmm; using namespace robotics; using namespace std; using json = nlohmann::json; namespace po = boost::program_options; field<mat> fromMatToField(const mat& obs) { field<mat> ret(obs.n_cols); for(int i = 0; i < obs.n_cols; i++) ret(i) = obs.col(i); return ret; } // Running the Viterbi algorithm. void ViterbiAlgorithm(HSMM& promp_hsmm, const field<field<mat>>& seq_obs, string filename) { int nseq = seq_obs.n_elem; for(int s = 0; s < nseq; s++) { const field<mat>& obs = seq_obs(s); int nstates = promp_hsmm.nstates_; int nobs = obs.n_elem; imat psi_duration(nstates, nobs, fill::zeros); imat psi_state(nstates, nobs, fill::zeros); mat delta(nstates, nobs, fill::zeros); cout << "Before pdf" << endl; cube log_pdf = promp_hsmm.computeEmissionsLogLikelihood(obs); cout << "After pdf" << endl; Viterbi(promp_hsmm.transition_, promp_hsmm.pi_, promp_hsmm.duration_, log_pdf, delta, psi_duration, psi_state, promp_hsmm.min_duration_, nobs); cout << "Delta last column" << endl; cout << delta.col(nobs - 1) << endl; ivec viterbiStates, viterbiDurations; viterbiPath(psi_duration, psi_state, delta, viterbiStates, viterbiDurations); cout << "Viterbi states and durations" << endl; imat states_and_durations = join_horiz(viterbiStates, viterbiDurations); cout << states_and_durations << endl; cout << "Python states list representation" << endl; cout << "["; for(int i = 0; i < viterbiStates.n_elem; i++) cout << viterbiStates[i] << ((i + 1 == viterbiStates.n_elem)? "]" : ","); cout << endl; cout << "Python duration list representation" << endl; cout << "["; for(int i = 0; i < viterbiDurations.n_elem; i++) cout << viterbiDurations[i] << ((i + 1 == viterbiDurations.n_elem)? "]" : ","); cout << endl; // Saving the matrix of joint states and durations. string viterbi_filename(filename); if (nseq > 1) viterbi_filename += string(".") + to_string(s); states_and_durations.save(viterbi_filename, raw_ascii); } } int main(int argc, char *argv[]) { po::options_description desc("Options"); desc.add_options() ("help,h", "Produce help message") ("input,i", po::value<string>(), "Path to the input obs") ("params,p", po::value<string>(), "Path to the json input params") ("output,o", po::value<string>(), "Path to the output viterbi file(s)") ("polybasisfun", po::value<int>()->default_value(1), "Order of the " "poly basis functions") ("norbf", "Flag to deactivate the radial basis functions") ("nsequences,n", po::value<int>()->default_value(1), "Number of sequences used for training"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { cout << desc << endl; return 0; } if (!vm.count("input") || !vm.count("output") || !vm.count("params")) { cerr << "Error: You should provide input and output files" << endl; return 1; } string input_filename = vm["input"].as<string>(); string output_filename = vm["output"].as<string>(); string params = vm["params"].as<string>(); int nseq = vm["nsequences"].as<int>(); field<field<mat>> seq_obs(nseq); int njoints; for(int i = 0; i < nseq; i++) { string name = input_filename; if (nseq != 1) name += string(".") + to_string(i); mat obs; obs.load(name, raw_ascii); ifstream input_params_file(params); json input_params; input_params_file >> input_params; njoints = obs.n_rows; int nobs = obs.n_cols; cout << "Time series shape: (" << njoints << ", " << nobs << ")." << endl; seq_obs(i) = fromMatToField(obs); } ifstream input_params_file(params); json input_params; input_params_file >> input_params; int min_duration = input_params["min_duration"]; int nstates = input_params["nstates"]; int ndurations = input_params["ndurations"]; mat transition(nstates, nstates); transition.fill(1.0 / (nstates - 1)); transition.diag().zeros(); // No self-transitions. vec pi(nstates); pi.fill(1.0/nstates); mat durations(nstates, ndurations); durations.fill(1.0 / ndurations); // Setting a combination of polynomial and rbf basis functions. auto rbf = shared_ptr<ScalarGaussBasis>(new ScalarGaussBasis( {0.25,0.5,0.75},0.25)); auto poly = make_shared<ScalarPolyBasis>(vm["polybasisfun"].as<int>()); auto comb = shared_ptr<ScalarCombBasis>(new ScalarCombBasis({rbf, poly})); if (vm.count("norbf")) comb = shared_ptr<ScalarCombBasis>(new ScalarCombBasis({poly})); int n_basis_functions = comb->dim(); // Instantiating as many ProMPs as hidden states. vector<FullProMP> promps; for(int i = 0; i < nstates; i++) { vec mu_w(n_basis_functions * njoints); mu_w.randn(); mat Sigma_w = eye<mat>(n_basis_functions * njoints, n_basis_functions * njoints); mat Sigma_y = 0.01*eye<mat>(njoints, njoints); ProMP promp(mu_w, Sigma_w, Sigma_y); FullProMP poly(comb, promp, njoints); promps.push_back(poly); } // Creating the ProMP emission and parsing the model parameters as json. shared_ptr<AbstractEmission> ptr_emission(new ProMPsEmission(promps)); HSMM promp_hsmm(ptr_emission, transition, pi, durations, min_duration); promp_hsmm.from_stream(input_params); ViterbiAlgorithm(promp_hsmm, seq_obs, output_filename); return 0; }
38.974359
82
0.611678
DiegoAE
1f6b282c287f4b512b2321af5a36faa2bb891294
9,097
cpp
C++
DrunkEngine/GameObject.cpp
MarcFly/Fly3D-Engine
e8da09a63c7c3d991b8f25c346798ee230593e78
[ "Unlicense" ]
null
null
null
DrunkEngine/GameObject.cpp
MarcFly/Fly3D-Engine
e8da09a63c7c3d991b8f25c346798ee230593e78
[ "Unlicense" ]
3
2018-09-27T17:00:14.000Z
2018-12-19T13:30:25.000Z
DrunkEngine/GameObject.cpp
MarcFly/Fly3D-Engine
e8da09a63c7c3d991b8f25c346798ee230593e78
[ "Unlicense" ]
null
null
null
#include "GameObject.h" #include "Application.h" #include "ComponentMaterial.h" #include "ComponentMesh.h" #include "ComponentCamera.h" #include "ResourceMesh.h" #include "ComponentBillboard.h" #include "ComponentSkeleton.h" #include "ComponentAnimation.h" // Creation of Root Node from a file GameObject::GameObject() { GetTransform(); App->gameObj->objects_in_scene.push_back(this); App->gameObj->non_static_objects_in_scene.push_back(this); Start(); UUID = GetUUID(); } GameObject::GameObject(const char* name, GameObject * par) { this->name = name; this->root = this; if (par != nullptr) { this->parent = par; root = par->root; } GetTransform(); App->gameObj->objects_in_scene.push_back(this); App->gameObj->non_static_objects_in_scene.push_back(this); UUID = GetUUID(); Start(); } void GameObject::Start() { for (int i = 0; i < this->components.size(); i++) this->components[i]->Start(); for (int i = 0; i < this->children.size(); i++) this->children[i]->Start(); } void GameObject::Update(float dt) { for (int i = 0; i < this->components.size(); i++) { if (this->components[i]->active) { this->components[i]->Update(dt); } } for (int i = 0; i < this->children.size(); i++) { if(this->children[i]->active) { this->children[i]->Update(dt); } } Draw(); } void GameObject::Draw() { for (int i = 0; i < this->components.size(); i++) { if (this->components[i]->active) { this->components[i]->Draw(); } } if (this->BoundingBox != nullptr && (App->renderer3D->bounding_box || this->sv_active)) this->DrawBB(); } void GameObject::DrawBB() const { glDisable(GL_LIGHTING); glBegin(GL_LINES); glColor3f(0.f, 1.f, 0.f); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->minPoint.z); glColor3f(0, 1, 0); glEnd(); if (App->renderer3D->lighting) glEnable(GL_LIGHTING); } vec GameObject::getObjectCenter() { if (BoundingBox != nullptr) { float aux_x = (BoundingBox->maxPoint.x + BoundingBox->minPoint.x) / 2; float aux_y = (BoundingBox->maxPoint.y + BoundingBox->minPoint.y) / 2; float aux_z = (BoundingBox->maxPoint.z + BoundingBox->minPoint.z) / 2; return vec(aux_x, aux_y, aux_z); } return vec(0, 0, 0); } void GameObject::OrderChildren() { for (int i = 0; i < this->children.size(); i++) { if (this->children[i]->par_UUID != UINT_FAST32_MAX && this->children[i]->par_UUID != this->children[i]->parent->UUID) { GameObject* obj = this->children[i]; this->children[i]->to_pop = true; this->AdjustObjects(); obj->to_pop = false; GameObject* get = this->GetChild(obj->par_UUID); obj->parent = get; if (get != nullptr) get->children.push_back(obj); i--; } } } void GameObject::AdjustObjects() { int i = 0; for (; i < this->children.size(); i++) { if (this->children[i]->to_pop == true) { //delete this->children[i]; //this->children[i] = nullptr; break; } } for (int j = i; j < this->children.size() - 1; j++) { this->children[j] = this->children[j + 1]; } this->children.pop_back(); } void GameObject::AdjustComponents() { int i = 0; for (; i < this->components.size(); i++) { if (this->components[i]->to_pop == true) { delete this->components[i]; this->components[i] = nullptr; break; } } for (int j = i; j < this->components.size() - 1; j++) { this->components[j] = this->components[j + 1]; } this->components.pop_back(); } void GameObject::RecursiveSetStatic(GameObject * obj, const bool bool_static) { obj->is_static = bool_static; for (int i = 0; i < obj->children.size(); i++) RecursiveSetStatic(obj->children[i], bool_static); } void GameObject::CleanUp() { for (int i = 0; i < this->components.size(); i++) { this->components[i]->CleanUp(); delete this->components[i]; this->components[i] = nullptr; } this->components.clear(); if (this->BoundingBox != nullptr) { delete this->BoundingBox; this->BoundingBox = nullptr; } for (int i = 0; i < this->children.size(); i++) this->children[i]->CleanUp(); this->children.clear(); this->parent = nullptr; this->root = nullptr; this->name.clear(); } void GameObject::DestroyThisObject() { this->CleanUp(); this->to_pop = true; if (parent != nullptr) parent->AdjustObjects(); } void GameObject::DestroyComponent() { } void GameObject::RecursiveSetNewUUID() { if (this->parent == nullptr) par_UUID = UINT_FAST32_MAX; else par_UUID = parent->UUID; UUID = GetUUID(); for (int i = 0; i < children.size(); i++) children[i]->RecursiveSetNewUUID(); } void GameObject::Load(const JSON_Value* go, const char* file) { bool ret = true; } void GameObject::Save(JSON_Array* go) { JSON_Value* append = json_value_init_object(); JSON_Object* curr = json_value_get_object(append); std::string obj = "gameobject."; std::string set_val; set_val = obj + "UUID"; json_object_dotset_number(curr, set_val.c_str(), UUID); set_val = obj + "par_UUID"; json_object_dotset_number(curr, set_val.c_str(), par_UUID); set_val = obj + "name"; json_object_dotset_string(curr, set_val.c_str(), name.c_str()); JSON_Value* set_array = json_value_init_array(); JSON_Array* comps = json_value_get_array(set_array); for (int i = 0; i < this->components.size(); i++) this->components[i]->Save(comps); set_val = obj + "components"; json_object_dotset_value(curr,set_val.c_str(), set_array); json_array_append_value(go, append); for(int i = 0; i < this->children.size(); i++) this->children[i]->Save(go); } std::vector<uint> GameObject::GetMeshProps() { uint ret[2] = { 0,0 }; std::vector<Component*> meshes; meshes = GetComponents(CT_Mesh); for (int i = 0; i < meshes.size(); i++) { ComponentMesh* aux = meshes[i]->AsMesh(); ret[0] += aux->r_mesh->num_vertex; ret[1] += aux->r_mesh->num_faces; } for (int i = 0; i < children.size(); i++) { std::vector<uint> child = children[i]->GetMeshProps(); ret[0] += child[0]; ret[1] += child[1]; } std::vector<uint> ret_v; ret_v.push_back(ret[0]); ret_v.push_back(ret[1]); return ret_v; } Component* GameObject::NewComponent(const CTypes type) { if (type == CT_Mesh) return new ComponentMesh(this); else if (type == CT_Material) return new ComponentMaterial(this); else if (type == CT_Camera) return new ComponentCamera(this); else if (type == CT_Transform) return new ComponentTransform(this); /*else if (type == CT_Billboard) return new ComponentBillboard(this);*/ else if (type == CT_Skeleton) return new ComponentSkeleton(this); else if (type == CT_Animation) return new ComponentAnimation(this); return nullptr; }
25.410615
119
0.68616
MarcFly
1f6d36c2e537f1d9ec41d98de0578c5e6520cc65
321
cpp
C++
src/ResLoader/data_mgr.cpp
wu1274704958/vulkan_demo
545e00a1fae98e0ff179115887dfa7669b56ccde
[ "MIT" ]
null
null
null
src/ResLoader/data_mgr.cpp
wu1274704958/vulkan_demo
545e00a1fae98e0ff179115887dfa7669b56ccde
[ "MIT" ]
null
null
null
src/ResLoader/data_mgr.cpp
wu1274704958/vulkan_demo
545e00a1fae98e0ff179115887dfa7669b56ccde
[ "MIT" ]
1
2021-12-27T08:40:07.000Z
2021-12-27T08:40:07.000Z
#include <data_mgr.hpp> #include <resource_mgr.hpp> #include <log.hpp> #include <sundry.hpp> #include <serialization.hpp> #include <assimp/scene.h> #include <fileop.hpp> using namespace dbg::literal; //---------------------------------------------------------------------------------------------------------------------
29.181818
119
0.470405
wu1274704958
1f7b0bfdd5712791868cee25dc91ae687f6177ed
5,023
cpp
C++
testing_environmen/testing_environmen/src/shadows/shadow.cpp
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
null
null
null
testing_environmen/testing_environmen/src/shadows/shadow.cpp
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
4
2018-12-24T11:16:53.000Z
2018-12-24T11:20:29.000Z
testing_environmen/testing_environmen/src/shadows/shadow.cpp
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
null
null
null
/*#include "shadow.h" auto shadow_handler::get_projection(void) -> glm::mat4 & { return projection_matrix; } auto shadow_handler::get_depth_map(void) -> texture & { return depth_map; } auto shadow_handler::get_fbo(void) -> framebuffer & { return depth_fbo; } auto shadow_handler::get_shaders(void) -> program & { return shaders; } auto shadow_handler::get_light_view(void) -> glm::mat4 & { return light_view_matrix; } auto shadow_handler::get_shadow_bias(void) -> glm::mat4 & { return shadow_bias; } auto shadow_handler::create(glm::vec3 const & light_pos) -> void { create_fbo(); create_shaders(); create_shadow_bias_matrix(); create_light_view_matrix(glm::normalize(glm::vec3(light_pos.x, -light_pos.y, light_pos.z))); } auto shadow_handler::update(f32 far, f32 near, f32 aspect, f32 fov, glm::vec3 const & pos, glm::vec3 const & dir) -> void { std::array<glm::vec4, 8> corners; calculate_frustum_dimensions(far, near, aspect, fov); calculate_ortho_corners(pos, dir, far, near, corners); find_min_max_values(corners); projection_matrix = glm::ortho<f32>(x_min, x_max, y_min, y_max, z_min, z_max); } auto shadow_handler::update_light_view(glm::vec3 const & light_pos) -> void { create_light_view_matrix(glm::normalize(glm::vec3(light_pos.x, -light_pos.y, light_pos.z))); } auto shadow_handler::calculate_frustum_dimensions(f32 far, f32 near, f32 aspect, f32 fov) -> void { far_width = 2.0f * far * tan(glm::radians(fov)); near_width = 2.0f * near * tan(glm::radians(fov)); far_height = far_width / aspect; near_height = near_width / aspect; } auto shadow_handler::calculate_ortho_corners(glm::vec3 const & pos, glm::vec3 const & dir, f32 far, f32 near, std::array<glm::vec4, 8> & corners) -> void { glm::vec3 right_view = glm::normalize(glm::cross(dir, detail::up)); glm::vec3 up_view = glm::normalize(glm::cross(dir, right_view)); f32 far_width_half = far_width / 2.0f; f32 near_width_half = near_width / 2.0f; f32 far_height_half = far_height / 2.0f; f32 near_height_half = near_height / 2.0f; corners[flt] = light_view_matrix * glm::vec4(pos + dir * far - right_view * far_width_half + up_view * far_height_half, 1.0f); corners[flb] = light_view_matrix * glm::vec4(pos + dir * far - right_view * far_width_half - up_view * far_height_half, 1.0f); corners[frt] = light_view_matrix * glm::vec4(pos + dir * far + right_view * far_width_half + up_view * far_height_half, 1.0f); corners[frb] = light_view_matrix * glm::vec4(pos + dir * far + right_view * far_width_half - up_view * far_height_half, 1.0f); corners[nlt] = light_view_matrix * glm::vec4(pos + dir * near - right_view * near_width_half + up_view * near_height_half, 1.0f); corners[nlb] = light_view_matrix * glm::vec4(pos + dir * near - right_view * near_width_half - up_view * near_height_half, 1.0f); corners[nrt] = light_view_matrix * glm::vec4(pos + dir * near + right_view * near_width_half + up_view * near_height_half, 1.0f); corners[nrb] = light_view_matrix * glm::vec4(pos + dir * near + right_view * near_width_half - up_view * near_height_half, 1.0f); } auto shadow_handler::find_min_max_values(std::array<glm::vec4, 8> & corners) -> void { x_min = x_max = corners[0].x; y_min = y_max = corners[0].y; z_min = z_max = corners[0].z; for (u32 i = 1; i < 8; ++i) { if (x_min > corners[i].x) x_min = corners[i].x; if (x_max < corners[i].x) x_max = corners[i].x; if (y_min > corners[i].y) y_min = corners[i].y; if (y_max < corners[i].y) y_max = corners[i].y; if (z_min > corners[i].z) z_min = corners[i].z; if (z_max < corners[i].z) z_max = corners[i].z; } } auto shadow_handler::create_fbo(void) -> void { depth_fbo.create(shadow_map_size, shadow_map_size); depth_fbo.bind(); create_depth_texture(); depth_fbo.attach(depth_map, GL_DEPTH_ATTACHMENT, 0); depth_fbo.select_color_buffer(GL_NONE); } auto shadow_handler::create_depth_texture(void) -> void { depth_map.create(); depth_map.bind(GL_TEXTURE_2D); depth_map.fill(GL_TEXTURE_2D, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr, shadow_map_size, shadow_map_size); depth_map.int_param(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); depth_map.int_param(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); depth_map.int_param(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); depth_map.int_param(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } auto shadow_handler::create_shaders(void) -> void { shaders.create_shader(GL_VERTEX_SHADER, "shadow/shadow_vsh.shader"); shaders.create_shader(GL_FRAGMENT_SHADER, "shadow/shadow_fsh.shader"); shaders.link_shaders("vertex_position"); shaders.get_uniform_locations("vp", "model"); } auto shadow_handler::create_light_view_matrix(glm::vec3 const & light_dir) -> void { light_view_matrix = glm::lookAt(glm::normalize(-light_dir), glm::vec3(0), detail::up); } auto shadow_handler::create_shadow_bias_matrix(void) -> void { shadow_bias = glm::mat4 ( 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0 ); }*/
39.865079
153
0.724069
llGuy