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
eb3c5ade1f7ba50efaa0e32632d449bb834bca13
20,526
cpp
C++
Source/Plugins/UIPlugins/QtPlugin/source/propertybrowser/moc_qtvariantproperty.cpp
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/Plugins/UIPlugins/QtPlugin/source/propertybrowser/moc_qtvariantproperty.cpp
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/Plugins/UIPlugins/QtPlugin/source/propertybrowser/moc_qtvariantproperty.cpp
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/**************************************************************************** ** Meta object code from reading C++ file 'qtvariantproperty.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "qtvariantproperty.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'qtvariantproperty.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.7.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_QtVariantPropertyManager_t { QByteArrayData data[26]; char stringdata0[418]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_QtVariantPropertyManager_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_QtVariantPropertyManager_t qt_meta_stringdata_QtVariantPropertyManager = { { QT_MOC_LITERAL(0, 0, 24), // "QtVariantPropertyManager" QT_MOC_LITERAL(1, 25, 12), // "valueChanged" QT_MOC_LITERAL(2, 38, 0), // "" QT_MOC_LITERAL(3, 39, 11), // "QtProperty*" QT_MOC_LITERAL(4, 51, 8), // "property" QT_MOC_LITERAL(5, 60, 3), // "val" QT_MOC_LITERAL(6, 64, 16), // "attributeChanged" QT_MOC_LITERAL(7, 81, 9), // "attribute" QT_MOC_LITERAL(8, 91, 8), // "setValue" QT_MOC_LITERAL(9, 100, 12), // "setAttribute" QT_MOC_LITERAL(10, 113, 5), // "value" QT_MOC_LITERAL(11, 119, 16), // "slotValueChanged" QT_MOC_LITERAL(12, 136, 16), // "slotRangeChanged" QT_MOC_LITERAL(13, 153, 21), // "slotSingleStepChanged" QT_MOC_LITERAL(14, 175, 19), // "slotDecimalsChanged" QT_MOC_LITERAL(15, 195, 17), // "slotRegExpChanged" QT_MOC_LITERAL(16, 213, 19), // "slotEchoModeChanged" QT_MOC_LITERAL(17, 233, 21), // "slotConstraintChanged" QT_MOC_LITERAL(18, 255, 20), // "slotEnumNamesChanged" QT_MOC_LITERAL(19, 276, 20), // "slotEnumIconsChanged" QT_MOC_LITERAL(20, 297, 15), // "QMap<int,QIcon>" QT_MOC_LITERAL(21, 313, 20), // "slotFlagNamesChanged" QT_MOC_LITERAL(22, 334, 19), // "slotReadOnlyChanged" QT_MOC_LITERAL(23, 354, 22), // "slotTextVisibleChanged" QT_MOC_LITERAL(24, 377, 20), // "slotPropertyInserted" QT_MOC_LITERAL(25, 398, 19) // "slotPropertyRemoved" }, "QtVariantPropertyManager\0valueChanged\0" "\0QtProperty*\0property\0val\0attributeChanged\0" "attribute\0setValue\0setAttribute\0value\0" "slotValueChanged\0slotRangeChanged\0" "slotSingleStepChanged\0slotDecimalsChanged\0" "slotRegExpChanged\0slotEchoModeChanged\0" "slotConstraintChanged\0slotEnumNamesChanged\0" "slotEnumIconsChanged\0QMap<int,QIcon>\0" "slotFlagNamesChanged\0slotReadOnlyChanged\0" "slotTextVisibleChanged\0slotPropertyInserted\0" "slotPropertyRemoved" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_QtVariantPropertyManager[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 43, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 2, // signalCount // signals: name, argc, parameters, tag, flags 1, 2, 229, 2, 0x06 /* Public */, 6, 3, 234, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 8, 2, 241, 2, 0x0a /* Public */, 9, 3, 246, 2, 0x0a /* Public */, 11, 2, 253, 2, 0x08 /* Private */, 12, 3, 258, 2, 0x08 /* Private */, 13, 2, 265, 2, 0x08 /* Private */, 11, 2, 270, 2, 0x08 /* Private */, 12, 3, 275, 2, 0x08 /* Private */, 13, 2, 282, 2, 0x08 /* Private */, 14, 2, 287, 2, 0x08 /* Private */, 11, 2, 292, 2, 0x08 /* Private */, 11, 2, 297, 2, 0x08 /* Private */, 15, 2, 302, 2, 0x08 /* Private */, 16, 2, 307, 2, 0x08 /* Private */, 11, 2, 312, 2, 0x08 /* Private */, 12, 3, 317, 2, 0x08 /* Private */, 11, 2, 324, 2, 0x08 /* Private */, 11, 2, 329, 2, 0x08 /* Private */, 11, 2, 334, 2, 0x08 /* Private */, 11, 2, 339, 2, 0x08 /* Private */, 11, 2, 344, 2, 0x08 /* Private */, 11, 2, 349, 2, 0x08 /* Private */, 11, 2, 354, 2, 0x08 /* Private */, 11, 2, 359, 2, 0x08 /* Private */, 12, 3, 364, 2, 0x08 /* Private */, 11, 2, 371, 2, 0x08 /* Private */, 12, 3, 376, 2, 0x08 /* Private */, 11, 2, 383, 2, 0x08 /* Private */, 17, 2, 388, 2, 0x08 /* Private */, 11, 2, 393, 2, 0x08 /* Private */, 17, 2, 398, 2, 0x08 /* Private */, 11, 2, 403, 2, 0x08 /* Private */, 18, 2, 408, 2, 0x08 /* Private */, 19, 2, 413, 2, 0x08 /* Private */, 11, 2, 418, 2, 0x08 /* Private */, 11, 2, 423, 2, 0x08 /* Private */, 11, 2, 428, 2, 0x08 /* Private */, 21, 2, 433, 2, 0x08 /* Private */, 22, 2, 438, 2, 0x08 /* Private */, 23, 2, 443, 2, 0x08 /* Private */, 24, 3, 448, 2, 0x08 /* Private */, 25, 2, 455, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, 0x80000000 | 3, QMetaType::QVariant, 4, 5, QMetaType::Void, 0x80000000 | 3, QMetaType::QString, QMetaType::QVariant, 4, 7, 5, // slots: parameters QMetaType::Void, 0x80000000 | 3, QMetaType::QVariant, 4, 5, QMetaType::Void, 0x80000000 | 3, QMetaType::QString, QMetaType::QVariant, 4, 7, 10, QMetaType::Void, 0x80000000 | 3, QMetaType::Int, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::Int, QMetaType::Int, 2, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::Int, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::Double, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::Double, QMetaType::Double, 2, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::Double, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::Int, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::Bool, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QString, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QRegExp, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::Int, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QDate, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QDate, QMetaType::QDate, 2, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QTime, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QDateTime, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QKeySequence, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QChar, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QLocale, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QPoint, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QPointF, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QSize, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QSize, QMetaType::QSize, 2, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QSizeF, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QSizeF, QMetaType::QSizeF, 2, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QRect, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QRect, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QRectF, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QRectF, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QColor, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QStringList, 2, 2, QMetaType::Void, 0x80000000 | 3, 0x80000000 | 20, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QSizePolicy, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QFont, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QCursor, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::QStringList, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::Bool, 2, 2, QMetaType::Void, 0x80000000 | 3, QMetaType::Bool, 2, 2, QMetaType::Void, 0x80000000 | 3, 0x80000000 | 3, 0x80000000 | 3, 2, 2, 2, QMetaType::Void, 0x80000000 | 3, 0x80000000 | 3, 2, 2, 0 // eod }; void QtVariantPropertyManager::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { QtVariantPropertyManager *_t = static_cast<QtVariantPropertyManager *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->valueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QVariant(*)>(_a[2]))); break; case 1: _t->attributeChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2])),(*reinterpret_cast< const QVariant(*)>(_a[3]))); break; case 2: _t->setValue((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QVariant(*)>(_a[2]))); break; case 3: _t->setAttribute((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2])),(*reinterpret_cast< const QVariant(*)>(_a[3]))); break; case 4: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 5: _t->d_func()->slotRangeChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break; case 6: _t->d_func()->slotSingleStepChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 7: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< double(*)>(_a[2]))); break; case 8: _t->d_func()->slotRangeChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< double(*)>(_a[2])),(*reinterpret_cast< double(*)>(_a[3]))); break; case 9: _t->d_func()->slotSingleStepChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< double(*)>(_a[2]))); break; case 10: _t->d_func()->slotDecimalsChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 11: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break; case 12: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; case 13: _t->d_func()->slotRegExpChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QRegExp(*)>(_a[2]))); break; case 14: _t->d_func()->slotEchoModeChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 15: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QDate(*)>(_a[2]))); break; case 16: _t->d_func()->slotRangeChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QDate(*)>(_a[2])),(*reinterpret_cast< const QDate(*)>(_a[3]))); break; case 17: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QTime(*)>(_a[2]))); break; case 18: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QDateTime(*)>(_a[2]))); break; case 19: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QKeySequence(*)>(_a[2]))); break; case 20: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QChar(*)>(_a[2]))); break; case 21: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QLocale(*)>(_a[2]))); break; case 22: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QPoint(*)>(_a[2]))); break; case 23: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QPointF(*)>(_a[2]))); break; case 24: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QSize(*)>(_a[2]))); break; case 25: _t->d_func()->slotRangeChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QSize(*)>(_a[2])),(*reinterpret_cast< const QSize(*)>(_a[3]))); break; case 26: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QSizeF(*)>(_a[2]))); break; case 27: _t->d_func()->slotRangeChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QSizeF(*)>(_a[2])),(*reinterpret_cast< const QSizeF(*)>(_a[3]))); break; case 28: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QRect(*)>(_a[2]))); break; case 29: _t->d_func()->slotConstraintChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QRect(*)>(_a[2]))); break; case 30: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QRectF(*)>(_a[2]))); break; case 31: _t->d_func()->slotConstraintChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QRectF(*)>(_a[2]))); break; case 32: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QColor(*)>(_a[2]))); break; case 33: _t->d_func()->slotEnumNamesChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QStringList(*)>(_a[2]))); break; case 34: _t->d_func()->slotEnumIconsChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QMap<int,QIcon>(*)>(_a[2]))); break; case 35: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QSizePolicy(*)>(_a[2]))); break; case 36: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QFont(*)>(_a[2]))); break; case 37: _t->d_func()->slotValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QCursor(*)>(_a[2]))); break; case 38: _t->d_func()->slotFlagNamesChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QStringList(*)>(_a[2]))); break; case 39: _t->d_func()->slotReadOnlyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break; case 40: _t->d_func()->slotTextVisibleChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break; case 41: _t->d_func()->slotPropertyInserted((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< QtProperty*(*)>(_a[2])),(*reinterpret_cast< QtProperty*(*)>(_a[3]))); break; case 42: _t->d_func()->slotPropertyRemoved((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< QtProperty*(*)>(_a[2]))); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (QtVariantPropertyManager::*_t)(QtProperty * , const QVariant & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QtVariantPropertyManager::valueChanged)) { *result = 0; return; } } { typedef void (QtVariantPropertyManager::*_t)(QtProperty * , const QString & , const QVariant & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QtVariantPropertyManager::attributeChanged)) { *result = 1; return; } } } } const QMetaObject QtVariantPropertyManager::staticMetaObject = { { &QtAbstractPropertyManager::staticMetaObject, qt_meta_stringdata_QtVariantPropertyManager.data, qt_meta_data_QtVariantPropertyManager, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *QtVariantPropertyManager::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *QtVariantPropertyManager::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_QtVariantPropertyManager.stringdata0)) return static_cast<void*>(const_cast< QtVariantPropertyManager*>(this)); return QtAbstractPropertyManager::qt_metacast(_clname); } int QtVariantPropertyManager::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QtAbstractPropertyManager::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 43) qt_static_metacall(this, _c, _id, _a); _id -= 43; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 43) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 43; } return _id; } // SIGNAL 0 void QtVariantPropertyManager::valueChanged(QtProperty * _t1, const QVariant & _t2) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void QtVariantPropertyManager::attributeChanged(QtProperty * _t1, const QString & _t2, const QVariant & _t3) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } struct qt_meta_stringdata_QtVariantEditorFactory_t { QByteArrayData data[1]; char stringdata0[23]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_QtVariantEditorFactory_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_QtVariantEditorFactory_t qt_meta_stringdata_QtVariantEditorFactory = { { QT_MOC_LITERAL(0, 0, 22) // "QtVariantEditorFactory" }, "QtVariantEditorFactory" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_QtVariantEditorFactory[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; void QtVariantEditorFactory::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } const QMetaObject QtVariantEditorFactory::staticMetaObject = { { &QtAbstractEditorFactory<QtVariantPropertyManager>::staticMetaObject, qt_meta_stringdata_QtVariantEditorFactory.data, qt_meta_data_QtVariantEditorFactory, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *QtVariantEditorFactory::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *QtVariantEditorFactory::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_QtVariantEditorFactory.stringdata0)) return static_cast<void*>(const_cast< QtVariantEditorFactory*>(this)); return QtAbstractEditorFactory<QtVariantPropertyManager>::qt_metacast(_clname); } int QtVariantEditorFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QtAbstractEditorFactory<QtVariantPropertyManager>::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
55.029491
199
0.625743
OscarGame
eb3e12a28cc12e2f2d4af3f2ee4bc06ecb0e15b4
480
hpp
C++
optionals/medical/configs/weapons/Bandages.hpp
Task-Force-Dagger/Dagger
56b9ffe3387f74830419a987eed5a0f386674331
[ "MIT" ]
null
null
null
optionals/medical/configs/weapons/Bandages.hpp
Task-Force-Dagger/Dagger
56b9ffe3387f74830419a987eed5a0f386674331
[ "MIT" ]
null
null
null
optionals/medical/configs/weapons/Bandages.hpp
Task-Force-Dagger/Dagger
56b9ffe3387f74830419a987eed5a0f386674331
[ "MIT" ]
null
null
null
// class ACE_fieldDressing: ACE_ItemCore { // scope=2; // picture="\z\tfd\addons\media\images\icon\IB.paa"; // // displayName="Israeli Bandage"; // descriptionShort="Quickly stanches haemorrhaging from injuries"; // descriptionUse="Quickly stanches haemorrhaging from injuries"; // }; // class ACE_quikclot: ACE_ItemCore { // scope=2; // // displayName="Quikclot Combat Gauze"; // picture="\z\tfd\addons\media\images\icon\Quikclot.paa"; // };
34.285714
71
0.666667
Task-Force-Dagger
eb3e3af860c226182e04657b9520203b56f4e782
6,959
cpp
C++
All Project/Project_08.cpp
jaibae21/CPE211_S2021_UAH
9e8e5452526288699e0d7ee22ed393857233501e
[ "MIT" ]
null
null
null
All Project/Project_08.cpp
jaibae21/CPE211_S2021_UAH
9e8e5452526288699e0d7ee22ed393857233501e
[ "MIT" ]
null
null
null
All Project/Project_08.cpp
jaibae21/CPE211_S2021_UAH
9e8e5452526288699e0d7ee22ed393857233501e
[ "MIT" ]
1
2022-03-26T08:52:00.000Z
2022-03-26T08:52:00.000Z
// **************************************** // Program Title: Project_08 // Project File: Project_08.cpp // Name: Jaiden Gann // Course Section: CPE-211-02 // Lab Section: 2 // Due Date: 03/28/21 // program description: Read records of // subscribers for a magazine. Practice with // structs and more functions // **************************************** #include <iostream> #include <string> #include <climits> #include <fstream> #include <iomanip> using namespace std; //structures struct SubscriberName { string firstName; string lastName; int customerID; }; struct Address { string street; string city; string state; int zip_code; }; struct Date { string month; int day; int year; }; struct RenewalInfo { int monthLeft; Date renewal_notice; }; struct MagazineService { SubscriberName subscriber_name; Address address; RenewalInfo renewal_info; }; //function prototypes void OpenInput(ifstream&); void OpenOutput(ofstream&); void ReadRecord(MagazineService&, ifstream&); //assign things structs bool CheckEmpty(MagazineService&, ifstream&); //check for the empty file void WriteInfo(MagazineService&, ofstream&); //write to output file int main() { MagazineService customer; int numberSubscribers, expireSubscriptions; //counters numberSubscribers = 0; expireSubscriptions = 0; ifstream InFile; ofstream OutFile; OpenInput(InFile); //open input file OpenOutput(OutFile); //open output file if (CheckEmpty(customer, InFile) == true) //test to see if file is empty at start { cout << "===> Input file is empty. Program terminated\n\n"; OutFile << string(52, '-') << endl; OutFile << "==> The input file does not contain any information.\n"; OutFile << string(52, '-') << endl; OutFile.close(); return 1; } else { while (!InFile.eof()) { cout << "====> Processing Customer ID: " << customer.subscriber_name.customerID << endl; if (customer.renewal_info.monthLeft == 0) { numberSubscribers++; expireSubscriptions++; WriteInfo(customer, OutFile); ReadRecord(customer, InFile); } else { numberSubscribers++; ReadRecord(customer, InFile); } } cout << endl << string(47, '-') << endl; cout << "Number of subscribers processed: " << numberSubscribers << endl; cout << "The number of expired subscriptions is: " << expireSubscriptions << endl; cout << string(47, '-') << endl << endl; } InFile.close(); OutFile.close(); InFile.clear(); return 0; } //functions void OpenInput(ifstream& InFile) { string filename; cout << endl << "Enter name of input file or Control-C to quit program: "; cin >> filename; cout << filename << endl << endl; InFile.open(filename.c_str()); while (InFile.fail()) { InFile.clear(); cout << string(15, '*') << " File Open Error " << string(15, '*') << endl; cout << "==> Input file failed to open properly!!\n"; cout << "==> Attempted to open file: " << filename << endl; cout << "==> Please try again...\n"; cout << string(47, '*') << endl << endl; cout << "Enter name of input file or Control-C to quit program: "; cin >> filename; cout << filename << endl << endl; cin.ignore(INT_MAX, '\n'); InFile.open(filename.c_str()); } return; } void OpenOutput(ofstream& OutFile) { string outname; cout << "Enter name of output file or Control-C to quit program: "; cin >> outname; cout << outname << endl << endl; OutFile.open(outname.c_str()); while (OutFile.fail()) { OutFile.clear(); cout << string(15, '*') << " File Open Error " << string(15, '*') << endl; cout << "==> Output file failed to open properly!!\n"; cout << "==> Attempted to open file: " << outname << endl; cout << "==> Please try again...\n"; cout << string(47, '*') << endl << endl; cout << "Enter name of output file or Control-C to quit program: "; cin >> outname; cout << outname << endl << endl; cin.ignore(INT_MAX, '\n'); OutFile.open(outname.c_str()); } return; } bool CheckEmpty(MagazineService& customer, ifstream& InFile) { bool empty; string emptyfile; empty = false; getline(InFile, customer.subscriber_name.firstName); getline(InFile, customer.subscriber_name.lastName, '\n'); InFile >> customer.subscriber_name.customerID; //ID InFile.ignore(INT_MAX, '\n'); getline(InFile, customer.address.street, '\n'); //street getline(InFile, customer.address.city, '\n'); //city getline(InFile, customer.address.state, '\n'); //state InFile >> customer.address.zip_code; //zip InFile.ignore(INT_MAX, '\n'); InFile >> customer.renewal_info.monthLeft; //months remaining on sub InFile.ignore(INT_MAX, '\n'); getline(InFile, customer.renewal_info.renewal_notice.month, '\n'); InFile >> customer.renewal_info.renewal_notice.day; //renewal notice day InFile.ignore(INT_MAX, '\n'); InFile >> customer.renewal_info.renewal_notice.year; //renewal notic year InFile.ignore(INT_MAX, '\n'); if (InFile.fail()) //would mean file is empty { empty = true; InFile.clear(); InFile.close(); } return empty; } void ReadRecord(MagazineService& customer, ifstream& InFile) { bool done; done = false; InFile.clear();//clear stream from empty check { getline(InFile, customer.subscriber_name.firstName); getline(InFile, customer.subscriber_name.lastName, '\n'); InFile >> customer.subscriber_name.customerID; //ID //cout << "Processing Customer ID:" << customer.subscriber_name.customerID << endl; InFile.ignore(INT_MAX, '\n'); getline(InFile, customer.address.street, '\n'); //street getline(InFile, customer.address.city, '\n'); //city getline(InFile, customer.address.state, '\n'); //state InFile >> customer.address.zip_code; //zip InFile.ignore(INT_MAX, '\n'); InFile >> customer.renewal_info.monthLeft; //months remaining on sub InFile.ignore(INT_MAX, '\n'); getline(InFile, customer.renewal_info.renewal_notice.month, '\n'); InFile >> customer.renewal_info.renewal_notice.day; //renewal notice day InFile.ignore(INT_MAX, '\n'); InFile >> customer.renewal_info.renewal_notice.year; //renewal notic year InFile.ignore(INT_MAX, '\n'); } return; } void WriteInfo(MagazineService& customer, ofstream& OutFile) { OutFile << string(55, '*') << endl; OutFile << customer.subscriber_name.firstName << " " << customer.subscriber_name.lastName << "(" << customer.subscriber_name.customerID << ")\n"; OutFile << customer.address.street << endl; OutFile << customer.address.city << ", " << customer.address.state << " " << customer.address.zip_code << endl; OutFile << "The last renewal notice was sent on " << customer.renewal_info.renewal_notice.month << " " << customer.renewal_info.renewal_notice.day << ", " << customer.renewal_info.renewal_notice.year << endl; OutFile << string(55, '*') << endl << endl; }
30.388646
210
0.651387
jaibae21
eb3e4625d894475d880bb4cd80b587b7076f0a55
16,603
cpp
C++
DesktopPony/ui/plugin/uipluginfilter.cpp
WisteFinch/DesktopPony
846499169164779b04118f5637d1e71c98c212ad
[ "MIT" ]
2
2020-10-02T03:45:57.000Z
2020-10-02T03:46:12.000Z
DesktopPony/ui/plugin/uipluginfilter.cpp
WisteFinch/DesktopPony
846499169164779b04118f5637d1e71c98c212ad
[ "MIT" ]
null
null
null
DesktopPony/ui/plugin/uipluginfilter.cpp
WisteFinch/DesktopPony
846499169164779b04118f5637d1e71c98c212ad
[ "MIT" ]
2
2021-04-04T11:53:44.000Z
2021-07-07T01:35:50.000Z
#include "uipluginfilter.h" UiPluginFilter::UiPluginFilter(QWidget *parent) : QWidget(parent) { this->m_p_hide_timer = new QTimer; this->m_p_hide_timer->setInterval(50); this->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint); connect(this->m_p_hide_timer, &QTimer::timeout, this, &UiPluginFilter::timerHideTimeOut); } UiPluginFilter::~UiPluginFilter() { this->m_p_text = nullptr; clearConnect(); disconnect(this->m_p_hide_timer, &QTimer::timeout, this, &UiPluginFilter::timerHideTimeOut); } void UiPluginFilter::init(Text *ptrText, QPushButton *ptrParent) { this->m_p_text = ptrText; this->m_p_parent_button = ptrParent; ptrText = nullptr; ptrParent = nullptr; this->setAttribute(Qt::WA_TranslucentBackground); initWidget(); initObjectName(); initProperty(); initContent(); initConnect(); } void UiPluginFilter::initWidget() { this->ui_layout_main = new QVBoxLayout; this->ui_layout_main->setSpacing(0); this->ui_layout_main->setMargin(0); this->ui_widget = new QWidget; this->ui_layout_main->addWidget(this->ui_widget); this->ui_layout_widget = new QVBoxLayout; this->ui_layout_widget->setMargin(5); this->ui_layout_widget->setSpacing(5); this->ui_widget->setLayout(this->ui_layout_widget); this->ui_layout_localisation = new QHBoxLayout; this->ui_layout_localisation->setMargin(0); this->ui_layout_localisation->setSpacing(0); this->ui_layout_widget->addLayout(this->ui_layout_localisation); this->ui_localisation = new QLabel; this->ui_layout_localisation->addWidget(this->ui_localisation); this->ui_layout_localisation->addStretch(); this->ui_localisation_switch = new QCheckBox; this->ui_localisation_switch->setChecked(true); this->ui_layout_localisation->addWidget(this->ui_localisation_switch); this->ui_layout_style = new QHBoxLayout; this->ui_layout_style->setMargin(0); this->ui_layout_style->setSpacing(0); this->ui_layout_widget->addLayout(this->ui_layout_style); this->ui_style = new QLabel; this->ui_layout_style->addWidget(this->ui_style); this->ui_layout_style->addStretch(); this->ui_style_switch = new QCheckBox; this->ui_style_switch->setChecked(true); this->ui_layout_style->addWidget(this->ui_style_switch); this->ui_layout_event = new QHBoxLayout; this->ui_layout_event->setMargin(0); this->ui_layout_event->setSpacing(0); this->ui_layout_widget->addLayout(this->ui_layout_event); this->ui_event = new QLabel; this->ui_layout_event->addWidget(this->ui_event); this->ui_layout_event->addStretch(); this->ui_event_switch = new QCheckBox; this->ui_event_switch->setChecked(true); this->ui_layout_event->addWidget(this->ui_event_switch); this->ui_layout_action = new QHBoxLayout; this->ui_layout_action->setMargin(0); this->ui_layout_action->setSpacing(0); this->ui_layout_widget->addLayout(this->ui_layout_action); this->ui_action = new QLabel; this->ui_layout_action->addWidget(this->ui_action); this->ui_layout_action->addStretch(); this->ui_action_switch = new QCheckBox; this->ui_action_switch->setChecked(true); this->ui_layout_action->addWidget(this->ui_action_switch); this->ui_layout_accessories = new QHBoxLayout; this->ui_layout_accessories->setMargin(0); this->ui_layout_accessories->setSpacing(0); this->ui_layout_widget->addLayout(this->ui_layout_accessories); this->ui_accessories = new QLabel; this->ui_layout_accessories->addWidget(this->ui_accessories); this->ui_layout_accessories->addStretch(); this->ui_accessories_switch = new QCheckBox; this->ui_accessories_switch->setChecked(true); this->ui_layout_accessories->addWidget(this->ui_accessories_switch); this->ui_layout_model = new QHBoxLayout; this->ui_layout_model->setMargin(0); this->ui_layout_model->setSpacing(0); this->ui_layout_widget->addLayout(this->ui_layout_model); this->ui_model = new QLabel; this->ui_layout_model->addWidget(this->ui_model); this->ui_layout_model->addStretch(); this->ui_model_switch = new QCheckBox; this->ui_model_switch->setChecked(true); this->ui_layout_model->addWidget(this->ui_model_switch); this->ui_layout_config = new QHBoxLayout; this->ui_layout_config->setMargin(0); this->ui_layout_config->setSpacing(0); this->ui_layout_widget->addLayout(this->ui_layout_config); this->ui_config = new QLabel; this->ui_layout_config->addWidget(this->ui_config); this->ui_layout_config->addStretch(); this->ui_config_switch = new QCheckBox; this->ui_config_switch->setChecked(true); this->ui_layout_config->addWidget(this->ui_config_switch); this->ui_layout_rc = new QHBoxLayout; this->ui_layout_rc->setMargin(0); this->ui_layout_rc->setSpacing(0); this->ui_layout_widget->addLayout(this->ui_layout_rc); this->ui_rc = new QLabel; this->ui_layout_rc->addWidget(this->ui_rc); this->ui_layout_rc->addStretch(); this->ui_rc_switch = new QCheckBox; this->ui_rc_switch->setChecked(true); this->ui_layout_rc->addWidget(this->ui_rc_switch); this->ui_layout_lib = new QHBoxLayout; this->ui_layout_lib->setMargin(0); this->ui_layout_lib->setSpacing(0); this->ui_layout_widget->addLayout(this->ui_layout_lib); this->ui_lib = new QLabel; this->ui_layout_lib->addWidget(this->ui_lib); this->ui_layout_lib->addStretch(); this->ui_lib_switch = new QCheckBox; this->ui_lib_switch->setChecked(true); this->ui_layout_lib->addWidget(this->ui_lib_switch); this->ui_layout_null = new QHBoxLayout; this->ui_layout_null->setMargin(0); this->ui_layout_null->setSpacing(0); this->ui_layout_widget->addLayout(this->ui_layout_null); this->ui_null = new QLabel; this->ui_layout_null->addWidget(this->ui_null); this->ui_layout_null->addStretch(); this->ui_null_switch = new QCheckBox; this->ui_null_switch->setChecked(true); this->ui_layout_null->addWidget(this->ui_null_switch); this->setLayout(this->ui_layout_main); } void UiPluginFilter::initObjectName() { this->setObjectName(QStringLiteral("ui_plugin_filter")); // 部件部分 this->ui_widget->setObjectName(QStringLiteral("ui_plugin_filter_widget")); this->ui_localisation->setObjectName(QStringLiteral("ui_plugin_filter_localisation")); this->ui_localisation_switch->setObjectName(QStringLiteral("ui_plugin_filter_localisation_switch")); this->ui_style->setObjectName(QStringLiteral("ui_plugin_filter_style")); this->ui_style_switch->setObjectName(QStringLiteral("ui_plugin_filter_style_switch")); this->ui_event->setObjectName(QStringLiteral("ui_plugin_filter_event")); this->ui_event_switch->setObjectName(QStringLiteral("ui_plugin_filter_event_switch")); this->ui_action->setObjectName(QStringLiteral("ui_plugin_filter_action")); this->ui_action_switch->setObjectName(QStringLiteral("ui_plugin_filter_action_switch")); this->ui_accessories->setObjectName(QStringLiteral("ui_plugin_filter_accessories")); this->ui_accessories_switch->setObjectName(QStringLiteral("ui_plugin_filter_accessories_switch")); this->ui_model->setObjectName(QStringLiteral("ui_plugin_filter_model")); this->ui_model_switch->setObjectName(QStringLiteral("ui_plugin_filter_model_switch")); this->ui_config->setObjectName(QStringLiteral("ui_plugin_filter_config")); this->ui_config_switch->setObjectName(QStringLiteral("ui_plugin_filter_config_switch")); this->ui_rc->setObjectName(QStringLiteral("ui_plugin_filter_rc")); this->ui_rc_switch->setObjectName(QStringLiteral("ui_plugin_filter_rc_switch")); this->ui_lib->setObjectName(QStringLiteral("ui_plugin_filter_lib")); this->ui_lib_switch->setObjectName(QStringLiteral("ui_plugin_filter_lib_switch")); this->ui_null->setObjectName(QStringLiteral("ui_plugin_filter_null")); this->ui_null_switch->setObjectName(QStringLiteral("ui_plugin_filter_null_switch")); // 布局部分 this->ui_layout_widget->setObjectName(QStringLiteral("ui_plugin_filter_layout_widget")); this->ui_layout_localisation->setObjectName(QStringLiteral("ui_plugin_filter_layout_localisation")); this->ui_layout_style->setObjectName(QStringLiteral("ui_plugin_filter_layout_style")); this->ui_layout_event->setObjectName(QStringLiteral("ui_plugin_filter_layout_event")); this->ui_layout_action->setObjectName(QStringLiteral("ui_plugin_filter_layout_action")); this->ui_layout_accessories->setObjectName(QStringLiteral("ui_plugin_filter_layout_accessories")); this->ui_layout_model->setObjectName(QStringLiteral("ui_plugin_filter_layout_model")); this->ui_layout_config->setObjectName(QStringLiteral("ui_plugin_filter_layout_config")); this->ui_layout_rc->setObjectName(QStringLiteral("ui_plugin_filter_layout_rc")); this->ui_layout_lib->setObjectName(QStringLiteral("ui_plugin_filter_layout_lib")); this->ui_layout_null->setObjectName(QStringLiteral("ui_plugin_filter_layout_null")); } void UiPluginFilter::initProperty() { this->setProperty("category", QStringLiteral("plugin_filter")); // 部件部分 this->ui_widget->setProperty("category", QStringLiteral("plugin_filter_widget")); this->ui_localisation->setProperty("category", QStringLiteral("plugin_filter_label")); this->ui_localisation_switch->setProperty("category", QStringLiteral("plugin_filter_switch")); this->ui_style->setProperty("category", QStringLiteral("plugin_filter_label")); this->ui_style_switch->setProperty("category", QStringLiteral("plugin_filter_switch")); this->ui_event->setProperty("category", QStringLiteral("plugin_filter_label")); this->ui_event_switch->setProperty("category", QStringLiteral("plugin_filter_switch")); this->ui_action->setProperty("category", QStringLiteral("plugin_filter_label")); this->ui_action_switch->setProperty("category", QStringLiteral("plugin_filter_switch")); this->ui_accessories->setProperty("category", QStringLiteral("plugin_filter_label")); this->ui_accessories_switch->setProperty("category", QStringLiteral("plugin_filter_switch")); this->ui_model->setProperty("category", QStringLiteral("plugin_filter_label")); this->ui_model_switch->setProperty("category", QStringLiteral("plugin_filter_switch")); this->ui_config->setProperty("category", QStringLiteral("plugin_filter_label")); this->ui_config_switch->setProperty("category", QStringLiteral("plugin_filter_switch")); this->ui_rc->setProperty("category", QStringLiteral("plugin_filter_label")); this->ui_rc_switch->setProperty("category", QStringLiteral("plugin_filter_switch")); this->ui_lib->setProperty("category", QStringLiteral("plugin_filter_label")); this->ui_lib_switch->setProperty("category", QStringLiteral("plugin_filter_switch")); this->ui_null->setProperty("category", QStringLiteral("plugin_filter_label")); this->ui_null_switch->setProperty("category", QStringLiteral("plugin_filter_switch")); } void UiPluginFilter::initContent() { this->ui_localisation->setText(this->m_p_text->getLoc(QStringLiteral("plugin_localisation"))); this->ui_style->setText(this->m_p_text->getLoc(QStringLiteral("plugin_style"))); this->ui_event->setText(this->m_p_text->getLoc(QStringLiteral("plugin_event"))); this->ui_action->setText(this->m_p_text->getLoc(QStringLiteral("plugin_action"))); this->ui_accessories->setText(this->m_p_text->getLoc(QStringLiteral("plugin_accessories"))); this->ui_model->setText(this->m_p_text->getLoc(QStringLiteral("plugin_model"))); this->ui_config->setText(this->m_p_text->getLoc(QStringLiteral("plugin_config"))); this->ui_rc->setText(this->m_p_text->getLoc(QStringLiteral("plugin_resources"))); this->ui_lib->setText(this->m_p_text->getLoc(QStringLiteral("plugin_library"))); this->ui_null->setText(this->m_p_text->getLoc(QStringLiteral("ui_plugin_page_filter_null_txt"))); } void UiPluginFilter::initConnect() { connect(this->ui_localisation_switch, &QCheckBox::toggled, this, [ = ](bool flag) { this->m_filter_loc = flag; emit sigFilterChanged(); }); connect(this->ui_style_switch, &QCheckBox::toggled, this, [ = ](bool flag) { this->m_filter_style = flag; emit sigFilterChanged(); }); connect(this->ui_event_switch, &QCheckBox::toggled, this, [ = ](bool flag) { this->m_filter_event = flag; emit sigFilterChanged(); }); connect(this->ui_action_switch, &QCheckBox::toggled, this, [ = ](bool flag) { this->m_filter_action = flag; emit sigFilterChanged(); }); connect(this->ui_accessories_switch, &QCheckBox::toggled, this, [ = ](bool flag) { this->m_filter_acc = flag; emit sigFilterChanged(); }); connect(this->ui_model_switch, &QCheckBox::toggled, this, [ = ](bool flag) { this->m_filter_model = flag; emit sigFilterChanged(); }); connect(this->ui_config_switch, &QCheckBox::toggled, this, [ = ](bool flag) { this->m_filter_conf = flag; emit sigFilterChanged(); }); connect(this->ui_rc_switch, &QCheckBox::toggled, this, [ = ](bool flag) { this->m_filter_model = flag; emit sigFilterChanged(); }); connect(this->ui_lib_switch, &QCheckBox::toggled, this, [ = ](bool flag) { this->m_filter_conf = flag; emit sigFilterChanged(); }); connect(this->ui_null_switch, &QCheckBox::toggled, this, [ = ](bool flag) { this->m_filter_null = flag; emit sigFilterChanged(); }); } void UiPluginFilter::clearConnect() { disconnect(this->ui_localisation_switch, &QCheckBox::toggled, this, nullptr); disconnect(this->ui_style_switch, &QCheckBox::toggled, this, nullptr); disconnect(this->ui_event_switch, &QCheckBox::toggled, this, nullptr); disconnect(this->ui_action_switch, &QCheckBox::toggled, this, nullptr); disconnect(this->ui_accessories_switch, &QCheckBox::toggled, this, nullptr); disconnect(this->ui_model_switch, &QCheckBox::toggled, this, nullptr); disconnect(this->ui_config_switch, &QCheckBox::toggled, this, nullptr); disconnect(this->ui_rc_switch, &QCheckBox::toggled, this, nullptr); disconnect(this->ui_lib_switch, &QCheckBox::toggled, this, nullptr); disconnect(this->ui_null_switch, &QCheckBox::toggled, this, nullptr); } void UiPluginFilter::showFilter() { this->m_is_mouse_entered = false; this->m_mouse_unentered_time = 0; this->setMouseTracking(true); this->m_p_hide_timer->start(); show(); moveSelf(); } void UiPluginFilter::moveSelf() { QPoint pr = this->m_p_parent_button->mapToGlobal(QPoint(0, 0)); QSize ps = this->m_p_parent_button->size(); QSize ws = this->ui_widget->size(); move(pr.x() + ps.width() - ws.width(), pr.y() + ps.height() + 5); } void UiPluginFilter::timerHideTimeOut() { if(this->isVisible()) { moveSelf(); if(this->m_is_mouse_entered) { QPoint cp = QCursor::pos(); QPoint sp = this->mapFromGlobal(cp); QRectF rect = this->rect(); if (!rect.contains(sp)) { this->setMouseTracking(false); this->m_p_hide_timer->stop(); this->hide(); } } else { if(++this->m_mouse_unentered_time > 50) { this->setMouseTracking(false); this->m_p_hide_timer->stop(); this->hide(); } } } else { this->setMouseTracking(false); this->m_p_hide_timer->stop(); this->hide(); } } void UiPluginFilter::enterEvent(QEvent *ev) { ev->ignore(); this->m_is_mouse_entered = true; } void UiPluginFilter::reset() { this->m_filter_loc = true; this->m_filter_style = true; this->m_filter_event = true; this->m_filter_action = true; this->m_filter_acc = true; this->m_filter_model = true; this->m_filter_conf = true; this->m_filter_rc = true; this->m_filter_lib = true; this->m_filter_null = true; this->ui_localisation_switch->setChecked(true); this->ui_style_switch->setChecked(true); this->ui_event_switch->setChecked(true); this->ui_action_switch->setChecked(true); this->ui_accessories_switch->setChecked(true); this->ui_model_switch->setChecked(true); this->ui_config_switch->setChecked(true); this->ui_rc_switch->setChecked(true); this->ui_lib_switch->setChecked(true); this->ui_null_switch->setChecked(true); }
44.872973
104
0.723423
WisteFinch
eb407b8f411e4f601273b2dd867805a51526bda1
400
cpp
C++
src/dxvk/dxvk_data.cpp
notaz/dxvk
93348731880b6764464c1fbc0d5fe92f47b053fe
[ "Zlib" ]
null
null
null
src/dxvk/dxvk_data.cpp
notaz/dxvk
93348731880b6764464c1fbc0d5fe92f47b053fe
[ "Zlib" ]
null
null
null
src/dxvk/dxvk_data.cpp
notaz/dxvk
93348731880b6764464c1fbc0d5fe92f47b053fe
[ "Zlib" ]
2
2019-08-10T07:38:07.000Z
2019-11-09T14:06:29.000Z
#include <cstring> #include "dxvk_data.h" namespace dxvk { DxvkDataBuffer:: DxvkDataBuffer() { } DxvkDataBuffer::~DxvkDataBuffer() { } DxvkDataBuffer::DxvkDataBuffer( size_t size) { m_data.resize(size); } DxvkDataBuffer::DxvkDataBuffer( const void* data, size_t size) { m_data.resize(size); std::memcpy(m_data.data(), data, size); } }
18.181818
43
0.62
notaz
eb422102cd381f9af351ac4b8870cfb81a1812de
639
cpp
C++
src/piece.cpp
hallur/boardgame
374fd1366cbae785bc40ba24403d50e36b2a3637
[ "MIT" ]
null
null
null
src/piece.cpp
hallur/boardgame
374fd1366cbae785bc40ba24403d50e36b2a3637
[ "MIT" ]
1
2018-04-09T19:08:41.000Z
2018-04-09T19:08:41.000Z
src/piece.cpp
hallur/boardgame
374fd1366cbae785bc40ba24403d50e36b2a3637
[ "MIT" ]
null
null
null
#include "piece.h" #include <iostream> boardgame::Piece::Piece(boardgame::Player* player, const char& marker) : marker_(marker), player_(player) {} boardgame::Piece::~Piece() {} char boardgame::Piece::getMarker() const { return marker_; } boardgame::Player* boardgame::Piece::getPlayer() const { return player_; } void boardgame::Piece::setPlayer(boardgame::Player* player) { player_ = player; } std::vector<boardgame::MoveRule> boardgame::Piece::getMoveRules() const { return moveRules_; } std::ostream& boardgame::operator<<(std::ostream& os, const boardgame::Piece& rhs) { os << rhs.marker_; return os; }
23.666667
108
0.694836
hallur
eb47dc856e2d386b34c596e3da6fd623d91dcce1
2,976
cpp
C++
src/extern/inventor/lib/database/src/so/nodes/nurbs/libnurbs/maplist.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
2
2020-05-21T07:06:07.000Z
2021-06-28T02:14:34.000Z
src/extern/inventor/lib/database/src/so/nodes/nurbs/libnurbs/maplist.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
null
null
null
src/extern/inventor/lib/database/src/so/nodes/nurbs/libnurbs/maplist.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
6
2016-03-21T19:53:18.000Z
2021-06-08T18:06:03.000Z
/* * * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. * * This library 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.1 of the License, or (at your option) any later version. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ * */ /* * maplist.c++ - $Revision: 1.1.1.1 $ * Derrick Burns - 1991 */ #include "glimports.h" #include "mystdio.h" #include "myassert.h" #include "mymath.h" #include "nurbsconsts.h" #include "maplist.h" #include "mapdesc.h" #include "backend.h" Maplist::Maplist( Backend& b ) : mapdescPool( sizeof( Mapdesc ), 10, "mapdesc pool" ), backend( b ) { maps = 0; lastmap = &maps; } void Maplist::initialize( void ) { freeMaps(); define( N_P2D, 0, 2 ); define( N_P2DR, 1, 3 ); } void Maplist::add( long type, int israt, int ncoords ) { *lastmap = new(mapdescPool) Mapdesc( type, israt, ncoords, backend ); lastmap = &((*lastmap)->next); } void Maplist::define( long type, int israt, int ncoords ) { Mapdesc *m = locate( type ); assert( m == NULL || ( m->isrational == israt && m->ncoords == ncoords ) ); add( type, israt, ncoords ); } void Maplist::remove( Mapdesc *m ) { for( Mapdesc **curmap = &maps; *curmap; curmap = &((*curmap)->next) ) { if( *curmap == m ) { *curmap = m->next; m->deleteMe( mapdescPool ); return; } } abort(); } void Maplist::freeMaps( void ) { mapdescPool.clear(); maps = 0; lastmap = &maps; } Mapdesc * Maplist::find( long type ) { Mapdesc *val = locate( type ); assert( val ); return val; } Mapdesc * Maplist::locate( long type ) { Mapdesc *m; for( m = maps; m; m = m->next ) if( m->getType() == type ) break; return m; }
25.220339
79
0.654234
OpenXIP
eb4873c22694abe76642c9974c96c5a2ab3d4d97
3,065
cpp
C++
aws-cpp-sdk-networkmanager/source/model/NetworkRoute.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-networkmanager/source/model/NetworkRoute.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-networkmanager/source/model/NetworkRoute.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/networkmanager/model/NetworkRoute.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace NetworkManager { namespace Model { NetworkRoute::NetworkRoute() : m_destinationCidrBlockHasBeenSet(false), m_destinationsHasBeenSet(false), m_prefixListIdHasBeenSet(false), m_state(RouteState::NOT_SET), m_stateHasBeenSet(false), m_type(RouteType::NOT_SET), m_typeHasBeenSet(false) { } NetworkRoute::NetworkRoute(JsonView jsonValue) : m_destinationCidrBlockHasBeenSet(false), m_destinationsHasBeenSet(false), m_prefixListIdHasBeenSet(false), m_state(RouteState::NOT_SET), m_stateHasBeenSet(false), m_type(RouteType::NOT_SET), m_typeHasBeenSet(false) { *this = jsonValue; } NetworkRoute& NetworkRoute::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("DestinationCidrBlock")) { m_destinationCidrBlock = jsonValue.GetString("DestinationCidrBlock"); m_destinationCidrBlockHasBeenSet = true; } if(jsonValue.ValueExists("Destinations")) { Array<JsonView> destinationsJsonList = jsonValue.GetArray("Destinations"); for(unsigned destinationsIndex = 0; destinationsIndex < destinationsJsonList.GetLength(); ++destinationsIndex) { m_destinations.push_back(destinationsJsonList[destinationsIndex].AsObject()); } m_destinationsHasBeenSet = true; } if(jsonValue.ValueExists("PrefixListId")) { m_prefixListId = jsonValue.GetString("PrefixListId"); m_prefixListIdHasBeenSet = true; } if(jsonValue.ValueExists("State")) { m_state = RouteStateMapper::GetRouteStateForName(jsonValue.GetString("State")); m_stateHasBeenSet = true; } if(jsonValue.ValueExists("Type")) { m_type = RouteTypeMapper::GetRouteTypeForName(jsonValue.GetString("Type")); m_typeHasBeenSet = true; } return *this; } JsonValue NetworkRoute::Jsonize() const { JsonValue payload; if(m_destinationCidrBlockHasBeenSet) { payload.WithString("DestinationCidrBlock", m_destinationCidrBlock); } if(m_destinationsHasBeenSet) { Array<JsonValue> destinationsJsonList(m_destinations.size()); for(unsigned destinationsIndex = 0; destinationsIndex < destinationsJsonList.GetLength(); ++destinationsIndex) { destinationsJsonList[destinationsIndex].AsObject(m_destinations[destinationsIndex].Jsonize()); } payload.WithArray("Destinations", std::move(destinationsJsonList)); } if(m_prefixListIdHasBeenSet) { payload.WithString("PrefixListId", m_prefixListId); } if(m_stateHasBeenSet) { payload.WithString("State", RouteStateMapper::GetNameForRouteState(m_state)); } if(m_typeHasBeenSet) { payload.WithString("Type", RouteTypeMapper::GetNameForRouteType(m_type)); } return payload; } } // namespace Model } // namespace NetworkManager } // namespace Aws
23.576923
114
0.741272
perfectrecall
eb4c0f236e261e5b57e31d49d5ed99837c6ce2bd
1,181
cpp
C++
src/proto/codec/AFCodecProto.cpp
ArkGame/ArkGameFrame
a7f8413dd416cd1ac5b12adbdd84f010f59f11e2
[ "Apache-2.0" ]
168
2016-08-18T07:24:48.000Z
2018-02-06T06:40:45.000Z
src/proto/codec/AFCodecProto.cpp
Mu-L/ARK
a7f8413dd416cd1ac5b12adbdd84f010f59f11e2
[ "Apache-2.0" ]
11
2019-05-27T12:26:02.000Z
2021-05-12T02:45:16.000Z
src/proto/codec/AFCodecProto.cpp
ArkGame/ArkGameFrame
a7f8413dd416cd1ac5b12adbdd84f010f59f11e2
[ "Apache-2.0" ]
51
2016-09-01T10:17:38.000Z
2018-02-06T10:45:25.000Z
/* * This source file is part of ArkNX * For the latest info, see https://github.com/ArkNX * * Copyright (c) 2013-2020 ArkNX authors. * * 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 "AFCodecProto.hpp" namespace ark { ark::ARK_CODEC_STATUS AFCodecProto::Encode() { // TODO: return ARK_CODEC_STATUS::CODEC_STATUS_OK; } ark::ARK_CODEC_STATUS AFCodecProto::Decode() { // TODO: return ARK_CODEC_STATUS::CODEC_STATUS_OK; } ARK_CODEC_TYPE AFCodecProto::GetCodecType() const { return ARK_CODEC_TYPE::CODEC_PROTO; } void AFCodecProto::SetCodecType(ARK_CODEC_TYPE type) { type_ = ARK_CODEC_TYPE::CODEC_PROTO; } } // namespace ark
24.604167
75
0.730737
ArkGame
eb5904afccf94f616edb8a35c4cc9b44f10aacc8
771
cc
C++
caffe2/operators/replace_nan_op_hip.cc
rohithkrn/rocm_caffe2
c21a1f0b8607a681cedb923b2013804d31d529a4
[ "Apache-2.0" ]
null
null
null
caffe2/operators/replace_nan_op_hip.cc
rohithkrn/rocm_caffe2
c21a1f0b8607a681cedb923b2013804d31d529a4
[ "Apache-2.0" ]
null
null
null
caffe2/operators/replace_nan_op_hip.cc
rohithkrn/rocm_caffe2
c21a1f0b8607a681cedb923b2013804d31d529a4
[ "Apache-2.0" ]
null
null
null
#include "hip/hip_runtime.h" #include "caffe2/core/context_hip.h" #include "caffe2/operators/replace_nan_op.h" namespace caffe2 { namespace { template <typename T> __global__ void replace_nan_kernel(const T value, const TIndex size, const T* X, T* Y) { HIP_1D_KERNEL_LOOP(i, size) { if (isnan(X[i])) { Y[i] = value; } else { Y[i] = X[i]; } } } } // namespace template <> template <typename T> void ReplaceNaNOp<HIPContext>::ReplaceNaN( const T& value, const TIndex size, const T* X, T* Y) { hipLaunchKernelGGL((replace_nan_kernel), dim3(CAFFE_GET_BLOCKS(size)), dim3(CAFFE_HIP_NUM_THREADS), 0, context_.hip_stream(), value, size, X, Y); } REGISTER_HIP_OPERATOR(ReplaceNaN, ReplaceNaNOp<HIPContext>); } // namespace caffe2
24.09375
147
0.688716
rohithkrn
eb5f96e9f816a33293716c1e21ce30c359ed042f
1,970
cpp
C++
Source/DarkLab/ExitVolume.cpp
rinial/DarkLab
82d29368d8b009eec02522706f368c1545fa3514
[ "MIT" ]
6
2020-09-05T02:25:37.000Z
2022-02-07T02:05:57.000Z
Source/DarkLab/ExitVolume.cpp
Ziririn/DarkLab
82d29368d8b009eec02522706f368c1545fa3514
[ "MIT" ]
null
null
null
Source/DarkLab/ExitVolume.cpp
Ziririn/DarkLab
82d29368d8b009eec02522706f368c1545fa3514
[ "MIT" ]
1
2020-09-05T02:25:56.000Z
2020-09-05T02:25:56.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "ExitVolume.h" #include "Components/ArrowComponent.h" #include "Components/BoxComponent.h" #include "Components/PointLightComponent.h" #include "MainCharacter.h" #include "MainGameMode.h" // Activates volume's light void AExitVolume::ActivateLight() { Light->SetVisibility(true); } void AExitVolume::Reset() { Light->SetVisibility(false); } // Used for the collision overlaps void AExitVolume::OnBeginOverlap(UPrimitiveComponent * OverlappedComp, AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult) { AMainCharacter* character = Cast<AMainCharacter>(OtherActor); if (!character) return; Cast<AMainGameMode>(GetWorld()->GetAuthGameMode())->OnExitReached(); } void AExitVolume::OnEndOverlap(UPrimitiveComponent * OverlappedComp, AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 OtherBodyIndex) { UE_LOG(LogTemp, Warning, TEXT("Left the exit! Why?? :c")); // TODO } // Sets default values AExitVolume::AExitVolume() { // Create root component Direction = CreateDefaultSubobject<UArrowComponent>(TEXT("Arrow")); SetRootComponent(Direction); // Create a box for collision Collision = CreateDefaultSubobject<UBoxComponent>(TEXT("BoxCollision")); Collision->SetupAttachment(RootComponent); Collision->OnComponentBeginOverlap.AddDynamic(this, &AExitVolume::OnBeginOverlap); Collision->OnComponentEndOverlap.AddDynamic(this, &AExitVolume::OnEndOverlap); // Create the light Light = CreateDefaultSubobject<UPointLightComponent>(TEXT("Light")); Light->SetupAttachment(RootComponent); } // Called when the game starts or when spawned void AExitVolume::BeginPlay() { Super::BeginPlay(); if (bForMenu) return; // Light is disabled Reset(); // Set size // Gets overridden if done in constructor for some reason BaseSize = FIntVector(8, 1, 5); // TODO make bigger on X? }
28.550725
195
0.76802
rinial
eb60467a51bceeb4946f62c2d169192b594f8061
622
hpp
C++
src/zookeeper/authentication.hpp
clearstorydata/mesos
4164125048c6635a4d0dbe72daf243457b0f325b
[ "Apache-2.0" ]
null
null
null
src/zookeeper/authentication.hpp
clearstorydata/mesos
4164125048c6635a4d0dbe72daf243457b0f325b
[ "Apache-2.0" ]
null
null
null
src/zookeeper/authentication.hpp
clearstorydata/mesos
4164125048c6635a4d0dbe72daf243457b0f325b
[ "Apache-2.0" ]
1
2022-02-19T10:59:37.000Z
2022-02-19T10:59:37.000Z
#ifndef __ZOOKEEPER_AUTHENTICATION_HPP__ #define __ZOOKEEPER_AUTHENTICATION_HPP__ #include <zookeeper.h> #include <string> namespace zookeeper { struct Authentication { Authentication( const std::string& _scheme, const std::string& _credentials) : scheme(_scheme), credentials(_credentials) {} const std::string scheme; const std::string credentials; }; // An ACL that ensures we're the only authenticated user to mutate our // nodes - others are welcome to read. extern const ACL_vector EVERYONE_READ_CREATOR_ALL; } // namespace zookeeper { #endif // __ZOOKEEPER_AUTHENTICATION_HPP__
20.733333
70
0.754019
clearstorydata
eb6330a03a2357147b9780f4e7fd1d6cc53275b3
784
cpp
C++
C++/single-number-iii.cpp
burneychen/LintCode
babd95aca1fa7540e75b1d3b4d458971ebbe6bcb
[ "Unlicense" ]
null
null
null
C++/single-number-iii.cpp
burneychen/LintCode
babd95aca1fa7540e75b1d3b4d458971ebbe6bcb
[ "Unlicense" ]
null
null
null
C++/single-number-iii.cpp
burneychen/LintCode
babd95aca1fa7540e75b1d3b4d458971ebbe6bcb
[ "Unlicense" ]
null
null
null
// Time: O(n) // Space: O(1) class Solution { public: /** * @param A : An integer array * @return : Two integers */ vector<int> singleNumberIII(vector<int> &A) { // Xor all the elements to get x ^ y. int x_xor_y = 0; for (const auto& i : A) { x_xor_y ^= i; } // Get the last bit where 1 occurs. const auto bit = x_xor_y & ~(x_xor_y - 1); // Get the subset of A where the number has the bit. // The subset only contains one of the two integers, call it x. // Xor all the elemets in the subset to get x. int x = 0; for (const auto& i : A) { if (i & bit) { x ^= i; } } return {x, x_xor_y ^ x}; } };
23.757576
71
0.47449
burneychen
eb6383f8d05cf1e2c368dbf8b09706cf2fdcfaa3
9,928
cpp
C++
Uber_Duper_Simulation_Haxe/bin/windows/cpp/obj/src/haxe/Int64.cpp
as3boyan/Uber-Duper-Simulation
a3942831a1acf08479f06fd8cfe8896ec00ac32c
[ "MIT" ]
null
null
null
Uber_Duper_Simulation_Haxe/bin/windows/cpp/obj/src/haxe/Int64.cpp
as3boyan/Uber-Duper-Simulation
a3942831a1acf08479f06fd8cfe8896ec00ac32c
[ "MIT" ]
null
null
null
Uber_Duper_Simulation_Haxe/bin/windows/cpp/obj/src/haxe/Int64.cpp
as3boyan/Uber-Duper-Simulation
a3942831a1acf08479f06fd8cfe8896ec00ac32c
[ "MIT" ]
null
null
null
#include <hxcpp.h> #ifndef INCLUDED_haxe_Int64 #include <haxe/Int64.h> #endif namespace haxe{ Void Int64_obj::__construct(int high,int low) { HX_STACK_FRAME("haxe.Int64","new",0xf44bbaf7,"haxe.Int64.new","D:\\Denis\\PortableSoft\\HaxeToolkit\\haxe\\std/haxe/Int64.hx",29,0x8ed75308) HX_STACK_THIS(this) HX_STACK_ARG(high,"high") HX_STACK_ARG(low,"low") { HX_STACK_LINE(30) this->high = high; HX_STACK_LINE(31) this->low = low; } ; return null(); } //Int64_obj::~Int64_obj() { } Dynamic Int64_obj::__CreateEmpty() { return new Int64_obj; } hx::ObjectPtr< Int64_obj > Int64_obj::__new(int high,int low) { hx::ObjectPtr< Int64_obj > result = new Int64_obj(); result->__construct(high,low); return result;} Dynamic Int64_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Int64_obj > result = new Int64_obj(); result->__construct(inArgs[0],inArgs[1]); return result;} ::String Int64_obj::toString( ){ HX_STACK_FRAME("haxe.Int64","toString",0x676a22b5,"haxe.Int64.toString","D:\\Denis\\PortableSoft\\HaxeToolkit\\haxe\\std/haxe/Int64.hx",80,0x8ed75308) HX_STACK_THIS(this) HX_STACK_LINE(81) if (((((int(this->high) | int(this->low))) == (int)0))){ HX_STACK_LINE(82) return HX_CSTRING("0"); } HX_STACK_LINE(83) ::String str = HX_CSTRING(""); HX_STACK_VAR(str,"str"); HX_STACK_LINE(84) bool neg = false; HX_STACK_VAR(neg,"neg"); HX_STACK_LINE(85) ::haxe::Int64 i = hx::ObjectPtr<OBJ_>(this); HX_STACK_VAR(i,"i"); HX_STACK_LINE(86) if (((i->high < (int)0))){ HX_STACK_LINE(87) neg = true; HX_STACK_LINE(88) ::haxe::Int64 _g; HX_STACK_VAR(_g,"_g"); HX_STACK_LINE(88) { HX_STACK_LINE(88) int high = ~(int)(i->high); HX_STACK_VAR(high,"high"); HX_STACK_LINE(88) int low = -(i->low); HX_STACK_VAR(low,"low"); HX_STACK_LINE(88) if (((low == (int)0))){ HX_STACK_LINE(88) (high)++; } HX_STACK_LINE(88) _g = ::haxe::Int64_obj::__new(high,low); } HX_STACK_LINE(88) i = _g; } HX_STACK_LINE(90) ::haxe::Int64 ten = ::haxe::Int64_obj::__new((int)0,(int)10); HX_STACK_VAR(ten,"ten"); HX_STACK_LINE(91) while((true)){ HX_STACK_LINE(91) if ((!((!(((((int(i->high) | int(i->low))) == (int)0))))))){ HX_STACK_LINE(91) break; } HX_STACK_LINE(92) Dynamic r = ::haxe::Int64_obj::divMod(i,ten); HX_STACK_VAR(r,"r"); HX_STACK_LINE(93) str = (r->__Field(HX_CSTRING("modulus"),true)->__Field(HX_CSTRING("low"),true) + str); HX_STACK_LINE(94) i = r->__Field(HX_CSTRING("quotient"),true); } HX_STACK_LINE(96) if ((neg)){ HX_STACK_LINE(96) str = (HX_CSTRING("-") + str); } HX_STACK_LINE(97) return str; } HX_DEFINE_DYNAMIC_FUNC0(Int64_obj,toString,return ) ::haxe::Int64 Int64_obj::sub( ::haxe::Int64 a,::haxe::Int64 b){ HX_STACK_FRAME("haxe.Int64","sub",0xf44f9417,"haxe.Int64.sub","D:\\Denis\\PortableSoft\\HaxeToolkit\\haxe\\std/haxe/Int64.hx",133,0x8ed75308) HX_STACK_ARG(a,"a") HX_STACK_ARG(b,"b") HX_STACK_LINE(134) int high = (a->high - b->high); HX_STACK_VAR(high,"high"); HX_STACK_LINE(135) int low = (a->low - b->low); HX_STACK_VAR(low,"low"); HX_STACK_LINE(136) int _g = ::haxe::Int64_obj::uicompare(a->low,b->low); HX_STACK_VAR(_g,"_g"); HX_STACK_LINE(136) if (((_g < (int)0))){ HX_STACK_LINE(137) (high)--; } HX_STACK_LINE(138) return ::haxe::Int64_obj::__new(high,low); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Int64_obj,sub,return ) Dynamic Int64_obj::divMod( ::haxe::Int64 modulus,::haxe::Int64 divisor){ HX_STACK_FRAME("haxe.Int64","divMod",0x6f2287ba,"haxe.Int64.divMod","D:\\Denis\\PortableSoft\\HaxeToolkit\\haxe\\std/haxe/Int64.hx",158,0x8ed75308) HX_STACK_ARG(modulus,"modulus") HX_STACK_ARG(divisor,"divisor") HX_STACK_LINE(159) ::haxe::Int64 quotient = ::haxe::Int64_obj::__new((int)0,(int)0); HX_STACK_VAR(quotient,"quotient"); HX_STACK_LINE(160) int mask_high = (int)0; HX_STACK_VAR(mask_high,"mask_high"); HX_STACK_LINE(160) int mask_low = (int)1; HX_STACK_VAR(mask_low,"mask_low"); HX_STACK_LINE(161) ::haxe::Int64 _g = ::haxe::Int64_obj::__new(divisor->high,divisor->low); HX_STACK_VAR(_g,"_g"); HX_STACK_LINE(161) divisor = _g; HX_STACK_LINE(162) while((true)){ HX_STACK_LINE(162) if ((!(((divisor->high >= (int)0))))){ HX_STACK_LINE(162) break; } HX_STACK_LINE(163) int cmp; HX_STACK_VAR(cmp,"cmp"); HX_STACK_LINE(163) { HX_STACK_LINE(163) int v = ::haxe::Int64_obj::uicompare(divisor->high,modulus->high); HX_STACK_VAR(v,"v"); HX_STACK_LINE(163) if (((v != (int)0))){ HX_STACK_LINE(163) cmp = v; } else{ HX_STACK_LINE(163) cmp = ::haxe::Int64_obj::uicompare(divisor->low,modulus->low); } } HX_STACK_LINE(164) divisor->high = (int((int(divisor->high) << int((int)1))) | int(hx::UShr(divisor->low,(int)31))); HX_STACK_LINE(165) divisor->low = (int(divisor->low) << int((int)1)); HX_STACK_LINE(166) mask_high = (int((int(mask_high) << int((int)1))) | int(hx::UShr(mask_low,(int)31))); HX_STACK_LINE(167) mask_low = (int(mask_low) << int((int)1)); HX_STACK_LINE(168) if (((cmp >= (int)0))){ HX_STACK_LINE(168) break; } } HX_STACK_LINE(170) while((true)){ HX_STACK_LINE(170) if ((!(((((int(mask_low) | int(mask_high))) != (int)0))))){ HX_STACK_LINE(170) break; } HX_STACK_LINE(171) int _g1; HX_STACK_VAR(_g1,"_g1"); HX_STACK_LINE(171) { HX_STACK_LINE(171) int v = ::haxe::Int64_obj::uicompare(modulus->high,divisor->high); HX_STACK_VAR(v,"v"); HX_STACK_LINE(171) if (((v != (int)0))){ HX_STACK_LINE(171) _g1 = v; } else{ HX_STACK_LINE(171) _g1 = ::haxe::Int64_obj::uicompare(modulus->low,divisor->low); } } HX_STACK_LINE(171) if (((_g1 >= (int)0))){ HX_STACK_LINE(172) quotient->high = (int(quotient->high) | int(mask_high)); HX_STACK_LINE(173) quotient->low = (int(quotient->low) | int(mask_low)); HX_STACK_LINE(174) ::haxe::Int64 _g2 = ::haxe::Int64_obj::sub(modulus,divisor); HX_STACK_VAR(_g2,"_g2"); HX_STACK_LINE(174) modulus = _g2; } HX_STACK_LINE(176) mask_low = (int(hx::UShr(mask_low,(int)1)) | int((int(mask_high) << int((int)31)))); HX_STACK_LINE(177) mask_high = hx::UShr(mask_high,(int)1); HX_STACK_LINE(179) divisor->low = (int(hx::UShr(divisor->low,(int)1)) | int((int(divisor->high) << int((int)31)))); HX_STACK_LINE(180) divisor->high = hx::UShr(divisor->high,(int)1); } struct _Function_1_1{ inline static Dynamic Block( ::haxe::Int64 &quotient,::haxe::Int64 &modulus){ HX_STACK_FRAME("*","closure",0x5bdab937,"*.closure","D:\\Denis\\PortableSoft\\HaxeToolkit\\haxe\\std/haxe/Int64.hx",182,0x8ed75308) { hx::Anon __result = hx::Anon_obj::Create(); __result->Add(HX_CSTRING("quotient") , quotient,false); __result->Add(HX_CSTRING("modulus") , modulus,false); return __result; } return null(); } }; HX_STACK_LINE(182) return _Function_1_1::Block(quotient,modulus); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Int64_obj,divMod,return ) int Int64_obj::uicompare( int a,int b){ HX_STACK_FRAME("haxe.Int64","uicompare",0x4e5b5aa8,"haxe.Int64.uicompare","D:\\Denis\\PortableSoft\\HaxeToolkit\\haxe\\std/haxe/Int64.hx",252,0x8ed75308) HX_STACK_ARG(a,"a") HX_STACK_ARG(b,"b") HX_STACK_LINE(252) if (((a < (int)0))){ HX_STACK_LINE(252) if (((b < (int)0))){ HX_STACK_LINE(252) return (~(int)(b) - ~(int)(a)); } else{ HX_STACK_LINE(252) return (int)1; } } else{ HX_STACK_LINE(252) if (((b < (int)0))){ HX_STACK_LINE(252) return (int)-1; } else{ HX_STACK_LINE(252) return (a - b); } } HX_STACK_LINE(252) return (int)0; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Int64_obj,uicompare,return ) Int64_obj::Int64_obj() { } Dynamic Int64_obj::__Field(const ::String &inName,bool inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"sub") ) { return sub_dyn(); } if (HX_FIELD_EQ(inName,"low") ) { return low; } break; case 4: if (HX_FIELD_EQ(inName,"high") ) { return high; } break; case 6: if (HX_FIELD_EQ(inName,"divMod") ) { return divMod_dyn(); } break; case 8: if (HX_FIELD_EQ(inName,"toString") ) { return toString_dyn(); } break; case 9: if (HX_FIELD_EQ(inName,"uicompare") ) { return uicompare_dyn(); } } return super::__Field(inName,inCallProp); } Dynamic Int64_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"low") ) { low=inValue.Cast< int >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"high") ) { high=inValue.Cast< int >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void Int64_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_CSTRING("high")); outFields->push(HX_CSTRING("low")); super::__GetFields(outFields); }; static ::String sStaticFields[] = { HX_CSTRING("sub"), HX_CSTRING("divMod"), HX_CSTRING("uicompare"), String(null()) }; #if HXCPP_SCRIPTABLE static hx::StorageInfo sMemberStorageInfo[] = { {hx::fsInt,(int)offsetof(Int64_obj,high),HX_CSTRING("high")}, {hx::fsInt,(int)offsetof(Int64_obj,low),HX_CSTRING("low")}, { hx::fsUnknown, 0, null()} }; #endif static ::String sMemberFields[] = { HX_CSTRING("high"), HX_CSTRING("low"), HX_CSTRING("toString"), String(null()) }; static void sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(Int64_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Int64_obj::__mClass,"__mClass"); }; #endif Class Int64_obj::__mClass; void Int64_obj::__register() { hx::Static(__mClass) = hx::RegisterClass(HX_CSTRING("haxe.Int64"), hx::TCanCast< Int64_obj> ,sStaticFields,sMemberFields, &__CreateEmpty, &__Create, &super::__SGetClass(), 0, sMarkStatics #ifdef HXCPP_VISIT_ALLOCS , sVisitStatics #endif #ifdef HXCPP_SCRIPTABLE , sMemberStorageInfo #endif ); } void Int64_obj::__boot() { } } // end namespace haxe
26.905149
154
0.67224
as3boyan
eb6d1b7f7459ee7406048837a293be48ed03ad0b
1,045
cpp
C++
examples/cancel.cpp
drobison00/taskflow
9415c3b68fd050889f57412394933e94b74755e0
[ "MIT" ]
3,337
2020-06-02T02:04:17.000Z
2022-03-31T19:12:03.000Z
examples/cancel.cpp
drobison00/taskflow
9415c3b68fd050889f57412394933e94b74755e0
[ "MIT" ]
235
2020-06-02T01:26:49.000Z
2022-03-31T01:35:31.000Z
examples/cancel.cpp
drobison00/taskflow
9415c3b68fd050889f57412394933e94b74755e0
[ "MIT" ]
414
2020-06-02T16:25:23.000Z
2022-03-30T09:17:19.000Z
// The program demonstrates how to cancel a submitted taskflow // graph and wait until the cancellation completes. #include <taskflow/taskflow.hpp> int main() { tf::Executor executor; tf::Taskflow taskflow("cancel"); // We create a taskflow graph of 1000 tasks each of 1 second. // Ideally, the taskflow completes in 1000/P seconds, where P // is the number of workers. for(int i=0; i<1000; i++) { taskflow.emplace([](){ std::this_thread::sleep_for(std::chrono::seconds(1)); }); } // submit the taskflow auto beg = std::chrono::steady_clock::now(); tf::Future fu = executor.run(taskflow); // submit a cancel request to cancel all 1000 tasks. fu.cancel(); // wait until the cancellation finishes fu.get(); auto end = std::chrono::steady_clock::now(); // the duration should be much less than 1000 seconds std::cout << "taskflow completes in " << std::chrono::duration_cast<std::chrono::milliseconds>(end-beg).count() << " milliseconds\n"; return 0; }
26.125
85
0.654545
drobison00
eb6eb6a938770cbcec77c90a3e80c07c2173fe77
5,173
cpp
C++
src/openms_gui/source/VISUAL/MISC/FilterableList.cpp
vmusch/OpenMS
3c4a078ad4687677393c138d4acb91bb444a7c7b
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
348
2015-01-17T16:50:12.000Z
2022-03-30T22:55:39.000Z
src/openms_gui/source/VISUAL/MISC/FilterableList.cpp
vmusch/OpenMS
3c4a078ad4687677393c138d4acb91bb444a7c7b
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
4,259
2015-01-01T14:07:54.000Z
2022-03-31T16:49:14.000Z
src/openms_gui/source/VISUAL/MISC/FilterableList.cpp
vmusch/OpenMS
3c4a078ad4687677393c138d4acb91bb444a7c7b
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
266
2015-01-24T14:56:14.000Z
2022-03-30T12:32:35.000Z
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2021. // // This software is released under a three-clause BSD license: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/VISUAL/MISC/FilterableList.h> #include <OpenMS/CONCEPT/Exception.h> #include <ui_FilterableList.h> using namespace std; namespace OpenMS { namespace Internal { FilterableList::FilterableList(QWidget *parent) : QWidget(parent), ui_(new Ui::FilterableList) { ui_->setupUi(this); connect(ui_->filter_text, &QLineEdit::textChanged, this, &FilterableList::filterEdited_); // forward double-clicked signal to outside connect(ui_->list_items, &QListWidget::itemDoubleClicked, [&](QListWidgetItem* item) { emit itemDoubleClicked(item); }); } FilterableList::~FilterableList() { delete ui_; } void FilterableList::setItems(const QStringList& items) { items_ = items; updateInternalList_(); } void FilterableList::setBlacklistItems(const QStringList& bl_items) { blacklist_ = bl_items.toSet(); updateInternalList_(); } void FilterableList::addBlackListItems(const QStringList& items) { blacklist_.unite(items.toSet()); updateInternalList_(); } void FilterableList::removeBlackListItems(const QStringList& outdated_blacklist_items) { // quadratic runtime, but maintains order of items (as opposed to converting to set) for (const auto& bl : outdated_blacklist_items.toSet()) { if (blacklist_.remove(bl) == 0) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value cannot be taken from blacklist. Does not belong to set!", bl.toStdString()); } } updateInternalList_(); } QStringList FilterableList::getSelectedItems() const { QStringList items; for (const auto& item : ui_->list_items->selectedItems()) items << item->text(); return items; } QStringList FilterableList::getAllVisibleItems() const { QStringList items; for (int row = 0; row < ui_->list_items->count(); ++row) items << ui_->list_items->item(row)->text(); return items; } void FilterableList::filterEdited_(const QString& filter_text) { // update list of visible items updateVisibleList_(); // let outside world know about it emit filterChanged(filter_text); } void FilterableList::updateInternalList_() { items_wo_bl_ = items_; // quadratic runtime, but maintains order of items (as opposed to converting to set) for (const auto& bl : blacklist_) { if (items_wo_bl_.removeAll(bl) == 0) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value does not belong to set!", bl.toStdString()); } } updateVisibleList_(); } void FilterableList::updateVisibleList_() { QRegExp regex(ui_->filter_text->text(), Qt::CaseInsensitive, QRegExp::WildcardUnix); ui_->list_items->clear(); ui_->list_items->addItems(items_wo_bl_.filter(regex)); } } //namespace Internal } //namspace OpenMS
36.687943
167
0.639861
vmusch
eb6fc6c492274d8f92c5f9a551cad0bf3b7016df
13,140
cc
C++
src/instructions.cc
DouglasRMiles/QuProlog
798d86f87fb4372b8918ef582ef2f0fc0181af2d
[ "Apache-2.0" ]
5
2019-11-20T02:05:31.000Z
2022-01-06T18:59:16.000Z
src/instructions.cc
logicmoo/QuProlog
798d86f87fb4372b8918ef582ef2f0fc0181af2d
[ "Apache-2.0" ]
null
null
null
src/instructions.cc
logicmoo/QuProlog
798d86f87fb4372b8918ef582ef2f0fc0181af2d
[ "Apache-2.0" ]
2
2022-01-08T13:52:24.000Z
2022-03-07T17:41:37.000Z
// // THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT! // //##Qu-Prolog Copyright.abst## // // $Id: MkInstructions.in,v 1.3 2005/04/12 04:02:48 qp Exp n #include "code.h" #include "defs.h" #include "instructions.h" // Opcode names const char *opnames[] = { /* EMPTY ENTRY */ 0, "put_x_variable", "put_y_variable", "put_x_value", "put_y_value", "put_constant", "put_integer", "put_list", "put_structure", "put_x_object_variable", "put_y_object_variable", "put_x_object_value", "put_y_object_value", "put_quantifier", "check_binder", "put_substitution", "put_x_term_substitution", "put_y_term_substitution", "put_initial_empty_substitution", "get_x_variable", "get_y_variable", "get_x_value", "get_y_value", "get_constant", "get_integer", "get_list", "get_structure", "get_structure_frame", "get_x_object_variable", "get_y_object_variable", "get_x_object_value", "get_y_object_value", "unify_x_variable", "unify_y_variable", "unify_x_value", "unify_y_value", "unify_void", "set_x_variable", "set_y_variable", "set_x_value", "set_y_value", "set_x_object_variable", "set_y_object_variable", "set_x_object_value", "set_y_object_value", "set_constant", "set_integer", "set_void", "set_object_void", "allocate", "deallocate", "call_predicate", "call_address", "call_escape", "execute_predicate", "execute_address", "execute_escape", "noop", "jump", "proceed", "fail", "halt", "exit", "try_me_else", "retry_me_else", "trust_me_else_fail", "try", "retry", "trust", "neck_cut", "get_x_level", "get_y_level", "cut", "switch_on_term", "switch_on_constant", "switch_on_structure", "switch_on_quantifier", "pseudo_instr0", "pseudo_instr1", "pseudo_instr2", "pseudo_instr3", "pseudo_instr4", "pseudo_instr5", "unify_constant", "unify_integer", "unify_x_ref", "unify_y_ref", "db_jump", "db_execute_predicate", "db_execute_address", "db_proceed", "put_double", "get_double", "set_double", "unify_double", "put_string", "get_string", "set_string", "unify_string", }; // Operand types const char *operands[] = { /* EMPTY ENTRY */ 0, /* PUT_X_VARIABLE */ "rr", /* PUT_Y_VARIABLE */ "rr", /* PUT_X_VALUE */ "rr", /* PUT_Y_VALUE */ "rr", /* PUT_CONSTANT */ "cr", /* PUT_INTEGER */ "ir", /* PUT_LIST */ "r", /* PUT_STRUCTURE */ "nr", /* PUT_X_OBJECT_VARIABLE */ "rr", /* PUT_Y_OBJECT_VARIABLE */ "rr", /* PUT_X_OBJECT_VALUE */ "rr", /* PUT_Y_OBJECT_VALUE */ "rr", /* PUT_QUANTIFIER */ "r", /* CHECK_BINDER */ "r", /* PUT_SUBSTITUTION */ "nr", /* PUT_X_TERM_SUBSTITUTION */ "rr", /* PUT_Y_TERM_SUBSTITUTION */ "rr", /* PUT_INITIAL_EMPTY_SUBSTITUTION */ "r", /* GET_X_VARIABLE */ "rr", /* GET_Y_VARIABLE */ "rr", /* GET_X_VALUE */ "rr", /* GET_Y_VALUE */ "rr", /* GET_CONSTANT */ "cr", /* GET_INTEGER */ "ir", /* GET_LIST */ "r", /* GET_STRUCTURE */ "cnr", /* GET_STRUCTURE_FRAME */ "nr", /* GET_X_OBJECT_VARIABLE */ "rr", /* GET_Y_OBJECT_VARIABLE */ "rr", /* GET_X_OBJECT_VALUE */ "rr", /* GET_Y_OBJECT_VALUE */ "rr", /* UNIFY_X_VARIABLE */ "r", /* UNIFY_Y_VARIABLE */ "r", /* UNIFY_X_VALUE */ "r", /* UNIFY_Y_VALUE */ "r", /* UNIFY_VOID */ "n", /* SET_X_VARIABLE */ "r", /* SET_Y_VARIABLE */ "r", /* SET_X_VALUE */ "r", /* SET_Y_VALUE */ "r", /* SET_X_OBJECT_VARIABLE */ "r", /* SET_Y_OBJECT_VARIABLE */ "r", /* SET_X_OBJECT_VALUE */ "r", /* SET_Y_OBJECT_VALUE */ "r", /* SET_CONSTANT */ "c", /* SET_INTEGER */ "i", /* SET_VOID */ "n", /* SET_OBJECT_VOID */ "n", /* ALLOCATE */ "n", /* DEALLOCATE */ "", /* CALL_PREDICATE */ "pnn", /* CALL_ADDRESS */ "an", /* CALL_ESCAPE */ "an", /* EXECUTE_PREDICATE */ "pn", /* EXECUTE_ADDRESS */ "a", /* EXECUTE_ESCAPE */ "a", /* NOOP */ "", /* JUMP */ "a", /* PROCEED */ "", /* FAIL */ "", /* HALT */ "", /* EXIT */ "", /* TRY_ME_ELSE */ "no", /* RETRY_ME_ELSE */ "o", /* TRUST_ME_ELSE_FAIL */ "", /* TRY */ "no", /* RETRY */ "o", /* TRUST */ "o", /* NECK_CUT */ "", /* GET_X_LEVEL */ "r", /* GET_Y_LEVEL */ "r", /* CUT */ "r", /* SWITCH_ON_TERM */ "r", /* SWITCH_ON_CONSTANT */ "rt", /* SWITCH_ON_STRUCTURE */ "rt", /* SWITCH_ON_QUANTIFIER */ "rt", /* PSEUDO_INSTR0 */ "n", /* PSEUDO_INSTR1 */ "nr", /* PSEUDO_INSTR2 */ "nrr", /* PSEUDO_INSTR3 */ "nrrr", /* PSEUDO_INSTR4 */ "nrrrr", /* PSEUDO_INSTR5 */ "nrrrrr", /* UNIFY_CONSTANT */ "c", /* UNIFY_INTEGER */ "i", /* UNIFY_X_REF */ "r", /* UNIFY_Y_REF */ "r", /* DB_JUMP */ "naaa", /* DB_EXECUTE_PREDICATE */ "pn", /* DB_EXECUTE_ADDRESS */ "a", /* DB_PROCEED */ "", /* PUT_DOUBLE */ "dr", /* GET_DOUBLE */ "dr", /* SET_DOUBLE */ "d", /* UNIFY_DOUBLE */ "d", /* PUT_STRING */ "r", /* GET_STRING */ "r", /* SET_STRING */ "", /* UNIFY_STRING */ "", }; // Instruction sizes const word32 opsizes[] = { /* EMPTY ENTRY */ 0, /* PUT_X_VARIABLE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_Y_VARIABLE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_X_VALUE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_Y_VALUE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_CONSTANT */ Code::SIZE_OF_CONSTANT + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_INTEGER */ Code::SIZE_OF_INTEGER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_LIST */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_STRUCTURE */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_X_OBJECT_VARIABLE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_Y_OBJECT_VARIABLE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_X_OBJECT_VALUE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_Y_OBJECT_VALUE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_QUANTIFIER */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* CHECK_BINDER */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_SUBSTITUTION */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_X_TERM_SUBSTITUTION */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_Y_TERM_SUBSTITUTION */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PUT_INITIAL_EMPTY_SUBSTITUTION */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_X_VARIABLE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_Y_VARIABLE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_X_VALUE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_Y_VALUE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_CONSTANT */ Code::SIZE_OF_CONSTANT + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_INTEGER */ Code::SIZE_OF_INTEGER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_LIST */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_STRUCTURE */ Code::SIZE_OF_CONSTANT + Code::SIZE_OF_NUMBER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_STRUCTURE_FRAME */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_X_OBJECT_VARIABLE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_Y_OBJECT_VARIABLE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_X_OBJECT_VALUE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_Y_OBJECT_VALUE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* UNIFY_X_VARIABLE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* UNIFY_Y_VARIABLE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* UNIFY_X_VALUE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* UNIFY_Y_VALUE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* UNIFY_VOID */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_INSTRUCTION, /* SET_X_VARIABLE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* SET_Y_VARIABLE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* SET_X_VALUE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* SET_Y_VALUE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* SET_X_OBJECT_VARIABLE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* SET_Y_OBJECT_VARIABLE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* SET_X_OBJECT_VALUE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* SET_Y_OBJECT_VALUE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* SET_CONSTANT */ Code::SIZE_OF_CONSTANT + Code::SIZE_OF_INSTRUCTION, /* SET_INTEGER */ Code::SIZE_OF_INTEGER + Code::SIZE_OF_INSTRUCTION, /* SET_VOID */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_INSTRUCTION, /* SET_OBJECT_VOID */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_INSTRUCTION, /* ALLOCATE */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_INSTRUCTION, /* DEALLOCATE */ Code::SIZE_OF_INSTRUCTION, /* CALL_PREDICATE */ Code::SIZE_OF_PRED + Code::SIZE_OF_NUMBER + Code::SIZE_OF_NUMBER + Code::SIZE_OF_INSTRUCTION, /* CALL_ADDRESS */ Code::SIZE_OF_ADDRESS + Code::SIZE_OF_NUMBER + Code::SIZE_OF_INSTRUCTION, /* CALL_ESCAPE */ Code::SIZE_OF_ADDRESS + Code::SIZE_OF_NUMBER + Code::SIZE_OF_INSTRUCTION, /* EXECUTE_PREDICATE */ Code::SIZE_OF_PRED + Code::SIZE_OF_NUMBER + Code::SIZE_OF_INSTRUCTION, /* EXECUTE_ADDRESS */ Code::SIZE_OF_ADDRESS + Code::SIZE_OF_INSTRUCTION, /* EXECUTE_ESCAPE */ Code::SIZE_OF_ADDRESS + Code::SIZE_OF_INSTRUCTION, /* NOOP */ Code::SIZE_OF_INSTRUCTION, /* JUMP */ Code::SIZE_OF_ADDRESS + Code::SIZE_OF_INSTRUCTION, /* PROCEED */ Code::SIZE_OF_INSTRUCTION, /* FAIL */ Code::SIZE_OF_INSTRUCTION, /* HALT */ Code::SIZE_OF_INSTRUCTION, /* EXIT */ Code::SIZE_OF_INSTRUCTION, /* TRY_ME_ELSE */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_OFFSET + Code::SIZE_OF_INSTRUCTION, /* RETRY_ME_ELSE */ Code::SIZE_OF_OFFSET + Code::SIZE_OF_INSTRUCTION, /* TRUST_ME_ELSE_FAIL */ Code::SIZE_OF_INSTRUCTION, /* TRY */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_OFFSET + Code::SIZE_OF_INSTRUCTION, /* RETRY */ Code::SIZE_OF_OFFSET + Code::SIZE_OF_INSTRUCTION, /* TRUST */ Code::SIZE_OF_OFFSET + Code::SIZE_OF_INSTRUCTION, /* NECK_CUT */ Code::SIZE_OF_INSTRUCTION, /* GET_X_LEVEL */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_Y_LEVEL */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* CUT */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* SWITCH_ON_TERM */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* SWITCH_ON_CONSTANT */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_TABLE_SIZE + Code::SIZE_OF_INSTRUCTION, /* SWITCH_ON_STRUCTURE */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_TABLE_SIZE + Code::SIZE_OF_INSTRUCTION, /* SWITCH_ON_QUANTIFIER */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_TABLE_SIZE + Code::SIZE_OF_INSTRUCTION, /* PSEUDO_INSTR0 */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_INSTRUCTION, /* PSEUDO_INSTR1 */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PSEUDO_INSTR2 */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PSEUDO_INSTR3 */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PSEUDO_INSTR4 */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* PSEUDO_INSTR5 */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* UNIFY_CONSTANT */ Code::SIZE_OF_CONSTANT + Code::SIZE_OF_INSTRUCTION, /* UNIFY_INTEGER */ Code::SIZE_OF_INTEGER + Code::SIZE_OF_INSTRUCTION, /* UNIFY_X_REF */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* UNIFY_Y_REF */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* DB_JUMP */ Code::SIZE_OF_NUMBER + Code::SIZE_OF_ADDRESS + Code::SIZE_OF_ADDRESS + Code::SIZE_OF_ADDRESS + Code::SIZE_OF_INSTRUCTION, /* DB_EXECUTE_PREDICATE */ Code::SIZE_OF_PRED + Code::SIZE_OF_NUMBER + Code::SIZE_OF_INSTRUCTION, /* DB_EXECUTE_ADDRESS */ Code::SIZE_OF_ADDRESS + Code::SIZE_OF_INSTRUCTION, /* DB_PROCEED */ Code::SIZE_OF_INSTRUCTION, /* PUT_DOUBLE */ Code::SIZE_OF_DOUBLE + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_DOUBLE */ Code::SIZE_OF_DOUBLE + Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* SET_DOUBLE */ Code::SIZE_OF_DOUBLE + Code::SIZE_OF_INSTRUCTION, /* UNIFY_DOUBLE */ Code::SIZE_OF_DOUBLE + Code::SIZE_OF_INSTRUCTION, /* PUT_STRING */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* GET_STRING */ Code::SIZE_OF_REGISTER + Code::SIZE_OF_INSTRUCTION, /* SET_STRING */ Code::SIZE_OF_INSTRUCTION, /* UNIFY_STRING */ Code::SIZE_OF_INSTRUCTION, };
40.934579
196
0.708828
DouglasRMiles
eb74302c7bdaa43e9a64f240e5e5f0ddd222b000
2,389
cpp
C++
src/user.cpp
hvlds/bgmaker
a815d1bff9ccd3082497eae13352663817aff10a
[ "MIT" ]
null
null
null
src/user.cpp
hvlds/bgmaker
a815d1bff9ccd3082497eae13352663817aff10a
[ "MIT" ]
null
null
null
src/user.cpp
hvlds/bgmaker
a815d1bff9ccd3082497eae13352663817aff10a
[ "MIT" ]
null
null
null
#include "user.hpp" #include <iostream> #include <string> #include <toml.hpp> #include <vector> #include "lsystem.hpp" UserInfo::UserInfo() { this->general_info.height = 1080; this->general_info.width = 1920; this->is_preview = false; this->stroke_color = "#FFFFFF"; this->general_info.background_color = "#546E7A"; this->general_info.output_file = "background.png"; } void UserInfo::create_empty_canvas() { this->image = std::make_shared<Magick::Image>( Magick::Geometry(this->general_info.width, this->general_info.height), Magick::Color(this->general_info.background_color)); } void UserInfo::read_config(std::string config_path) { const auto data = toml::parse(config_path); if (data.contains("general")) { auto general_config = toml::find<config::General>(data, "general"); this->general_info = general_config; } for (auto drawing_option : this->drawing_options) { if (data.contains(drawing_option)) { const auto& lsystems = toml::find(data, drawing_option); auto key = drawing_option; std::vector<config::LSystem> drawable_configs; for (const auto& item : lsystems.as_table()) { std::cout << item.first << std::endl; auto drawable_config = toml::find<config::LSystem>(lsystems, item.first); drawable_configs.push_back(drawable_config); } this->drawable_config.insert( {key, drawable_configs}); } } } void UserInfo::draw() { this->create_empty_canvas(); int width = this->general_info.width; int height = this->general_info.height; for (auto item : this->drawable_config) { auto name = item.first; auto configs = item.second; if (configs.size() > 0 && name == "lsystem") { for (auto config : configs) { auto lsystem_type = config.type; LSystem lsystem = LSystem(config); lsystem.set_properties(lsystem_type); lsystem.draw(this->image, width, height); } } } // Temporarily export as file anyway this->image->write(this->general_info.output_file); if (this->is_preview == true) { this->image->display(); } else { this->image->write(this->general_info.output_file); } }
32.283784
89
0.611134
hvlds
eb76b2ec86edd840107d37bf541e66cc9c3f4937
427
cpp
C++
src/simple_psh/main/cpp/main.cpp
jmprathab/pshell
8b9955c96b9c185a6d66314e6b692d932e535109
[ "Apache-2.0" ]
null
null
null
src/simple_psh/main/cpp/main.cpp
jmprathab/pshell
8b9955c96b9c185a6d66314e6b692d932e535109
[ "Apache-2.0" ]
null
null
null
src/simple_psh/main/cpp/main.cpp
jmprathab/pshell
8b9955c96b9c185a6d66314e6b692d932e535109
[ "Apache-2.0" ]
null
null
null
#define SIMPLEPSH_MODULE_EXPORT #include <simplepsh.hpp> #include <cstdlib> #include <memory> #include <simple_psh/main/headers/noopinterpreter.hpp> class PSH; int main(int argc, char **argv) { std::unique_ptr<Interpreter> interpreter(new NoOpInterpreter()); std::unique_ptr<PSH> psh(new SimplePSH(std::move(interpreter))); psh->initialize(); psh->execute(); psh->terminate(); return EXIT_SUCCESS; }
23.722222
68
0.716628
jmprathab
eb7b35ba781b293e0ed315a1680fa5c4270528e6
621
cpp
C++
Source-simplified/Computational Geometry/Two-dimension/Graham Scanning Algorithm.cpp
lmxyy/Code-Library-for-lmxyy
e7740402076588624e2fb3dff7ed916851b2eb76
[ "MIT" ]
3
2019-06-27T14:14:32.000Z
2021-01-11T11:36:47.000Z
Source-simplified/Computational Geometry/Two-dimension/Graham Scanning Algorithm.cpp
lmxyy/Code-Library-for-lmxyy
e7740402076588624e2fb3dff7ed916851b2eb76
[ "MIT" ]
null
null
null
Source-simplified/Computational Geometry/Two-dimension/Graham Scanning Algorithm.cpp
lmxyy/Code-Library-for-lmxyy
e7740402076588624e2fb3dff7ed916851b2eb76
[ "MIT" ]
1
2021-04-27T00:26:54.000Z
2021-04-27T00:26:54.000Z
//凸包上最大四边形面积 int N,M; double ans; struct Point { double x,y; }P[maxn],convex[maxn]; inline void Graham() { ConvexHull(); for (int i = 1;i <= M;++i) convex[i+M] = convex[i]; int p1,p2,p3,p4; for (p1 = 1;p1 <= M;++p1) { p2 = p1+1; p3 = p2+1; p4 = p3+1; for (;p3 < p1+M-1;++p3) { Point v = convex[p3]-convex[p1]; while (p2 < p3&&fabs((convex[p2]-convex[p1])/v) < fabs((convex[p2+1]-convex[p1])/v)) ++p2; while (p4 < p1+M&&fabs((convex[p4]-convex[p1])/v) < fabs((convex[p4+1]-convex[p1])/v)) ++p4; ans = max(ans,fabs((convex[p2]-convex[p1])/v)+fabs((convex[p4]-convex[p1])/v)); } } ans = ans/2; }
27
95
0.558776
lmxyy
eb7b4e40248e7269f950ece536e2b5c4896a2e4b
1,213
hpp
C++
src/sdl2/sdl.hpp
fl4shk/liborangepower
a2aa99a7f9b35cc06ad78976406432913718800b
[ "MIT" ]
2
2019-01-02T02:07:44.000Z
2022-03-21T10:22:18.000Z
src/sdl2/sdl.hpp
fl4shk/liborangepower
a2aa99a7f9b35cc06ad78976406432913718800b
[ "MIT" ]
null
null
null
src/sdl2/sdl.hpp
fl4shk/liborangepower
a2aa99a7f9b35cc06ad78976406432913718800b
[ "MIT" ]
1
2019-01-01T02:51:25.000Z
2019-01-01T02:51:25.000Z
#ifndef liborangepower_sdl2_sdl_hpp #define liborangepower_sdl2_sdl_hpp #include "../misc/misc_includes.hpp" #include "../gen_class_innards_defines.hpp" #include <algorithm> #include <SDL.h> namespace liborangepower { namespace sdl { //template<typename Type> //class StructWrapper //{ //public: // typedefs // using Dtor = void (*)(Type* self); //private: // variables // Type* _self; // Dtor _dtor; //public: // functions // inline StructWrapper(Type* self, Dtor dtor) // : _self(self), _dtor(dtor) // { // } // virtual inline ~StructWrapper() // { // _dtor(_self); // } //}; class QuitUponDtor final { private: // variables bool _valid; public: // functions inline QuitUponDtor(bool s_valid=true) : _valid(s_valid) { } inline QuitUponDtor(const QuitUponDtor& to_copy) = delete; inline QuitUponDtor(QuitUponDtor&& to_move) { *this = std::move(to_move); } inline ~QuitUponDtor() { SDL_Quit(); } inline QuitUponDtor& operator = (const QuitUponDtor& to_copy) = delete; inline QuitUponDtor& operator = (QuitUponDtor&& to_move) { std::swap(_valid, to_move._valid); return *this; } }; } // namespace sdl } // namespace liborangepower #endif // liborangepower_sdl2_sdl_hpp
17.838235
62
0.694971
fl4shk
eb7b79a45bd23a062fb0939d98e0c4b3dbffc214
9,418
cpp
C++
coopserver/CoopMgr/Event.cpp
vinthewrench/chickencoop
7338f0e800db7e1379bf15f0f2750c0959b2a641
[ "MIT" ]
1
2022-02-03T21:33:30.000Z
2022-02-03T21:33:30.000Z
coopserver/CoopMgr/Event.cpp
vinthewrench/chickencoop
7338f0e800db7e1379bf15f0f2750c0959b2a641
[ "MIT" ]
null
null
null
coopserver/CoopMgr/Event.cpp
vinthewrench/chickencoop
7338f0e800db7e1379bf15f0f2750c0959b2a641
[ "MIT" ]
null
null
null
// // Event.cpp // coopserver // // Created by Vincent Moscaritolo on 12/29/21. // #include "Event.hpp" #include "TimeStamp.hpp" using namespace nlohmann; constexpr string_view JSON_ARG_ACTION = "action"; constexpr string_view JSON_ARG_TRIGGER = "trigger"; constexpr string_view JSON_ARG_EVENTID = "eventID"; constexpr string_view JSON_ARG_NAME = "name"; constexpr string_view JSON_TIME_BASE = "timeBase"; constexpr string_view JSON_TIME_OFFSET = "mins"; constexpr string_view JSON_ARG_EVENT = "event"; constexpr string_view JSON_EVENT_STARTUP = "startup"; constexpr string_view JSON_EVENT_SHUTDOWN = "shutdown"; // MARK: - EventTrigger() EventTrigger::EventTrigger(app_event_t appEvent){ _eventType = EVENT_TYPE_APP; _appEvent = appEvent; } EventTrigger::EventTrigger(){ _eventType = EVENT_TYPE_UNKNOWN; } EventTrigger::EventTrigger(tod_offset_t timeBase, int16_t timeOfDay){ _eventType = EVENT_TYPE_TIME; _timeEvent.timeBase = timeBase; _timeEvent.timeOfDay = timeOfDay; _timeEvent.lastRun = 0; } void EventTrigger::copy(const EventTrigger &evt1, EventTrigger *evt2){ evt2->_eventType = evt1._eventType; switch (evt1._eventType) { case EVENT_TYPE_TIME: evt2->_timeEvent = evt1._timeEvent; break; case EVENT_TYPE_APP: evt2->_appEvent = evt1._appEvent; break; default: break; } } EventTrigger::EventTrigger(nlohmann::json j){ initWithJSON(j); } EventTrigger::EventTrigger(std::string str){ _eventType = EVENT_TYPE_UNKNOWN; json j; j = json::parse(str); initWithJSON(j); } void EventTrigger::initWithJSON(nlohmann::json j){ _eventType = EVENT_TYPE_UNKNOWN; if( j.contains(string(JSON_TIME_OFFSET)) && j.contains(string(JSON_TIME_BASE))) { _eventType = EVENT_TYPE_TIME; } else if(j.contains(string(JSON_ARG_EVENT))){ _eventType = EVENT_TYPE_APP; _appEvent = APP_EVENT_INVALID; } if(_eventType == EVENT_TYPE_TIME) { _timeEvent.timeBase = TOD_INVALID; _timeEvent.timeOfDay = 0; _timeEvent.lastRun = 0; if( j.contains(string(JSON_TIME_BASE)) && j.at(string(JSON_TIME_BASE)).is_number()){ _timeEvent.timeBase = j.at(string(JSON_TIME_BASE)); } if( j.contains(string(JSON_TIME_OFFSET)) && j.at(string(JSON_TIME_OFFSET)).is_number()){ _timeEvent.timeOfDay = j.at(string(JSON_TIME_OFFSET)); } } else if(_eventType == EVENT_TYPE_APP) { if( j.contains(string(JSON_ARG_EVENT)) && j.at(string(JSON_ARG_EVENT)).is_string()){ string str = j.at(string(JSON_ARG_EVENT)); if(str == JSON_EVENT_STARTUP ){ _appEvent = APP_EVENT_STARTUP; } else if(str == JSON_EVENT_SHUTDOWN ){ _appEvent = APP_EVENT_SHUTDOWN; } } } } nlohmann::json EventTrigger::JSON(){ json j; switch(_eventType){ case EVENT_TYPE_TIME: { json j1; j1[string(JSON_TIME_OFFSET)] = _timeEvent.timeOfDay; j1[string(JSON_TIME_BASE)] = _timeEvent.timeBase; j = j1; } break; case EVENT_TYPE_APP: { json j1; switch (_appEvent) { case APP_EVENT_STARTUP: j1[string(JSON_ARG_EVENT)] = JSON_EVENT_STARTUP; break; case APP_EVENT_SHUTDOWN: j1[string(JSON_ARG_EVENT)] = JSON_EVENT_SHUTDOWN; break; default: break; } j = j1; } break; default:; } return j; } const std::string EventTrigger:: printString(){ std::ostringstream oss; using namespace timestamp; auto j = JSON(); if(_eventType == EVENT_TYPE_TIME){ solarTimes_t solar; SolarTimeMgr::shared()->getSolarEvents(solar); int16_t minsFromMidnight = 0; // when does it need to run today calculateTriggerTime(solar,minsFromMidnight); time_t schedTime = solar.previousMidnight + (minsFromMidnight * SECS_PER_MIN) ; string timeString = TimeStamp(schedTime).ClockString(); string offsetMinutes = ""; if(_timeEvent.timeOfDay > 0) offsetMinutes = " + " + to_string(_timeEvent.timeOfDay) + " minutes"; else if(_timeEvent.timeOfDay < 0) offsetMinutes = " - " + to_string(abs(_timeEvent.timeOfDay)) + " minutes"; switch(_timeEvent.timeBase){ case TOD_SUNRISE: oss << timeString << " (Sunrise" << offsetMinutes << ")" ; break; case TOD_SUNSET: oss << timeString << " (Sunset" << offsetMinutes << ")" ; break; case TOD_CIVIL_SUNRISE: oss << timeString << " (Civil Sunrise" << offsetMinutes << ")" ; ; break; case TOD_CIVIL_SUNSET: oss << timeString << " (Civil Sunset" << offsetMinutes << ")"; break; case TOD_ABSOLUTE: oss << timeString; break; case TOD_INVALID: oss << "Invalid Time:"; break; } } else { oss << j.dump(); } return oss.str(); } bool EventTrigger::isValid(){ return (_eventType != EVENT_TYPE_UNKNOWN); } bool EventTrigger::isTimed(){ return (_eventType == EVENT_TYPE_TIME); } bool EventTrigger::setLastRun(time_t time){ if(_eventType == EVENT_TYPE_TIME){ _timeEvent.lastRun = time; return true; } else return false; } bool EventTrigger::shouldTriggerInFuture(const solarTimes_t &solar, time_t localNow){ bool result = false; if(_eventType == EVENT_TYPE_TIME){ int16_t minsFromMidnight = 0; // when does it need to run today if(calculateTriggerTime(solar,minsFromMidnight)) { time_t schedTime = solar.previousMidnight + (minsFromMidnight * SECS_PER_MIN) ; // // printf("\n sched: %s \n", timestamp::TimeStamp(schedTime).ClockString().c_str()); // printf(" now: %s \n", timestamp::TimeStamp(localNow).ClockString().c_str()); // if( schedTime > localNow) { result = true; } }; } return result; } bool EventTrigger::shouldTriggerFromAppEvent(app_event_t a){ bool result = false; if(_eventType == EVENT_TYPE_APP){ return (_appEvent == a); } return result; } bool EventTrigger::shouldTriggerFromTimeEvent(const solarTimes_t &solar, time_t localNow){ bool result = false; if(_eventType == EVENT_TYPE_TIME){ int16_t minsFromMidnight = 0; // when does it need to run today if(calculateTriggerTime(solar,minsFromMidnight)) { time_t schedTime = solar.previousMidnight + (minsFromMidnight * SECS_PER_MIN) ; // // printf("\n sched: %s \n", timestamp::TimeStamp(schedTime).ClockString().c_str()); // printf(" now: %s \n", timestamp::TimeStamp(localNow).ClockString().c_str()); // if( schedTime < localNow) { if( _timeEvent.lastRun == 0 || _timeEvent.lastRun < solar.previousMidnight ) result = true; } }; } return result; } bool EventTrigger::calculateTriggerTime(const solarTimes_t &solar, int16_t &minsFromMidnight) { bool result = false; if(_eventType == EVENT_TYPE_TIME){ int16_t actualTime = _timeEvent.timeOfDay; switch(_timeEvent.timeBase){ case TOD_SUNRISE: actualTime = solar.sunriseMins + actualTime; result = true; break; case TOD_SUNSET: actualTime = solar.sunSetMins + actualTime; result = true; break; case TOD_CIVIL_SUNRISE: actualTime = solar.civilSunRiseMins + actualTime; result = true; break; case TOD_CIVIL_SUNSET: actualTime = solar.civilSunSetMins + actualTime; result = true; break; case TOD_ABSOLUTE: actualTime = actualTime; result = true; break; case TOD_INVALID: break; } if(result) minsFromMidnight = actualTime; } return result; } // MARK: - Event() bool str_to_EventID(const char* str, eventID_t *eventIDOut){ bool status = false; eventID_t val = 0; status = sscanf(str, "%hx", &val) == 1; if(eventIDOut) { *eventIDOut = val; } return status; }; string EventID_to_string(eventID_t eventID){ return to_hex<unsigned short>(eventID); } Event::Event(){ _rawEventID = 0; _trigger = EventTrigger(); _action = Action(); } Event::Event(EventTrigger trigger, Action action){ _rawEventID = 0; _trigger = trigger; _action = action; } Event::Event(EventTrigger trigger, Action action, std::string name){ _rawEventID = 0; _trigger = trigger; _action = action; if(!name.empty()) _name = name; } Event::Event(nlohmann::json j){ _rawEventID = 0; if( j.contains(JSON_ARG_TRIGGER) && j.at(string(JSON_ARG_TRIGGER)).is_object()) { auto jT = j.at(string(JSON_ARG_TRIGGER)); _trigger = EventTrigger(jT); } if( j.contains(JSON_ARG_ACTION) && j.at(string(JSON_ARG_ACTION)).is_object()) { auto jA = j.at(string(JSON_ARG_ACTION)); _action = Action(jA); } if(j.contains(JSON_ARG_NAME) && j.at(string(JSON_ARG_NAME)).is_string()) { auto jS = j.at(string(JSON_ARG_NAME)); _name = jS; } if(j.contains(JSON_ARG_EVENTID) && j.at(string(JSON_ARG_EVENTID)).is_string()) { string jID = j.at(string(JSON_ARG_EVENTID)); str_to_EventID(jID.c_str(), &_rawEventID); } } void Event::copy(const Event &evt1, Event *evt2){ evt2->_rawEventID = evt1._rawEventID; evt2->_name = evt1._name; evt2->_trigger = evt1._trigger; evt2->_action = evt1._action; } nlohmann::json Event::JSON(){ json j; auto jA = _action.JSON(); auto jT = _trigger.JSON(); j[string(JSON_ARG_ACTION)] = jA; j[string(JSON_ARG_TRIGGER)] = jT; j[string(JSON_ARG_EVENTID)] = to_hex<unsigned short>(_rawEventID); if(!_name.empty()) j[string(JSON_ARG_NAME)] = _name; return j; } bool Event::isValid(){ return (_action.isValid() && _trigger.isValid()); }
21.069351
95
0.673285
vinthewrench
eb8000383b8fa8044f48e03041fbca5dd4591579
5,341
cpp
C++
vpr/src/place/compressed_grid.cpp
dpbaines/vtr-verilog-to-routing
cea4b63689db11816027aea23b6690af1c384f2d
[ "MIT" ]
32
2018-01-10T11:47:44.000Z
2022-03-18T15:17:36.000Z
vpr/src/place/compressed_grid.cpp
dpbaines/vtr-verilog-to-routing
cea4b63689db11816027aea23b6690af1c384f2d
[ "MIT" ]
179
2018-08-22T22:48:59.000Z
2021-10-10T10:00:56.000Z
vpr/src/place/compressed_grid.cpp
dpbaines/vtr-verilog-to-routing
cea4b63689db11816027aea23b6690af1c384f2d
[ "MIT" ]
25
2019-02-10T16:55:40.000Z
2021-08-29T05:28:47.000Z
#include "compressed_grid.h" #include "arch_util.h" #include "globals.h" std::vector<t_compressed_block_grid> create_compressed_block_grids() { auto& device_ctx = g_vpr_ctx.device(); auto& grid = device_ctx.grid; //Collect the set of x/y locations for each instace of a block type std::vector<std::vector<vtr::Point<int>>> block_locations(device_ctx.logical_block_types.size()); for (size_t x = 0; x < grid.width(); ++x) { for (size_t y = 0; y < grid.height(); ++y) { const t_grid_tile& tile = grid[x][y]; if (tile.width_offset == 0 && tile.height_offset == 0) { auto equivalent_sites = get_equivalent_sites_set(tile.type); for (auto& block : equivalent_sites) { //Only record at block root location block_locations[block->index].emplace_back(x, y); } } } } std::vector<t_compressed_block_grid> compressed_type_grids(device_ctx.logical_block_types.size()); for (const auto& logical_block : device_ctx.logical_block_types) { auto compressed_block_grid = create_compressed_block_grid(block_locations[logical_block.index]); for (const auto& physical_tile : logical_block.equivalent_tiles) { std::vector<int> compatible_sub_tiles; // Build a vector to store all the sub tile indices that are compatible with the // (physical_tile, logical_block) pair. // // Given that a logical block can potentially be compatible with only a subset of the // sub tiles of a physical tile, we need to ensure which sub tile locations are part of // this subset. for (int isub_tile = 0; isub_tile < physical_tile->capacity; isub_tile++) { if (is_sub_tile_compatible(physical_tile, &logical_block, isub_tile)) { compatible_sub_tiles.push_back(isub_tile); } } // For each of physical tiles compatible with the current logical block, create add an entry // to the compatible sub tiles map with the physical tile index and the above generated vector. compressed_block_grid.compatible_sub_tiles_for_tile.insert({physical_tile->index, compatible_sub_tiles}); } compressed_type_grids[logical_block.index] = compressed_block_grid; } return compressed_type_grids; } //Given a set of locations, returns a 2D matrix in a compressed space t_compressed_block_grid create_compressed_block_grid(const std::vector<vtr::Point<int>>& locations) { t_compressed_block_grid compressed_grid; if (locations.empty()) { return compressed_grid; } { std::vector<int> x_locs; std::vector<int> y_locs; //Record all the x/y locations seperately for (auto point : locations) { x_locs.emplace_back(point.x()); y_locs.emplace_back(point.y()); } //Uniquify x/y locations std::sort(x_locs.begin(), x_locs.end()); x_locs.erase(unique(x_locs.begin(), x_locs.end()), x_locs.end()); std::sort(y_locs.begin(), y_locs.end()); y_locs.erase(unique(y_locs.begin(), y_locs.end()), y_locs.end()); //The index of an x-position in x_locs corresponds to it's compressed //x-coordinate (similarly for y) compressed_grid.compressed_to_grid_x = x_locs; compressed_grid.compressed_to_grid_y = y_locs; } // //Build the compressed grid // //Create a full/dense x-dimension (since there must be at least one //block per x location) compressed_grid.grid.resize(compressed_grid.compressed_to_grid_x.size()); //Fill-in the y-dimensions // //Note that we build the y-dimension sparsely (using a flat map), since //there may not be full columns of blocks at each x location, this makes //it efficient to find the non-empty blocks in the y dimension for (auto point : locations) { //Determine the compressed indices in the x & y dimensions auto x_itr = std::lower_bound(compressed_grid.compressed_to_grid_x.begin(), compressed_grid.compressed_to_grid_x.end(), point.x()); int cx = std::distance(compressed_grid.compressed_to_grid_x.begin(), x_itr); auto y_itr = std::lower_bound(compressed_grid.compressed_to_grid_y.begin(), compressed_grid.compressed_to_grid_y.end(), point.y()); int cy = std::distance(compressed_grid.compressed_to_grid_y.begin(), y_itr); VTR_ASSERT(cx >= 0 && cx < (int)compressed_grid.compressed_to_grid_x.size()); VTR_ASSERT(cy >= 0 && cy < (int)compressed_grid.compressed_to_grid_y.size()); VTR_ASSERT(compressed_grid.compressed_to_grid_x[cx] == point.x()); VTR_ASSERT(compressed_grid.compressed_to_grid_y[cy] == point.y()); auto result = compressed_grid.grid[cx].insert(std::make_pair(cy, t_type_loc(point.x(), point.y()))); VTR_ASSERT_MSG(result.second, "Duplicates should not exist in compressed grid space"); } return compressed_grid; } int grid_to_compressed(const std::vector<int>& coords, int point) { auto itr = std::lower_bound(coords.begin(), coords.end(), point); VTR_ASSERT(*itr == point); return std::distance(coords.begin(), itr); }
42.055118
139
0.661299
dpbaines
eb83cd51ea2785478bd632024f02f068fff82b0d
2,585
cpp
C++
src/the_framework/unittest/utest_utility_fct.cpp
schnedann/linebuffer
494745a6d83eef1adebf9a6e30c636a8edd5f0c2
[ "BSD-3-Clause" ]
null
null
null
src/the_framework/unittest/utest_utility_fct.cpp
schnedann/linebuffer
494745a6d83eef1adebf9a6e30c636a8edd5f0c2
[ "BSD-3-Clause" ]
null
null
null
src/the_framework/unittest/utest_utility_fct.cpp
schnedann/linebuffer
494745a6d83eef1adebf9a6e30c636a8edd5f0c2
[ "BSD-3-Clause" ]
null
null
null
/**************************************** * Includes ****************************************/ #include <iostream> #include <iomanip> #include <random> #include <cmath> #include "catch.hpp" #include "dtypes.h" #include "utility_fct.h" /**************************************** * Defines ****************************************/ /**************************************** * Namespaces ****************************************/ using namespace std; /**************************************** * local Prototypes ****************************************/ /**************************************** * Global Constants ****************************************/ /**************************************** * Typedefs ****************************************/ //--- Code TEST_CASE("Utility::Numbers","[utility,numbers]"){ SECTION("Utility::Numbers::gethexdigitscount"){ REQUIRE( 1 == Utility::Numbers::gethexdigitscount<u32>(0) ); REQUIRE( 1 == Utility::Numbers::gethexdigitscount<u32>(15) ); REQUIRE( 2 == Utility::Numbers::gethexdigitscount<u32>(16) ); REQUIRE( 2 == Utility::Numbers::gethexdigitscount<u32>(255) ); REQUIRE( 3 == Utility::Numbers::gethexdigitscount<u32>(256) ); REQUIRE( 3 == Utility::Numbers::gethexdigitscount<u32>(4095) ); REQUIRE( 4 == Utility::Numbers::gethexdigitscount<u32>(4096) ); REQUIRE( 4 == Utility::Numbers::gethexdigitscount<u32>(65535) ); REQUIRE( 5 == Utility::Numbers::gethexdigitscount<u32>(65536) ); REQUIRE( 5 == Utility::Numbers::gethexdigitscount<u32>(1048575) ); REQUIRE( 6 == Utility::Numbers::gethexdigitscount<u32>(1048576) ); REQUIRE( 6 == Utility::Numbers::gethexdigitscount<u32>(16777215) ); } SECTION("Utility::Numbers::estimatedecimalplaces"){ REQUIRE( 1 == Utility::Numbers::gethexdigitscount<u32>(0) ); REQUIRE( 1 == Utility::Numbers::gethexdigitscount<u32>(9) ); REQUIRE( 2 == Utility::Numbers::gethexdigitscount<u32>(10) ); REQUIRE( 2 == Utility::Numbers::gethexdigitscount<u32>(99) ); REQUIRE( 3 == Utility::Numbers::gethexdigitscount<u32>(100) ); REQUIRE( 3 == Utility::Numbers::gethexdigitscount<u32>(999) ); REQUIRE( 4 == Utility::Numbers::gethexdigitscount<u32>(1000) ); REQUIRE( 4 == Utility::Numbers::gethexdigitscount<u32>(9999) ); REQUIRE( 5 == Utility::Numbers::gethexdigitscount<u32>(10000) ); REQUIRE( 5 == Utility::Numbers::gethexdigitscount<u32>(99999) ); REQUIRE( 6 == Utility::Numbers::gethexdigitscount<u32>(100000) ); REQUIRE( 6 == Utility::Numbers::gethexdigitscount<u32>(999999) ); } }
33.141026
71
0.543133
schnedann
eb851c5766b50948429d1676c386f2daec39f294
13,551
cpp
C++
chapter03/resolve/resolver.cpp
caigen/windows-network-programming
367abd891203528a1405012df0551e21a239f131
[ "MIT" ]
null
null
null
chapter03/resolve/resolver.cpp
caigen/windows-network-programming
367abd891203528a1405012df0551e21a239f131
[ "MIT" ]
null
null
null
chapter03/resolve/resolver.cpp
caigen/windows-network-programming
367abd891203528a1405012df0551e21a239f131
[ "MIT" ]
null
null
null
// // Sample: Illustrates getaddrinfo and getnameinfo // // Files: // resolver.cpp - this file // // Description: // This sample illustrates how to use the new name resolution APIs: // getaddrinfo and getnameinfo. This sample takes a hostname or address // and performs an address resolution via getaddrinfo. This lookup will // return one or more binary addresses which will then be passed to // getnameinfo to perform a reverse lookup. The results of each query // are displayed to the console. // // Complile: // cl.exe -o resolver.exe resolver.cpp ws2_32.lib // // Usage: // resolver.exe [options] // -n name Host name to resolve // -s port/service Service name or port number to resolve // -a address-family Preferred address family // 4 IPv4 (AF_INET) // 6 IPv6 (AF_INET6) // -t socket-type Preferred socket type // stream Stream socket (SOCK_STREAM) // dgram Datagram socket (SOCK_DGRAM) // -p protocol Preferred protocol // tcp TCP (IPPROTO_TCP) // udp UDP (IPPROTO_UDP) // -f flag Flags passed to getname info (options may be present multiple times) // nofqdn NI_NOFQDN // numerichost NI_NUMERICHOST // namereqd NI_NAMEREQD // numericserv NI_NUMERICSERV // dgram NI_DGRAM // -b Obtain the bind address for the given address family (i.e. AI_PASSIVE) // #include <winsock2.h> #include <ws2tcpip.h> // If running on Win9x or pre Windows XP uncomment the following //#include <wspiapi.h> #include <stdio.h> #include <stdlib.h> // // Function: usage // // Description: // Prints usage information for application // void usage(char *progname) { fprintf(stderr, "usage: %s [-n name] [-s port/service] [-a 4|6] [-t s|u] [-p tcp|udp] [-b]\n", progname); fprintf(stderr, " -n name Host name to resolve\n"); fprintf(stderr, " -s port/service Service name or port number to resolve\n"); fprintf(stderr, " -a address-family Preferred address family\n" " 4 IPv4 (AF_INET)\n" " 6 IPv6 (AF_INET6)\n"); fprintf(stderr, " -t socket-type Preferred socket type\n" " stream Stream socket (SOCK_STREAM)\n" " dgram Datagram socket (SOCK_DGRAM)\n"); fprintf(stderr, " -p protocol Preferred protocol\n" " tcp TCP (IPPROTO_TCP)\n" " udp UDP (IPPROTO_UDP)\n"); fprintf(stderr, " -f flag Flags passed to getname info (may appear multiple times)\n" " nofqdn NI_NOFQDN\n" " numerichost NI_NUMERICHOST\n" " namereqd NI_NAMEREQD\n" " numericserv NI_NUMERICSERV\n" " dgram NI_DGRAM\n"); fprintf(stderr, " -b Obtain the bind address for the given address family\n"); ExitProcess(-1); } // // Function: PrintParameters // // Description: // Prints the parameters passed into the application before attempting to // resolve the requested name and service. // void PrintParameters(char *host, char *serv, int af, int type, int proto, int flags) { printf("\n"); printf("Attempting to resolve the host: %s\n", (host ? host: "NULL")); printf("Service/port information is : %s\n", (serv ? serv: "NULL")); if (af == AF_INET) printf("Requested address family : AF_INET\n"); else if (af == AF_INET6) printf("Requested address family : AF_INET6\n"); else printf("Requested address family : NONE (default is AF_UNSPEC)\n"); if (type == SOCK_STREAM) printf("Requested socket type : SOCK_STREAM\n"); else if (type == SOCK_DGRAM) printf("Requested socket type : SOCK_DGRAM\n"); else printf("Requested socket type : NONE\n"); if (proto == IPPROTO_TCP) printf("Requested protocol : IPPROTO_TCP\n"); else if (proto == IPPROTO_UDP) printf("Requested protocol : IPPROTO_UDP\n"); else printf("Requested protocol : NONE\n"); printf("Requested flags to getnameinfo: "); if (flags & NI_NOFQDN) printf("NI_NOFQDN "); if (flags & NI_NUMERICHOST) printf("NI_NUMERICHOST "); if (flags & NI_NAMEREQD) printf("NI_NAMEREQD "); if (flags & NI_NUMERICSERV) printf("NI_NUMERICSERV "); if (flags & NI_DGRAM) printf("NI_DGRAM "); printf("\n\n"); } // // Function: main // // Description: // This routine takes the host and service information obtained from // the command line and calls getaddrinfo. The first getaddrinfo call // assumes that a numeric string address was passed. If that call fails // then it will attempt to resolve the name via DNS. After getaddrinfo // succeeds, then for each address returned we will call getnameinfo // to resolve it back to its hostname along with displaying the numeric // string address. // int __cdecl main(int argc, char **argv) { WSADATA wsd; struct addrinfo hints, *res=NULL, *ptr; int rc, count, i; // Variables for getnameinfo char host[NI_MAXHOST], serv[NI_MAXSERV], numerichost[NI_MAXHOST]; int hostlen=NI_MAXHOST, servlen=NI_MAXSERV, numerichostlen=NI_MAXHOST, flags=0; // Variables for getaddrinfo int AddressFamily=AF_UNSPEC, SocketType=0, Protocol=0; char *HostName=NULL, *ServPort=NULL; BOOL bGetBindAddress=FALSE; // Load Winsock if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) { fprintf(stderr, "Unable to load Winsock: %d\n", GetLastError()); return -1; } // // Parse the command line arguments // for(i=1; i < argc ;i++) { if ((argv[i][0] != '-') && (argv[i][0] != '/') && (strlen(argv[i]) < 2)) usage(argv[0]); switch (tolower(argv[i][1])) { case 'a': // address family if (i+1 >= argc) usage(argv[0]); if (atoi(argv[i+1]) == 4) AddressFamily = AF_INET; else if (atoi(argv[i+1]) == 6) AddressFamily = AF_INET6; else usage(argv[0]); i++; break; case 'b': // get the bind address only bGetBindAddress = TRUE; break; case 'f': // flags for getnameinfo if (i+1 >= argc) usage(argv[0]); if (_strnicmp(argv[i+1], "nofqdn", 6) == 0) flags |= NI_NOFQDN; else if (_strnicmp(argv[i+1], "numerichost", 11) == 0) flags |= NI_NUMERICHOST; else if (_strnicmp(argv[i+1], "namereqd", 8) == 0) flags |= NI_NAMEREQD; else if (_strnicmp(argv[i+1], "numericserv", 11) == 0) flags |= NI_NUMERICSERV; else if (_strnicmp(argv[i+1], "dgram", 5) == 0) flags |= NI_DGRAM; else usage(argv[0]); i++; break; case 'n': // name to resolve if (i+1 >= argc) usage(argv[0]); HostName = argv[++i]; break; case 'p': // protocol to resove for if (i+1 >= argc) usage(argv[0]); if (_strnicmp(argv[i+1], "tcp", 3) == 0) Protocol = IPPROTO_TCP; else if (_strnicmp(argv[i+1], "udp", 3) == 0) Protocol = IPPROTO_UDP; else usage(argv[0]); i++; break; case 's': // port/service to resolve if (i+1 >= argc) usage(argv[0]); ServPort = argv[++i]; break; case 't': // socket type if (i+1 >= argc) usage(argv[0]); if (_strnicmp(argv[i+1], "stream", 6) == 0) SocketType = SOCK_STREAM; else if (_strnicmp(argv[i+1], "dgram", 5) == 0) SocketType = SOCK_DGRAM; else usage(argv[0]); i++; break; default: usage(argv[0]); break; } } // // Check for the minumum parameters required // if (!HostName && !ServPort) { fprintf(stderr, "\n\nYou must specify at least a host name or service name\n\n"); usage(argv[0]); } if ((flags & NI_NUMERICSERV) == 0) { printf("\nNOTE: Without the NI_NUMERICSERV flag (-f numericserv) getnameinfo will\n" " fail if the port information does not resolve to a well known service\n" " like ftp (21), etc.\n\n"); } PrintParameters(HostName, ServPort, AddressFamily, SocketType, Protocol, flags); // // Resolve the name/address - first assume that the name might be a string // literal address // memset(&hints, 0, sizeof(hints)); if (bGetBindAddress == TRUE) hints.ai_flags = AI_PASSIVE; else hints.ai_flags = AI_NUMERICHOST; hints.ai_family = AddressFamily; hints.ai_socktype = SocketType; hints.ai_protocol = Protocol; rc = getaddrinfo( HostName, ServPort, &hints, &res ); if (rc != 0) { if (rc == WSAHOST_NOT_FOUND) { // // Host name to resolve isn't a string literal, now try a DNS lookup // The numerichost lookup is done first since it doesn't actually // send a request on the network and will fail quickly if it isn't a // numeric address. // hints.ai_flags = AI_CANONNAME; rc = getaddrinfo( HostName, ServPort, &hints, &res ); if (rc != 0) { fprintf(stderr, "getaddrinfo failed: %d\n", rc); return -1; } } else { fprintf(stderr, "getaddrinfo failed: %d\n", rc); return -1; } } // // Count how many addresses were returned // count = 0; ptr = res; while (ptr) { count++; ptr = ptr->ai_next; } printf("Hostname '%s' resolved to %d addresses\n\n", HostName, count); // //Do a reverse lookup on each of the resolved address // count = 1; ptr = res; while (ptr) { host[0] = '\0'; serv[0] = '\0'; // // First convert the binary addresses returned from getaddrinfo into // their numeric string form so we can see the address returned. // rc = getnameinfo( ptr->ai_addr, ptr->ai_addrlen, numerichost, numerichostlen, NULL, 0, NI_NUMERICHOST ); if (rc != 0) { fprintf(stderr, "getnameinfo failed: %d\n", rc); return -1; } printf("[%d] Numeric address resolved: %s\n", count, numerichost); // // Now attemp to reverse lookup according the parameters passed in // by the user // rc = getnameinfo( ptr->ai_addr, ptr->ai_addrlen, host, hostlen, serv, servlen, flags ); if (rc != 0) { fprintf(stderr, "getnameinfo failed: %d for the address: %s\n", rc, numerichost); } else { printf("[%d] Host: %s\n", count, host); printf("[%d] Service: %s\n", count, serv); } printf("\n"); count++; // Goto the next address ptr = ptr->ai_next; } // Free up the results from getaddrinfo freeaddrinfo(res); WSACleanup(); return 0; }
34.306329
110
0.468157
caigen
eb8a8f5f3311f49ff06f3af84722286b57e72ad0
403
cpp
C++
Codechef/PieceOfCake.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
1
2019-09-29T03:58:35.000Z
2019-09-29T03:58:35.000Z
Codechef/PieceOfCake.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
Codechef/PieceOfCake.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); int i, m, mi, n, a[5000], T; string s; cin >> T; while(T--){ cin >> s; n = s.size(); memset(a, 0, sizeof a); for(i = 0; i < n; i++){ a[s[i]]++; } m = -1; for(i = 0; i < 500; i++){ if(m < a[i]){ m = a[i]; } } if(n%2 == 0 && m == n/2)cout << "YES\n"; else cout << "NO\n"; } }
15.5
42
0.441687
MartinAparicioPons
eb8b3b7562777d0e49e67edf216045052c73aaae
3,011
hpp
C++
src/sfizz/WindowedSinc.hpp
michaelwillis/sfizz
0461f6e5e288da71aeccf7b7dfd71302bf0ba175
[ "BSD-2-Clause" ]
281
2019-06-06T05:58:59.000Z
2022-03-06T12:20:09.000Z
src/sfizz/WindowedSinc.hpp
michaelwillis/sfizz
0461f6e5e288da71aeccf7b7dfd71302bf0ba175
[ "BSD-2-Clause" ]
590
2019-09-22T00:26:10.000Z
2022-03-31T19:21:58.000Z
src/sfizz/WindowedSinc.hpp
michaelwillis/sfizz
0461f6e5e288da71aeccf7b7dfd71302bf0ba175
[ "BSD-2-Clause" ]
44
2019-10-08T08:24:20.000Z
2022-02-26T04:21:44.000Z
// SPDX-License-Identifier: BSD-2-Clause // This code is part of the sfizz library and is licensed under a BSD 2-clause // license. You should have receive a LICENSE.md file along with the code. // If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz #pragma once #include "WindowedSinc.h" #include <cstdint> #if SIMDE_NATURAL_VECTOR_SIZE_GE(128) #include <simde/x86/sse2.h> #endif namespace sfz { template <class T> inline void AbstractWindowedSinc<T>::fillTable() noexcept { float* table = const_cast<float*>(static_cast<T*>(this)->getTablePointer()); size_t points = static_cast<T*>(this)->getNumPoints(); size_t tableSize = static_cast<T*>(this)->getTableSize(); WindowedSincDetail::calculateTable( absl::MakeSpan(table, tableSize), points, beta_, TableExtra); } template <class T> inline float AbstractWindowedSinc<T>::getUnchecked(float x) const noexcept { const float* table = static_cast<const T*>(this)->getTablePointer(); size_t points = static_cast<const T*>(this)->getNumPoints(); size_t tableSize = static_cast<const T*>(this)->getTableSize(); float ix = (x + points / 2.0f) * ((tableSize - 1) / points); intptr_t i0 = static_cast<intptr_t>(ix); float mu = ix - i0; float y0 = table[i0]; float dy = table[i0 + 1] - y0; return y0 + mu * dy; } #if SIMDE_NATURAL_VECTOR_SIZE_GE(128) template <class T> inline simde__m128 AbstractWindowedSinc<T>::getUncheckedX4(simde__m128 x) const noexcept { const float* table = static_cast<const T*>(this)->getTablePointer(); size_t points = static_cast<const T*>(this)->getNumPoints(); size_t tableSize = static_cast<const T*>(this)->getTableSize(); simde__m128 ix = simde_mm_mul_ps( simde_mm_add_ps(x, simde_mm_set1_ps(points / 2.0f)), simde_mm_set1_ps((tableSize - 1) / points)); alignas(simde__m128i) int j0[4]; simde__m128i i0 = simde_mm_cvttps_epi32(ix); simde_mm_store_si128((simde__m128i*)j0, i0); simde__m128 mu = simde_mm_sub_ps(ix, simde_mm_cvtepi32_ps(i0)); // reference: Interpolated table lookups using SSE2 [2/2] // https://rawstudio.org/blog/?p=482 simde__m128 p0p1 = simde_mm_castsi128_ps(simde_mm_loadl_epi64((simde__m128i*)&table[j0[0]])); simde__m128 p2p3 = simde_mm_castsi128_ps(simde_mm_loadl_epi64((simde__m128i*)&table[j0[2]])); p0p1 = simde_mm_loadh_pi(p0p1, (simde__m64*)&table[j0[1]]); p2p3 = simde_mm_loadh_pi(p2p3, (simde__m64*)&table[j0[3]]); simde__m128 y0 = simde_mm_shuffle_ps(p0p1, p2p3, SIMDE_MM_SHUFFLE(2, 0, 2, 0)); simde__m128 y1 = simde_mm_shuffle_ps(p0p1, p2p3, SIMDE_MM_SHUFFLE(3, 1, 3, 1)); simde__m128 dy = simde_mm_sub_ps(y1, y0); return simde_mm_add_ps(y0, simde_mm_mul_ps(mu, dy)); } #endif template <class T> inline double AbstractWindowedSinc<T>::getExact(double x) const noexcept { size_t points = static_cast<const T*>(this)->getNumPoints(); return WindowedSincDetail::calculateExact(x, points, beta_); } } // namespace sfz
37.6375
97
0.713384
michaelwillis
eb8f47b9a3853c564e99cab0ce8cf6562d734067
1,270
cpp
C++
Little Panda Power.cpp
michaelarakel/hackerrank-solutions
77ba66a5d81c53b32c59d7547eba67a12349a2f0
[ "Unlicense" ]
null
null
null
Little Panda Power.cpp
michaelarakel/hackerrank-solutions
77ba66a5d81c53b32c59d7547eba67a12349a2f0
[ "Unlicense" ]
null
null
null
Little Panda Power.cpp
michaelarakel/hackerrank-solutions
77ba66a5d81c53b32c59d7547eba67a12349a2f0
[ "Unlicense" ]
1
2020-11-24T19:22:02.000Z
2020-11-24T19:22:02.000Z
// // Little Panda Power.cpp // Hackerrank // // Created by Mikael Arakelian on 6/11/17. // Copyright © 2017 Mikael Arakelian. All rights reserved. // #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int bin_pow(int a, int n, int mod) { if (n == 0) return 1; if (n == 1) return a % mod; if (n & 1) return ((a % mod) * 1ll * (bin_pow(a, n - 1, mod))) % mod; int temp = bin_pow(a, n / 2, mod); return (temp * 1ll * temp) % mod; } int phi(int n) { long long ans = 1; for (int i = 2; i * 1ll * i <= n; ++i) { bool flag = false; while (n % i == 0) { flag = true; n /= i; ans *= i; } if (flag) { ans /= i; ans *= (i - 1); } } if (n > 1) ans *= (n - 1); return ans; } inline int solve() { int a, n, mod; cin >> a >> n >> mod; int a_inverse = bin_pow(a, phi(mod) - 1, mod); //cout << a_inverse << ' '; if (n < 0) return bin_pow(a_inverse, -n, mod); return bin_pow(a, n, mod); } int main() { int t; cin >> t; for (int i= 0; i < t; ++i) cout << solve() << endl;; return 0; }
19.538462
66
0.46063
michaelarakel
eb906b68c09739fec5f46a90d4ebff2ad6377ed0
14,191
cpp
C++
unit/engine/unittest_layouts.cpp
DamianMehers/apl-core-library
9c003dbfc8bc90709396c07179c523473d380db1
[ "Apache-2.0" ]
null
null
null
unit/engine/unittest_layouts.cpp
DamianMehers/apl-core-library
9c003dbfc8bc90709396c07179c523473d380db1
[ "Apache-2.0" ]
null
null
null
unit/engine/unittest_layouts.cpp
DamianMehers/apl-core-library
9c003dbfc8bc90709396c07179c523473d380db1
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "gtest/gtest.h" #include "apl/engine/evaluate.h" #include "../testeventloop.h" using namespace apl; static const char *DATA = "{" "\"title\": \"Pecan Pie V\"" "}"; class LayoutTest : public DocumentWrapper {}; static const char *SIMPLE_LAYOUT = "{" " \"type\": \"APL\"," " \"version\": \"1.0\"," " \"layouts\": {" " \"SimpleLayout\": {" " \"parameters\": []," " \"items\": {" " \"type\": \"Text\"," " \"text\": \"${payload.title}\"" " }" " }" " }," " \"mainTemplate\": {" " \"parameters\": [" " \"payload\"" " ]," " \"item\": {" " \"type\": \"SimpleLayout\"" " }" " }" "}"; TEST_F(LayoutTest, Simple) { loadDocument(SIMPLE_LAYOUT, DATA); auto map = component->getCalculated(); ASSERT_EQ(kComponentTypeText, component->getType()); ASSERT_EQ("Pecan Pie V", map[kPropertyText].asString()); } TEST_F(LayoutTest, SimpleInfo) { loadDocument(SIMPLE_LAYOUT, DATA); auto count = root->info().count(Info::kInfoTypeLayout); ASSERT_EQ(1, count); auto p = root->info().at(Info::kInfoTypeLayout, 0); ASSERT_STREQ("SimpleLayout", p.first.c_str()); ASSERT_STREQ("_main/layouts/SimpleLayout", p.second.c_str()); } static const char *PARAMETERIZED = "{" " \"type\": \"APL\"," " \"version\": \"1.0\"," " \"layouts\": {" " \"SimpleLayout\": {" " \"parameters\": [" " \"text\"" " ]," " \"items\": {" " \"type\": \"Text\"," " \"text\": \"${text}\"" " }" " }" " }," " \"mainTemplate\": {" " \"parameters\": [" " \"payload\"" " ]," " \"item\": {" " \"type\": \"SimpleLayout\"," " \"text\": \"${payload.title}\"," " \"width\": 222" " }" " }" "}"; TEST_F(LayoutTest, Parameterized) { loadDocument(PARAMETERIZED, DATA); auto map = component->getCalculated(); ASSERT_EQ(kComponentTypeText, component->getType()); ASSERT_EQ("Pecan Pie V", map[kPropertyText].asString()); ASSERT_EQ(Object(Dimension(222)), map[kPropertyWidth]); ASSERT_EQ(Object(Dimension()), map[kPropertyHeight]); } static const char* PARAMETERIZED_DEFAULT_EVALUATE = "{\n" " \"type\": \"APL\",\n" " \"version\": \"1.1\",\n" " \"layouts\": {\n" " \"myLayout\": {\n" " \"parameters\": [\n" " {\n" " \"name\": \"content\",\n" " \"type\": \"string\",\n" " \"default\": \"${ordinal}\"\n" " }\n" " ],\n" " \"item\": {\n" " \"type\": \"Text\",\n" " \"text\": \"${content}\"\n" " }\n" " }\n" " },\n" " \"mainTemplate\": {\n" " \"items\": [\n" " {\n" " \"type\": \"Sequence\",\n" " \"data\": [\n" " \"One\",\n" " \"Two\",\n" " \"Three\"\n" " ],\n" " \"numbered\": true,\n" " \"items\": [\n" " {\n" " \"type\": \"myLayout\"\n" " }\n" " ]\n" " }\n" " ]\n" " }\n" "}"; TEST_F(LayoutTest, ParameterizedDefaultEvaluate) { loadDocument(PARAMETERIZED_DEFAULT_EVALUATE); auto one = component->getChildAt(0); auto two = component->getChildAt(1); auto three = component->getChildAt(2); ASSERT_EQ(kComponentTypeText, one->getType()); ASSERT_EQ(kComponentTypeText, two->getType()); ASSERT_EQ(kComponentTypeText, three->getType()); ASSERT_EQ("1", one->getCalculated(kPropertyText).asString()); ASSERT_EQ("2", two->getCalculated(kPropertyText).asString()); ASSERT_EQ("3", three->getCalculated(kPropertyText).asString()); } static const char *DOUBLE = "{" " \"type\": \"APL\"," " \"version\": \"1.0\"," " \"layouts\": {" " \"A\": {" " \"parameters\": [" " \"text\"" " ]," " \"items\": {" " \"type\": \"Text\"," " \"text\": \"${text}\"" " }" " }," " \"B\": {" " \"parameters\": [" " {" " \"name\": \"w\"," " \"default\": 10" " }," " {" " \"name\": \"h\"," " \"default\": 10" " }" " ]," " \"items\": {" " \"type\": \"A\"," " \"height\": \"${h}\"," " \"width\": \"${w}\"" " }" " }" " }," " \"mainTemplate\": {" " \"parameters\": [" " \"payload\"" " ]," " \"item\": {" " \"type\": \"B\"," " \"h\": 52," " \"text\": \"${payload.title}\"," " \"width\": 222" " }" " }" "}"; TEST_F(LayoutTest, Double) { loadDocument(DOUBLE, DATA); auto map = component->getCalculated(); ASSERT_EQ(kComponentTypeText, component->getType()); ASSERT_EQ("Pecan Pie V", map[kPropertyText].asString()); ASSERT_EQ(Object(Dimension(222)), map[kPropertyWidth]); ASSERT_EQ(Object(Dimension(52)), map[kPropertyHeight]); } static const char *BASIC_WHEN = "{" " \"type\": \"APL\"," " \"version\": \"1.0\"," " \"layouts\": {" " \"Basic\": {" " \"parameters\": [" " \"text\"" " ]," " \"items\": {" " \"type\": \"Text\"," " \"text\": \"${text}\"" " }" " }" " }," " \"mainTemplate\": {" " \"parameters\": [" " \"payload\"" " ]," " \"item\": {" " \"type\": \"Basic\"," " \"when\": false," " \"text\": \"${payload.title}\"" " }" " }" "}"; TEST_F(LayoutTest, BasicWhen) { loadDocumentExpectFailure(BASIC_WHEN, DATA); } static const char *BASIC_WHEN_NESTED = "{" " \"type\": \"APL\"," " \"version\": \"1.0\"," " \"layouts\": {" " \"Basic\": {" " \"parameters\": [" " \"text\"," " {" " \"name\": \"inflate\"," " \"default\": false" " }" " ]," " \"items\": {" " \"type\": \"Text\"," " \"when\": \"${inflate}\"," " \"text\": \"${text}\"" " }" " }" " }," " \"mainTemplate\": {" " \"parameters\": [" " \"payload\"" " ]," " \"item\": {" " \"type\": \"Basic\"," " \"text\": \"${payload.title}\"" " }" " }" "}"; TEST_F(LayoutTest, BasicWhenNested) { loadDocumentExpectFailure(BASIC_WHEN_NESTED, DATA); } static const char *DOUBLE_NESTED = "{" " \"type\": \"APL\"," " \"version\": \"1.0\"," " \"layouts\": {" " \"A\": {" " \"parameters\": [" " \"text\"," " {" " \"name\": \"inflate\"," " \"default\": true" " }" " ]," " \"items\": {" " \"type\": \"Text\"," " \"when\": \"${inflate}\"," " \"text\": \"${text}\"" " }" " }," " \"B\": {" " \"parameters\": [" " {" " \"name\": \"doB\"," " \"default\": true" " }" " ]," " \"items\": {" " \"type\": \"A\"," " \"when\": \"${doB}\"" " }" " }" " }," " \"mainTemplate\": {" " \"parameters\": [" " \"payload\"" " ]," " \"item\": {" " \"type\": \"Container\"," " \"items\": [" " {" " \"type\": \"B\"," " \"doB\": true," " \"inflate\": false," " \"text\": \"doB=true inflate=false\"" " }," " {" " \"type\": \"B\"," " \"doB\": false," " \"inflate\": false," " \"text\": \"doB=false inflate=false\"" " }," " {" " \"type\": \"B\"," " \"doB\": true," " \"inflate\": true," " \"text\": \"doB=true inflate=true\"" " }," " {" " \"type\": \"B\"," " \"doB\": true," " \"inflate\": false," " \"text\": \"doB=true inflate=false\"" " }" " ]" " }" " }" "}"; TEST_F(LayoutTest, DoubleNested) { loadDocument(DOUBLE_NESTED, DATA); ASSERT_TRUE(component); auto map = component->getCalculated(); ASSERT_EQ(kComponentTypeContainer, component->getType()); ASSERT_EQ(1, component->getChildCount()); auto child = component->getChildAt(0); ASSERT_EQ("doB=true inflate=true", child->getCalculated(kPropertyText).asString()); } static const char *EMBEDDED_CONTENT = "{" " \"type\": \"APL\"," " \"version\": \"1.1\"," " \"layouts\": {" " \"contentControl\": {" " \"parameters\": [" " {" " \"name\": \"content\"," " \"type\": \"component\"" " }," " \"backgroundColor\"" " ]," " \"item\": {" " \"type\": \"Frame\"," " \"backgroundColor\": \"${backgroundColor}\"," " \"width\": \"100%\"," " \"height\": \"100%\"," " \"item\": \"${content}\"" " }" " }" " }," " \"mainTemplate\": {" " \"items\": [" " {" " \"type\": \"contentControl\"," " \"width\": \"80vw\"," " \"height\": \"80vh\"," " \"backgroundColor\": \"red\"," " \"content\": {" " \"type\": \"Text\"," " \"text\": \"child\"" " }" " }" " ]" " }" "}"; TEST_F(LayoutTest, EmbeddedContent) { loadDocument(EMBEDDED_CONTENT); ASSERT_TRUE(component); ASSERT_EQ(kComponentTypeFrame, component->getType()); ASSERT_EQ(1, component->getChildCount()); auto child = component->getChildAt(0); ASSERT_EQ(kComponentTypeText, child->getType()); ASSERT_TRUE(IsEqual("child", child->getCalculated(kPropertyText).asString())); } const char *DIMENSION_PARAMETER_DEFAULT = "{" " \"type\": \"APL\"," " \"version\": \"1.1\"," " \"layouts\": {" " \"MyText\": {" " \"parameters\": [" " {" " \"name\": \"size\"," " \"description\": \"Size (height and width) of the text. Defaults to 300dp.\"," " \"type\": \"dimension\"," " \"default\": \"300dp\"" " }" " ]," " \"item\": {" " \"type\": \"Text\"," " \"text\": \"${size/2}\"," " \"width\": \"${size}\"," " \"height\": \"${size}\"" " }" " }" " }," " \"mainTemplate\": {" " \"items\": [" " {" " \"type\": \"Container\"," " \"width\": \"100vw\"," " \"height\": \"100vh\"," " \"items\": [" " {" " \"type\": \"MyText\"" " }" " ]" " }" " ]" " }" "}"; TEST_F(LayoutTest, TypedLayoutParameterDefault) { loadDocument(DIMENSION_PARAMETER_DEFAULT); ASSERT_EQ(kComponentTypeContainer, component->getType()); auto text = component->getCoreChildAt(0); ASSERT_TRUE(text); ASSERT_EQ(kComponentTypeText, text->getType()); ASSERT_EQ("150dp", text->getCalculated(kPropertyText).asString()); ASSERT_EQ(Rect(0, 0, 300, 300), text->getCalculated(kPropertyBounds).getRect()); } const char *DIMENSION_PARAMETER = "{" " \"type\": \"APL\"," " \"version\": \"1.1\"," " \"layouts\": {" " \"MyText\": {" " \"parameters\": [" " {" " \"name\": \"size\"," " \"description\": \"Size (height and width) of the text. Defaults to 300dp.\"," " \"type\": \"dimension\"," " \"default\": \"300dp\"" " }" " ]," " \"item\": {" " \"type\": \"Text\"," " \"text\": \"${size/2}\"," " \"width\": \"${size}\"," " \"height\": \"${size}\"" " }" " }" " }," " \"mainTemplate\": {" " \"items\": [" " {" " \"type\": \"Container\"," " \"width\": \"100vw\"," " \"height\": \"100vh\"," " \"items\": [" " {" " \"type\": \"MyText\"," " \"size\": \"200dp\"" " }" " ]" " }" " ]" " }" "}"; TEST_F(LayoutTest, TypedLayoutParameter) { loadDocument(DIMENSION_PARAMETER); ASSERT_EQ(kComponentTypeContainer, component->getType()); auto text = component->getCoreChildAt(0); ASSERT_TRUE(text); ASSERT_EQ(kComponentTypeText, text->getType()); ASSERT_EQ("100dp", text->getCalculated(kPropertyText).asString()); ASSERT_EQ(Rect(0, 0, 200, 200), text->getCalculated(kPropertyBounds).getRect()); }
26.826087
97
0.394053
DamianMehers
eb9a912b4da2a95de67cbe47dee1b711cfff5743
4,688
cpp
C++
tests/test-allflags.cpp
lcapaldo/c-server-sdk
87edbe872b5f5fa6e797a6e26e89faf941958679
[ "Apache-2.0" ]
5
2019-10-08T05:05:40.000Z
2022-03-23T10:46:27.000Z
tests/test-allflags.cpp
lcapaldo/c-server-sdk
87edbe872b5f5fa6e797a6e26e89faf941958679
[ "Apache-2.0" ]
8
2020-01-18T02:16:27.000Z
2022-02-23T21:28:07.000Z
tests/test-allflags.cpp
lcapaldo/c-server-sdk
87edbe872b5f5fa6e797a6e26e89faf941958679
[ "Apache-2.0" ]
6
2019-12-13T21:00:11.000Z
2021-06-09T09:55:13.000Z
#include "gtest/gtest.h" #include "commonfixture.h" extern "C" { #include <string.h> #include <launchdarkly/api.h> #include "client.h" #include "config.h" #include "evaluate.h" #include "store.h" #include "utility.h" #include "test-utils/client.h" #include "test-utils/flags.h" } // Inherit from the CommonFixture to give a reasonable name for the test output. // Any custom setup and teardown would happen in this derived class. class AllFlagsFixture : public CommonFixture { }; TEST_F(AllFlagsFixture, AllFlagsValid) { struct LDJSON *flag1, *flag2, *allFlags; struct LDClient *client; struct LDUser *user; ASSERT_TRUE(client = makeTestClient()); ASSERT_TRUE(user = LDUserNew("userkey")); /* flag1 */ ASSERT_TRUE(flag1 = LDNewObject()); ASSERT_TRUE(LDObjectSetKey(flag1, "key", LDNewText("flag1"))); ASSERT_TRUE(LDObjectSetKey(flag1, "version", LDNewNumber(1))); ASSERT_TRUE(LDObjectSetKey(flag1, "on", LDNewBool(LDBooleanTrue))); ASSERT_TRUE(LDObjectSetKey(flag1, "salt", LDNewText("abc"))); setFallthrough(flag1, 1); addVariation(flag1, LDNewText("a")); addVariation(flag1, LDNewText("b")); /* flag2 */ ASSERT_TRUE(flag2 = LDNewObject()); ASSERT_TRUE(LDObjectSetKey(flag2, "key", LDNewText("flag2"))); ASSERT_TRUE(LDObjectSetKey(flag2, "version", LDNewNumber(1))); ASSERT_TRUE(LDObjectSetKey(flag2, "on", LDNewBool(LDBooleanTrue))); ASSERT_TRUE(LDObjectSetKey(flag2, "salt", LDNewText("abc"))); setFallthrough(flag2, 1); addVariation(flag2, LDNewText("c")); addVariation(flag2, LDNewText("d")); /* store */ ASSERT_TRUE(LDStoreInitEmpty(client->store)); ASSERT_TRUE(LDStoreUpsert(client->store, LD_FLAG, flag1)); ASSERT_TRUE(LDStoreUpsert(client->store, LD_FLAG, flag2)); /* test */ ASSERT_TRUE(allFlags = LDAllFlags(client, user)); /* validation */ ASSERT_EQ(LDCollectionGetSize(allFlags), 2); ASSERT_STREQ(LDGetText(LDObjectLookup(allFlags, "flag1")), "b"); ASSERT_STREQ(LDGetText(LDObjectLookup(allFlags, "flag2")), "d"); /* cleanup */ LDJSONFree(allFlags); LDUserFree(user); LDClientClose(client); } /* If there is a problem with a single flag, then that should not prevent returning other flags. * In this test one of the flags will have an invalid fallthrough that contains neither a variation * nor rollout. */ TEST_F(AllFlagsFixture, AllFlagsWithFlagWithFallthroughWithNoVariationAndNoRollout) { struct LDJSON * flag1, *flag2, *allFlags; struct LDClient *client; struct LDUser * user; ASSERT_TRUE(client = makeTestClient()); ASSERT_TRUE(user = LDUserNew("userkey")); /* flag1 */ ASSERT_TRUE(flag1 = LDNewObject()); ASSERT_TRUE(LDObjectSetKey(flag1, "key", LDNewText("flag1"))); ASSERT_TRUE(LDObjectSetKey(flag1, "version", LDNewNumber(1))); ASSERT_TRUE(LDObjectSetKey(flag1, "on", LDNewBool(LDBooleanTrue))); ASSERT_TRUE(LDObjectSetKey(flag1, "salt", LDNewText("abc"))); setFallthrough(flag1, 1); addVariation(flag1, LDNewText("a")); addVariation(flag1, LDNewText("b")); /* flag2 */ ASSERT_TRUE(flag2 = LDNewObject()); ASSERT_TRUE(LDObjectSetKey(flag2, "key", LDNewText("flag2"))); ASSERT_TRUE(LDObjectSetKey(flag2, "version", LDNewNumber(1))); ASSERT_TRUE(LDObjectSetKey(flag2, "on", LDNewBool(LDBooleanTrue))); ASSERT_TRUE(LDObjectSetKey(flag2, "salt", LDNewText("abc"))); /* Set a fallthrough which has no variation or rollout. */ struct LDJSON *fallthrough; ASSERT_TRUE(fallthrough = LDNewObject()); ASSERT_TRUE(LDObjectSetKey(flag2, "fallthrough", fallthrough)); /* store */ ASSERT_TRUE(LDStoreInitEmpty(client->store)); ASSERT_TRUE(LDStoreUpsert(client->store, LD_FLAG, flag1)); ASSERT_TRUE(LDStoreUpsert(client->store, LD_FLAG, flag2)); /* test */ ASSERT_TRUE(allFlags = LDAllFlags(client, user)); /* validation */ ASSERT_EQ(LDCollectionGetSize(allFlags), 1); ASSERT_STREQ(LDGetText(LDObjectLookup(allFlags, "flag1")), "b"); /* cleanup */ LDJSONFree(allFlags); LDUserFree(user); LDClientClose(client); } TEST_F(AllFlagsFixture, AllFlagsNoFlagsInStore) { struct LDJSON *flag1, *flag2, *allFlags; struct LDClient *client; struct LDUser *user; ASSERT_TRUE(client = makeTestClient()); ASSERT_TRUE(user = LDUserNew("userkey")); /* store */ ASSERT_TRUE(LDStoreInitEmpty(client->store)); /* test */ ASSERT_TRUE(allFlags = LDAllFlags(client, user)); /* validation */ ASSERT_EQ(LDCollectionGetSize(allFlags), 0); /* cleanup */ LDJSONFree(allFlags); LDUserFree(user); LDClientClose(client); }
32.555556
99
0.694326
lcapaldo
eb9c1dbc2600e452d1aa03f872b7b8611001d3bb
820
cpp
C++
src/Stages/ObstacleMaker.cpp
lucashflores/jogo-tecprog
21b114f21b933247a321e17905338a4f51620d2a
[ "MIT" ]
null
null
null
src/Stages/ObstacleMaker.cpp
lucashflores/jogo-tecprog
21b114f21b933247a321e17905338a4f51620d2a
[ "MIT" ]
null
null
null
src/Stages/ObstacleMaker.cpp
lucashflores/jogo-tecprog
21b114f21b933247a321e17905338a4f51620d2a
[ "MIT" ]
null
null
null
#include "Stages/ObstacleMaker.h" using namespace Stages; ObstacleMaker::ObstacleMaker() { } ObstacleMaker::~ObstacleMaker() { } Entities::Barrel* ObstacleMaker::makeBarrel(Coordinates::Vector<float> pos) { Entities::Barrel* barrel = NULL; barrel = new Entities::Barrel(pos); return barrel; } Entities::OilTile* ObstacleMaker::makeOilTile(Coordinates::Vector<float> pos) { Entities::OilTile* oilTile = NULL; oilTile = new Entities::OilTile(pos); return oilTile; } Entities::Fire* ObstacleMaker::makeFire(Coordinates::Vector<float> pos) { Entities::Fire* fire = NULL; fire = new Entities::Fire(pos); return fire; } Entities::Sign* ObstacleMaker::makeSign(Coordinates::Vector<float> pos) { Entities::Sign* sign = NULL; sign = new Entities::Sign(pos); return sign; }
23.428571
79
0.7
lucashflores
eba0caae28ebe220f16ce3e5677abf1a8cc9ed25
2,108
hpp
C++
src/marnav/nmea/rte.hpp
ShadowTeolog/marnav
094dd06a2b9e52591bc9c3879ea4b5cf34a92192
[ "BSD-4-Clause" ]
null
null
null
src/marnav/nmea/rte.hpp
ShadowTeolog/marnav
094dd06a2b9e52591bc9c3879ea4b5cf34a92192
[ "BSD-4-Clause" ]
null
null
null
src/marnav/nmea/rte.hpp
ShadowTeolog/marnav
094dd06a2b9e52591bc9c3879ea4b5cf34a92192
[ "BSD-4-Clause" ]
null
null
null
#ifndef MARNAV__NMEA__RTE__HPP #define MARNAV__NMEA__RTE__HPP #include "sentence.hpp" #include "waypoint.hpp" #include "../utils/optional.hpp" namespace marnav { namespace nmea { /// @brief RTE - Routes /// /// @code /// 1 2 3 4 5 x /// | | | | | | /// $--RTE,x.x,x.x,a,c--c,c--c, ..... c--c*hh<CR><LF> /// @endcode /// /// Field Number: /// 1. Total number of messages being transmitted /// 2. Message Number /// 3. Message mode c = complete route, all waypoints w = working route, the waypoint /// you just left, the waypoint you’re heading to, then all the rest /// 4. Waypoint ID /// /// More waypoints follow. Last field is a checksum as usual. /// /// The Garmin 65 and possibly other units report a <tt>$GPR00</tt> in the same format. /// class rte : public sentence { friend class detail::factory; public: constexpr static sentence_id ID = sentence_id::RTE; constexpr static const char * TAG = "RTE"; constexpr static int max_waypoints = 10; rte(); rte(const rte &) = default; rte & operator=(const rte &) = default; rte(rte &&) = default; rte & operator=(rte &&) = default; protected: rte(talker talk, fields::const_iterator first, fields::const_iterator last); virtual void append_data_to(std::string &) const override; private: uint32_t n_messages_ = 1; uint32_t message_number_ = 1; route message_mode_ = route::complete; // C:complete route, W:working route utils::optional<waypoint> waypoint_id_[max_waypoints]; // names or numbers of the active route public: decltype(n_messages_) get_n_messages() const { return n_messages_; } decltype(message_number_) get_message_number() const { return message_number_; } decltype(message_mode_) get_message_mode() const { return message_mode_; } utils::optional<waypoint> get_waypoint_id(int index) const; void set_n_messages(uint32_t t) noexcept { n_messages_ = t; } void set_message_number(uint32_t t) noexcept { message_number_ = t; } void set_message_mode(route t) noexcept { message_mode_ = t; } void set_waypoint_id(int index, const waypoint & id); }; } } #endif
28.876712
87
0.694972
ShadowTeolog
eba10adf7c5e6d4ee5736e8b1f05fc2a1c7f3ad9
33,209
hxx
C++
header/rsfe_splitbregman.hxx
marco-fedele/3dimagetoolkit
c58db95c52e7d434080e0de28f3b9ce519d7ad3f
[ "BSD-3-Clause" ]
11
2016-02-26T17:33:13.000Z
2021-01-20T12:52:15.000Z
header/rsfe_splitbregman.hxx
marco-fedele/3dimagetoolkit
c58db95c52e7d434080e0de28f3b9ce519d7ad3f
[ "BSD-3-Clause" ]
null
null
null
header/rsfe_splitbregman.hxx
marco-fedele/3dimagetoolkit
c58db95c52e7d434080e0de28f3b9ce519d7ad3f
[ "BSD-3-Clause" ]
3
2016-03-16T17:01:50.000Z
2018-05-05T02:57:55.000Z
/* ========================================================================================= 3D Image Toolkit Copyright 2013: Marco Fedele, Luca Barbarotta, Francesco Cremonesi, Elena Faggiano. All rights reserved. Read details of the license in the file license.txt provided with the library. ========================================================================================= */ /*! \file rsfe_splitbregman.hxx \brief header file of class \ref segm::rsfe_splitbregman */ #ifndef RSFE_SPLITBREGMAN_HXX_INCLUDED #define RSFE_SPLITBREGMAN_HXX_INCLUDED #include "image3d.hxx" #include "interface.hxx" #include "segmentation.hxx" #include "poisson.hxx" #include "convolution.hxx" #include "exceptions.hxx" #include <GetPot> #include <sstream> namespace segm { /*! \brief A class to apply a segmentation algorithm consisting on the application of the Split-Bregman method to minimize the Region Scalable Fitting Energy Functional. This algorithm divides an \ref im3d::image3d into two regions, hence it works good to segment images with two clearly defined set of intensity values. It works good also with inhomogeneous images thanks to its property of approximation of the intensity of the image to segment using convolution with a Gaussian kernel.\n More precisely this algorithm minimize the following functional, where \ref phi is the levelset function in which the contour of the image is stored and \f$u_0\f$ is the intensity function of the image: \f[ \mathcal{F}(\phi(\mathbf{x})) \quad=\quad \nu~\left\|\nabla \phi \right\|_{g} \quad+\quad \left\langle \phi, \lambda_{1}e_{1} - \lambda_{2}e_{2} \right\rangle_{L^2(\Omega)} \f] \f[ \mbox{where}\qquad e_i(\mathbf{x}) \quad=\quad \int_{\Omega} K_\sigma(\mathbf{x}-\mathbf{y})\left| u_0 (\mathbf{x}) - f_i(\mathbf{y})\right|^2 d \mathbf{y}, \f] \f[ \mbox{with}\qquad K_\sigma(\mathbf{x})= \frac{1}{(\sqrt{2\pi}\ \sigma)^d}\ \exp \left\{ -\frac{|\mathbf{x}|^2}{2\sigma^2}\right\}, \quad \mathbf{x} \in \mathbf{R}^d, \qquad \qquad f_{i}(\mathbf{x}) = \frac{K_{\sigma} \ast \Big[ M_{i}^{\varepsilon} \big(\phi(\mathbf{x})\big) u_{0}(\mathbf{x}) \Big] } {K_{\sigma}(\mathbf{x}) \ast M_{i}^{\varepsilon}\big(\phi(\mathbf{x})\big) }, \f] \f[ M_{1}^{\varepsilon}(\mathbf{x}) = \frac{1}{2} \left( 1 + \frac{2}{\pi}\arctan\left( \frac{\phi(\mathbf{x})-(a_0 +\alpha)}{\varepsilon|b_0 -a_0|} \right) \right), \qquad \qquad M_{2}^{\varepsilon}(\mathbf{x}) = 1 - M_{1}^{\varepsilon}. \f] \f[ \|f\|_{g}~=~ \left\|~g(u_0)~f~\right\|_{L^1(\Omega)}, \qquad g\big(u_0(\mathbf{x})\big) ~=~ \frac{1}{1+\beta\left|edge\_detector\big(u_0(\mathbf{x})\big)\right|^2}. \f] The behaviour of the algorithm changes with the modification of the parameters characterizing the functional. Using the default values is a good starting point, but it could be necessary to modify the parameters to obtain a better segmentation. To understand better how to modify each parameter see the documentation of each one: \ref sigma, \ref lamda, \ref lamda1, \ref lamda2, \ref nu, \ref beta, \ref dt, \ref ls_steps, \ref epsilon, \ref a0, \ref b0, \ref alpha.\n Another feature of the algorithm is to 'think globally' dividing the whole image into two regions. On the contrary, to focus only on a part of the image, you can use the automatic extraction of a connected component of the image setting some specific parameters (\ref auto_extract_conn_comp, \ref auto_extract_conn_comp_freq).\n Also other customization are allowed, see the documentation of all private variables for more details. */ template <typename T> class rsfe_splitbregman : public segmentation<T> { private: /*! * \brief A type to define various kind of boundary condition */ enum bc_type {NEU = 1, DIR}; /*! * \brief A type to define various kind of edge detector */ enum ed_type {GRAD = 1, GRAD_THRESHOLD, LBP}; // GENERAL PARAMETERS /*! * \name General Parameters * \brief Variables related to numbers of iteration, frequency of showing * partial results and general setting */ ///@{ /*! * \brief Name of ".pot" file used by \ref apply to set some private attribute via * GetPot (default="data") * * This variable, if it is set to a value different from the default empty string, * allows \ref apply to call private member \ref set_param_from_getpot before * starting * iterations of the algorithm. In this way algorithm initializes all variables in * section [\\init] of file getpotfile and it updates all variables in section * [\\onthego] * every \ref showfrequency iterations if private variable \ref onthego is true. * * \note If the desired ".pot" file is not in your current directory you can * set this string with the path to reach it. * * \warning It is useless to set \ref onthego equal to true if this variable is * set equal to an empty string or to a string that doesn't match with any * existing file */ std::string getpotfile; /*! * \brief It is true to produce a verbose output during execution of \ref apply, * otherwise false (default=true) */ bool verbosity; /*! * \brief It indicates the maximum number of iterations allowed by the algorithm * (default=100) */ uint maxiter; /*! * \brief Number that indicates how often \ref apply shows partial result * (0=never, default=0) */ uint showfrequency; /*! * \brief Number that indicates how often \ref apply saves partial result * (0=never, default=0) */ uint dumpfrequency; /*! * \brief Name of desired output file in which partial and final results are stored * (default="result") * * In case of not null \ref dumpfrequency, \ref apply will save partial results in * a .mhd-.raw file called <outputname>_<iteration number> adding also the string * "_final" to the last result. In case of null \ref dumpfrequency it will not * save any files. */ std::string outputname; /*! * \brief Name of the logfile in which history of the algorithm is saved * (default="") * * If this string is not null, stderr is redirected to a text file called * logfilename in append modality. * In this way all important informations of the execution of of the algorithm * like initial private attributes, norm of errors at each iteration, * update of private attributes or extraction of a connected component of the * levelset are saved in a file for consultation. On the contrary, if this string * is null, the program will write all this informations on the screen. * * \note The algorithm execution will produce a verbose output only in case of a * true value of private attribute \ref verbosity */ std::string logfilename; /*! * \brief If it is true (default), it allows user to update some private attributes * from file \ref getpotfile (section [\\onthego]) every \ref showfrequency * iterations. */ bool onthego; /*! * \brief If is true, the levelset of the current iteration is saved in file * \ref outputname (default false) * * \note The only way to set this variable to true is through section [\\onthego] * of file \ref getpotfile, so it works only if \ref onthego is true and * \ref getpotfile links to an existing ".pot" file. After saving current levelset * its value is set to false again. */ bool save_current; /*! * \brief Variable settable via \ref getpotfile (section [\\onthego]) to end * algorithm at the current iteration without reaching \ref maxiter * * \warning Settable only from \ref getpotfile during execution, if \ref onthego * is true. */ bool end_now; ///@} // RSFE PARAMETERS /*! * \name RSFE Parameters * \brief All the parameters that appear in the Region Scalable Fitting Energy * Functional */ ///@{ /*! * \brief set the width of all the Gaussian kernels (default=\f$3\f$) * * A quite general rule is to set \f$\sigma\f$ an order of magnitude smaller than * the diameter of the object of interest in the image. A too high \f$\sigma\f$ * will cause an aggregation between all near objects inside the image. * A \f$\sigma\f$ a bit bigger than the one of the rule speeds up the algorithm * in the very first iterations and avoids the problem of the creation of other * contours inside the one of interest. Hence, sometimes a good compromise could * be to adopt an hybrid strategy starting from a bigger \f$\sigma\f$ for a * few iterations and after decreasing it on-the-go. */ T sigma; /*! * \brief it deals with the splitting of the functional with the Split-Bregman * method (default=\f$5 \times 10^{-2}\f$) * * It has an effect on the speed of movement of the contour. The greater it is, * the slower the algorithm becomes. Despite this seems to prove that a smaller * value is always better, the property of slowing down the algorithm increasing * \f$\lambda\f$ can be really useful in lots of practical applications. */ T lamda; /*! * \brief \f$\lambda_1\f$ and \f$\lambda_2\f$ weigh the terms \f$e_1\f$ and * \f$e_2\f$ one in relation to the other (default=\f$10^{-5}\f$) * * It is suggested to set \f$\lambda_1 = \lambda_2 \f$. Indeed, setting * \f$\lambda_2 > \lambda_1\f$ will encourage the contour to develop towards the * outside of the object of interest overestimating it a bit also at the * convergence, while the opposite strategy underestimates the contour especially * during its evolution. The larger the difference between the two values is, * the more this behaviour is evident. * However, sometimes setting these parameters in order * to underestimate the contour during its evolution can help to avoid the problem * of aggregation between near objects. */ T lamda1; /*! * \brief \f$\lambda_1\f$ and \f$\lambda_2\f$ weigh the terms \f$e_1\f$ and * \f$e_2\f$ one in relation to the other (default=\f$10^{-5}\f$) * * It is suggested to set \f$\lambda_1 = \lambda_2 \f$. Indeed, setting * \f$\lambda_2 > \lambda_1\f$ will encourage the contour to develop towards the * outside of the object of interest overestimating it a bit also at the * convergence, while the opposite strategy underestimates the contour especially * during its evolution. The larger the difference between the two values is, * the more this behaviour is evident. * However, sometimes setting these parameters in order * to underestimate the contour during its evolution can help to avoid the problem * of aggregation between near objects. */ T lamda2; /*! * \brief it weighs the edge detector at the denominator of the function * \f$g\big(u_0(\mathbf{x})\big)\f$ (default = \f$100\f$) * * A general rule is to increase it if the edge detector used works good with * your image. Otherwise it is better to decrease it. */ T beta; /*! * \brief desired time step of the time discretization (default=\f$1\f$). * * Useful to slow down the algorithm in some cases. */ T dt; /*! * \brief The number of steps that \ref apply does at each iteration to solve * linear system (default=\f$5\f$) * * At each iteration \ref segmentation::phi becomes the solution of the unsteady * Poisson problem at \f$ t{n+1} = t_n + \f$\ref ls_steps \ref dt. * Hence this variable tells the algorithm how many steps of the resolution of * linear system it has to execute. * This also depends on the method chosen to solve it and on its convergence * properties. Generally the more steps you set, the more accurate is the solution * (but you need more time to solve it). * It is also suggested to use this parameter to slow down the algorithm when * necessary. */ uint ls_steps; /*! * \brief the shape parameter that determines how sharp is the approximation of * the Heaviside (default=\f$10^{-3}\f$) * * A general rule is to set \f$\varepsilon\f$ smaller than two orders of magnitude * in respect of the image spacing. */ T epsilon; /*! * \brief It is the lower bound that levelset \ref segmentation::phi can assume * (default=\f$0\f$) * * This is the minimal allowed value for \ref segmentation::phi. In fact, at * the end of each iteration of the algorithm, every lower value is forced to be * equal to \ref a0 in order to ensure that values of the levelset are in the range * [\ref a0, \ref b0].\n * In case of Dirichlet \ref bc , this is also the value * of the boundary condition of the Poisson problem. * * \warning Cannot set this attributes greater than the value of \ref b0 */ T a0; /*! * \brief It is the upper bound that levelset \ref segmentation::phi can assume * (default=\f$1\f$) * * This is the maximal allowed value for \ref segmentation::phi. In fact, at * the end of each iteration of the algorithm, every bigger value is forced to be * equal to \ref b0 in order to ensure that values of the levelset are in the range * [\ref a0, \ref b0]. * * \warning Cannot set this attributes lower than the value of \ref a0 */ T b0; ///@} // CONNECTED COMPONENT /*! * \name Connected Component * \brief Variables related to the extraction of a connected component of the * partial result */ ///@{ /*! * \brief If it is set to true (default=false), automatic extraction of a connected * component is activate every \ref auto_extract_conn_comp_freq * * This variable, when it is true, allows \ref apply to extract a connected * component of the current levelset \ref segmentation::phi calling * public member \ref im3d::image3d::connected_component on the levelset * only if a selected pixel is white (a pixel is considered white if its value is * between \ref segmentation::alpha and \ref b0). The coordinates of this pixel * are settable by the user and they are stored in private attributes * \ref cc_init_pixel_x, \ref cc_init_pixel_y and \ref cc_init_pixel_z. * After extraction, the connected component is automatically set as current * levelset and the algorithm restarts from this new initial * \ref im3d::image3d.\n * By the way, this is not the only way to extract a connected component of * \ref segmentation::phi. If this variable is false, every \ref showfrequency * iterations, after the show of partial results, user can decide to extract it * answering a question. Only if he likes the output, he could decide to set it * as current levelset.\n * The difference between the two approaches is that the first is totally automatic * and it doesn't need user interaction with the show of partial results (it works * also if \ref showfrequency is 0), the second needs an 'active' user to works. */ bool auto_extract_conn_comp; //! X coordinate of the starting pixel of the automatic extraction double cc_init_pixel_x; //! Y coordinate of the starting pixel of the automatic extraction double cc_init_pixel_y; //! Z coordinate of the starting pixel of the automatic extraction double cc_init_pixel_z; bool cc_binary_output; bool cc_init_variables; /*! Number that indicates, if \ref auto_extract_conn_comp is true, how often * \ref apply automatically extracts a connected_component */ uint auto_extract_conn_comp_freq; ///@} // EXPERT /*! * \name Expert * \brief Parameters to set the edge detector that appears in the second addend * of the RSFE functional */ ///@{ /*! * \brief The kind of boundary conditions to give to the Poisson problem * depends on this value (default=NEU) * * If it is equal to NEU the problem is solved with Neumann condition and this * allows contours with holes on the boundary. If it is set to DIR it is solved * with Dirichlet condition imposing \ref a0 at the boundary and hence preventing * holes in it. */ bc_type bc; /*! * \brief The tolerance of the chosen linear system method (default=0, not set) * * This variable by default is not used by the algorithm because it uses variable * \ref ls_steps to choose when finishing the iterations of the linear system * method. * Instead, if user set a value different from zero, * the iterative method to solve linear system continue also after \ref ls_steps * iterations till the * percentage L2-norm error is greater than this value. It is suggested not to use * a value too small, for instance a value of 0.01 it is more than enough. */ T ls_tol; /*! * \brief The kind of edge detector used to compute an opportune norm of the * gradient of \ref segmentation::phi in the functional to be minimized * * The goal is to compute a function to be multiplied with the module of the * gradient in order to make his L1 norm smaller in regions with edges. * This function is of the form \f$ g=1\big/(1+\beta\xi) \f$, where \f$\xi\f$ is * the edge detector, hence it assumes higher values in regions with edges. * The choice of \f$\xi\f$ depends on this variable that can assume three values: * GRAD, GRAD_THRESHOLD and LBP.\n * GRAD is the default (and suggested) choice that sets * \f$\xi=\big|\nabla\phi\big|^2\f$. * Most of time this is a good choice because generally edges coincide with * regions with high gradient, however in some kind of images * (for instance images with really high noise) * gradient could be not null also in regions far from edges. To avoid this * problem the second values makes a threshold on the gradient using member * im3d::image3d::im_to_black_and_white. User can choose the preferred * value of the threshold during the beginning of the execution of the algorithm. * Note that this choice leads to a \f$\xi\f$ equal to 1 on the 'candidate' edges, * 0 otherwise, hence it produces a less efficient g if at the same time \ref beta * is not increased properly by the user.\n * Both of this two choices can be combined with a Gaussian blur of the images to * limit error linked with noise setting \ref edge_detector_sigma with a value * different from zero.\n * LBP is the last possibility user can choose, but it works only with 2D images. * The effect is similar to the usage of GRAD_THRESHOLD, but to compute the black * and white image is used member * \ref im3d::image3d::local_binary_pattern_edge_detector instead of the gradient. * With an opportune choice of the parameters this leads to an edge detector * less influenced by noise. Also in this case parameters are settable * during the beginning of the execution of the algorithm. */ ed_type edge_detector; /*! * \brief Value of sigma used to compute a Gaussian blur on the \ref edge_detector * in case it is not equal to LBP (default=0, no Gaussian blur). * * In case of not null value and \ref edge_detector equal to GRAD or * GRAD_THRESHOLD, it allows \ref edge_detect to filter the image with a Gaussian * kernel using class \ref conv::filtering before computing the edge detector * function. */ T edge_detector_sigma; /*! * \brief it weighs the first addend of the functional (default=1). * * No significant changes are noted on the contour evolution modifying its value. */ T nu; /*! * \brief Private functor used by \ref apply to compute one step of the unsteady * Poisson problem * * This functor uses by default the \ref lapl::NeuGaussSeidel function (or the * \ref lapl::DirGaussSeidel function in case of \ref bc equal to DIR). * Expert user could implements himself a different function to solve the linear * system and he could pass it to this functor using public member * \ref set_onestep_poisson. See \ref lapl::unsteady_poisson_functor class * documentation for further information. */ lapl::unsteady_poisson_functor<T> onestep_poisson; /*! * \brief Private functor used by \ref apply to compute convolution with * Gaussian kernel during execution of the algorithm * * Default function associated with this functor is * \ref conv::acyclic_fftw_convolution * because is the quickest way to compute a convolution. * Only if \ref sigma is really small, \ref conv::direct_convolution could be * also a good choice. Any other choice is deprecated unless user is comfortable * with Fourier Transform and Convolution Theory. */ conv::filtering<T> cv; /*! * \brief Boolean variable (deafult=false) to change way of computing Gaussian * kernel used by \ref cv in every convolution * * See \ref conv::filtering::build_gaussian_filter for further information */ bool gaussian_pixel_approach; /*! * \brief tollerance value, the algorithm ends if the error is lesser than its * value (default 1.e-5) * * Only if the image is really easy to segment this value could cause the end of * the algorithm, otherwise user could stop the algorithm if partial results * are good using \ref onthego parameter \ref end_now or setting \ref maxiter. * Despite changing this value is allowed, it is not suggested. */ T tol; ///@} // NOT DIRECTLY SETTABLE /*! * \name Not Directly Settable * \brief These attributes are used my some members of the class, but they are not * directly settable by user using any specialized public members */ ///@{ int ix; //!< index of initial contour set by \ref initialize_contour_as_cube int iy; //!< index of initial contour set by \ref initialize_contour_as_cube int iz; //!< index of initial contour set by \ref initialize_contour_as_cube int fx; //!< index of initial contour set by \ref initialize_contour_as_cube int fy; //!< index of initial contour set by \ref initialize_contour_as_cube int fz; //!< index of initial contour set by \ref initialize_contour_as_cube uint dimx; //!< dimension in X direction of current analyzed image uint dimy; //!< dimension in Y direction of current analyzed image uint dimz; //!< dimension in Z direction of current analyzed image uint space_dim; //!< equal to 3 for 3D image, 2 for 2D image double hx; //!< spacing in X direction of current analyzed image double hy; //!< spacing in Y direction of current analyzed image double hz; //!< spacing in Z direction of current analyzed image /*! * \brief auxiliary variable to reinitialize variables after a connected * component extraction */ bool init_variables; ///@} // PRIVATE MEMBERS USED BY APPLY /*! \brief private member used by \ref apply to update domain of the two regions at each iteration */ void set_heaviside (im3d::image3d<T>& Heps) const; /*! \brief private member used by \ref apply to initialize \ref segmentation::phi with a cube */ void initialize_phi_with_cube (); /*! \brief private member used by \ref apply to initialize \ref segmentation::phi with an \ref im3d::image3d chosen by user */ void initialize_phi_with_init (im3d::image3d<T> const& init); /*! \brief private member used by \ref apply to set the \ref edge_detector function used by \ref shrink */ void edge_detect (im3d::image3d<T>& res, im3d::image3d<T> const& f ) const; /*! \brief private member used by \ref apply to select after solving linear system only those values of levelset in the allowed range [\ref a0, \ref b0] */ void cut_phi(); /*! \brief private member used by \ref apply to apply shrink operator */ void shrink (std::vector<im3d::image3d<T> >& res, std::vector<im3d::image3d<T> > const& f1, im3d::image3d<T> const& f2) const; /*! \brief private member used by \ref apply to show partial result using private attribute \ref segmentation::levelset and \ref segmentation::image */ void internal_show (); /*! \brief private member used by \ref apply to extract a connected component of \ref segmentation::phi at some iteration */ void extract_connected_component (); /*! \brief private member used by \ref apply to update on the go those private attributes settable via GetPot using \ref update_param_onthego */ void update_param_onthego (); /*! \brief private member used by \ref apply to set parameters from \ref getpotfile */ void set_param_from_getpot (std::string const& section); public: // CONSTRUCTOR /*! \brief constructor to set all private attributes to their default values */ rsfe_splitbregman(); // MEMBERS TO SET PRIVATE PARAMETERS // NOT CHANGABLE WITH GETPOTFILE /*! * \name Private Parameters * \brief Members to set some private attributes not changable via GetPot */ ///@{ /*! \brief to set private attribute \ref getpotfile \param name is the desired filename of GetPot file */ inline void set_getpotfile (std::string const& name); /*! \brief to set private attribute \ref onthego \param onthego is the desired value */ inline void set_onthego (bool const onthego); /*! \brief to set private attribute \ref verbosity \param v is the desired value */ inline void set_verbosity (bool const v); /*! \brief to set private attribute \ref logfilename \param name is the desired filename of GetPot file */ inline void set_logfilename (std::string const& name); /*! \brief to set private attribute \ref cv \param cv is the desired function to assign at the private functor */ inline void set_cv (conv::filtering<T> const cv); /*! \brief to set private attribute \ref onestep_poisson \param osl is the desired function to assign at the private functor */ inline void set_onestep_poisson (lapl::unsteady_poisson_functor<T> const osl); ///@} end name Private Parameters // CHANGABLE WITH GETPOTFILE /*! * \name GetPot Parameters * \brief Members to set all private attributes also settable via \ref getpotfile */ ///@{ /*! \brief to set private attribute \ref maxiter \param maxiter is the desired value */ inline void set_maxiter (uint const& maxiter); /*! \brief to set private attribute \ref showfrequency \param sf is the desired value */ inline void set_showfrequency (uint const& sf); /*! \brief to set private attribute \ref auto_extract_conn_comp_freq \param cc_freq is the desired value */ inline void set_auto_extract_conn_comp_freq (uint const& cc_freq); /*! \brief to set private attribute \ref dumpfrequency \param dump is the desired value */ inline void set_dumpfrequency (uint const& dump); /*! \brief to set private attribute \ref outputname \param name is the desired filename of GetPot file */ inline void set_outputname (std::string const& name); /*! \brief to set private attribute \ref tol \param tol is the desired value */ inline void set_tol (T const& tol); /*! \brief to set private attribute \ref cc_init_pixel_x \param cc_x is the desired value */ inline void set_cc_init_pixel_x (double const& cc_x); /*! \brief to set private attribute \ref cc_init_pixel_y \param cc_y is the desired value */ inline void set_cc_init_pixel_y (double const& cc_y); /*! \brief to set private attribute \ref cc_init_pixel_z \param cc_z is the desired value */ inline void set_cc_init_pixel_z (double const& cc_z); /*! \brief to set private attribute \ref lamda \param lamda is the desired value */ inline void set_lamda (T const& lamda); /*! \brief to set private attribute \ref lamda1 \param lamda1 is the desired value */ inline void set_lamda1 (T const& lamda1); /*! \brief to set private attribute \ref lamda2 \param lamda2 is the desired value */ inline void set_lamda2 (T const& lamda2); /*! \brief to set private attribute \ref sigma \param sigma is the desired value */ inline void set_sigma (T const& sigma); /*! \brief to set private attribute \ref edge_detector_sigma \param eds is the desired value */ inline void set_edge_detector_sigma (T const& eds); /*! \brief to set private attribute \ref nu \param nu is the desired value */ inline void set_nu (T const& nu); /*! \brief to set private attribute \ref beta \param beta is the desired value */ inline void set_beta (T const& beta); /*! \brief to set private attribute \ref dt \param dt is the desired value */ inline void set_dt (T const& dt); /*! \brief to set private attribute \ref a0 \param a0 is the desired value */ inline void set_a0 (T const& a0); /*! \brief to set private attribute \ref b0 \param b0 is the desired value */ inline void set_b0 (T const& b0); /*! \brief to set private attribute \ref epsilon \param epsilon is the desired value */ inline void set_epsilon (T const& epsilon); /*! \brief to set private attribute \ref bc \param bc is the desired value */ inline void set_bc (bc_type const bc); /*! \brief to set private attribute \ref ls_tol \param tol is the desired value */ inline void set_ls_tol (T const& tol); /*! \brief to set private attribute \ref ls_steps \param steps is the desired value */ inline void set_ls_steps (uint const steps); /*! \brief to set private attribute \ref gaussian_pixel_approach \param gpa is the desired value */ inline void set_gaussian_pixel_approach (bool const gpa); /*! \brief to set private attribute \ref bc \param ed is the desired value */ inline void set_edge_detector (ed_type const ed); /*! \brief to set private attribute \ref auto_extract_conn_comp \param auto_cc is the desired value */ inline void set_auto_extract_conn_comp (bool const auto_cc); /*! \brief to set private attribute \ref cc_binary_output \param cc_bo is the desired value */ inline void set_cc_binary_output (bool const cc_bo); /*! \brief to set private attribute \ref cc_init_variables \param cc_bo is the desired value */ inline void set_cc_init_variables (bool const cc_iv); /*! \brief to set private attribute \ref segmentation::alpha \param alpha is the desired value */ inline void set_alpha (T const& alpha); ///@} end name GetPot Parameters // MEMBERS TO APPLY ALGORITHM /*! * \name Algorithm Execution * \brief Members to execute algorithm */ ///@{ /*! \brief Member to set inizial rectangle/cube. This member show image you'd like to segment and allows user to select coordinates of the two vertices of the desired inizial rectangle/cube. Clicking with mouse on the image user would be able to know coordinates and to write it when program asks him. Coordinates will be saved in private variables, so when user executes algorithm the desired initial rectangle/cube is built. \param image is image you'd like to segment using \ref apply. \warning use this member with the same image you'd like to segment and note that at the end of the algorithm coordinates will be set to the default values again. */ void initialize_contour_as_cube (im3d::image3d<T> const& image); /*! \brief Member to apply the algorithm. \param myim is the image to segment. */ void apply (im3d::image3d<T> const& myim); /*! \brief Member to apply the algorithm. \param myim is the image to segment \param init is the initial value with whom levelset \ref phi is initialized */ void apply (im3d::image3d<T> const& myim, im3d::image3d<T> const& init); ///@} end name Algorithm Execution }; }//end namespace segm #include "rsfe_splitbregman_imp.hxx" #endif // RSFE_SPLITBREGMAN_HXX_INCLUDED
36.857936
93
0.66762
marco-fedele
eba5e1b421fbc33309d9083debfed0a0cd79c7ab
535
hpp
C++
Krakoa/Source/UI/ImGui/TextUI.hpp
KingKiller100/Krakoa-Engine
0f2a5a5109e256a384abe8dc21eacaa45c1de610
[ "Apache-2.0" ]
1
2020-04-05T13:37:48.000Z
2020-04-05T13:37:48.000Z
Krakoa/Source/UI/ImGui/TextUI.hpp
KingKiller100/Krakoa-Engine
0f2a5a5109e256a384abe8dc21eacaa45c1de610
[ "Apache-2.0" ]
null
null
null
Krakoa/Source/UI/ImGui/TextUI.hpp
KingKiller100/Krakoa-Engine
0f2a5a5109e256a384abe8dc21eacaa45c1de610
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../UITypes.hpp" #include "../Flags/InputTextFlags.hpp" #include <Utility/String/kToString.hpp> namespace krakoa::ui { void DrawRawText(const std::string_view& text); template<typename T, typename ...Ts> void DrawRawText(const std::string_view& fmt, const T& arg, const Ts& ...args) { DrawRawText(klib::kString::ToString(fmt, arg, args...)); } bool DrawInputTextBox(const std::string_view& label, char* buf, size_t buf_size, InputTextFlags::Underlying_t flags, const UICallBack& cb = nullptr); }
25.47619
117
0.723364
KingKiller100
eba8b6f107ceb9665f0d2eefe8eac3cb16f20a98
25,032
cc
C++
tensorflow_recommenders_addons/embedding_variable/core/kernels/ev_ops.cc
cockroachzl/recommenders-addons
94886fa490a0042190579375cbacde947026115c
[ "Apache-2.0" ]
584
2020-11-20T01:45:05.000Z
2022-03-29T12:33:03.000Z
tensorflow_recommenders_addons/embedding_variable/core/kernels/ev_ops.cc
cockroachzl/recommenders-addons
94886fa490a0042190579375cbacde947026115c
[ "Apache-2.0" ]
141
2021-01-06T14:43:14.000Z
2022-03-31T07:32:40.000Z
tensorflow_recommenders_addons/embedding_variable/core/kernels/ev_ops.cc
cockroachzl/recommenders-addons
94886fa490a0042190579375cbacde947026115c
[ "Apache-2.0" ]
138
2020-12-16T10:09:31.000Z
2022-03-27T13:30:41.000Z
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "sparsehash/dense_hash_map" #include "tensorflow/core/framework/resource_mgr.h" #include "tensorflow/core/framework/resource_op_kernel.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/util/work_sharder.h" #include "tensorflow_recommenders_addons/embedding_variable/core/kernels/embedding_var.h" #include "tensorflow_recommenders_addons/embedding_variable/core/kernels/ev_op_helpers.h" namespace tensorflow { namespace ev { #define REGISTER_EV_HANDLE(ktype, vtype) \ REGISTER_KERNEL_BUILDER(Name("EVHandleOp") \ .Device(DEVICE_CPU) \ .TypeConstraint<ktype>("Tkey") \ .TypeConstraint<vtype>("Tvalue"), \ ResourceHandleOp<EmbeddingVar<ktype, vtype>>); REGISTER_EV_HANDLE(int32, float) REGISTER_EV_HANDLE(int64, float) #undef REGISTER_EV_HANDLE template <typename T, typename TKey, typename TValue> class EVShapeOp : public OpKernel { public: explicit EVShapeOp(OpKernelConstruction* c) : OpKernel(c) {} void Compute(OpKernelContext* ctx) override { EmbeddingVar<TKey, TValue>* embedding_var = nullptr; OP_REQUIRES_OK( ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &embedding_var)); core::ScopedUnref unref_me(embedding_var); TensorShape shape({embedding_var->Size(), embedding_var->ValueLen()}); Tensor* output; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, {shape.dims()}, &output)); for (int i = 0; i < shape.dims(); ++i) { output->flat<T>()(i) = shape.dim_size(i); } } }; #define REGISTER_KV_VARIABLE_SHAPE(type, ktype, vtype) \ REGISTER_KERNEL_BUILDER(Name("EVShape") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("out_type") \ .TypeConstraint<ktype>("Tkey") \ .TypeConstraint<vtype>("Tvalue"), \ EVShapeOp<type, ktype, vtype>); REGISTER_KV_VARIABLE_SHAPE(int32, int32, float) REGISTER_KV_VARIABLE_SHAPE(int32, int64, float) REGISTER_KV_VARIABLE_SHAPE(int64, int32, float) REGISTER_KV_VARIABLE_SHAPE(int64, int64, float) #undef REGISTER_KV_VARIABLE_SHAPE template <typename TKey, typename TValue> class InitializeEVOp : public OpKernel { public: explicit InitializeEVOp(OpKernelConstruction* c) : OpKernel(c) { OP_REQUIRES_OK(c, c->GetAttr("Tvalue", &dtype_)); OP_REQUIRES_OK(c, c->GetAttr("shape", &shape_)); OP_REQUIRES(c, shape_.dims() == 1, errors::InvalidArgument("EV dimension must be 1")); } void Compute(OpKernelContext* context) override { OP_REQUIRES(context, dtype_ == context->input(1).dtype(), errors::InvalidArgument( "Variable and value dtypes don't match; respectively, ", dtype_, " and ", context->input(1).dtype())); EmbeddingVar<TKey, TValue>* embedding_var = nullptr; const Tensor& default_values = context->input(1); const Tensor& invalid_key = context->input(2); OP_REQUIRES_OK(context, LookupOrCreateResource<EmbeddingVar<TKey, TValue>>( context, HandleFromInput(context, 0), &embedding_var, [this, default_values, invalid_key](EmbeddingVar<TKey, TValue>** ptr) { *ptr = new EmbeddingVar<TKey, TValue>("EmbeddingVar"); return (*ptr)->Init(default_values, invalid_key); })); core::ScopedUnref unref_me(embedding_var); embedding_var->SetInitialized(); } private: DataType dtype_; TensorShape shape_; }; #define REGISTER_KERNELS(ktype, vtype) \ REGISTER_KERNEL_BUILDER(Name("InitializeEVOp") \ .Device(DEVICE_CPU) \ .TypeConstraint<ktype>("Tkey") \ .TypeConstraint<vtype>("Tvalue"), \ InitializeEVOp<ktype, vtype>); #define REGISTER_KERNELS_ALL_INDEX(type) \ REGISTER_KERNELS(int32, type) \ REGISTER_KERNELS(int64, type) REGISTER_KERNELS_ALL_INDEX(float) #undef REGISTER_KERNELS_ALL_INDEX #undef REGISTER_KERNELS template <typename TKey, typename TValue> class EVIsInitializedOp : public OpKernel { public: explicit EVIsInitializedOp(OpKernelConstruction* c) : OpKernel(c) {} void Compute(OpKernelContext* ctx) override { Tensor* output; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, {}, &output)); EmbeddingVar<TKey, TValue>* embedding_var = nullptr; bool found; if (LookupResource<EmbeddingVar<TKey, TValue>>(ctx, HandleFromInput(ctx, 0), &embedding_var) .ok()) { found = embedding_var->IsInitialized(); embedding_var->Unref(); } else { found = false; } output->flat<bool>()(0) = found; } }; #define REGISTER_KERNELS(ktype, vtype) \ REGISTER_KERNEL_BUILDER(Name("EVIsInitializedOp") \ .TypeConstraint<ktype>("Tkey") \ .TypeConstraint<vtype>("Tvalue") \ .Device(DEVICE_CPU), \ EVIsInitializedOp<ktype, vtype>); REGISTER_KERNELS(int32, float) REGISTER_KERNELS(int64, float) #undef REGISTER_KERNELS template <typename TKey, typename TValue> class EVGatherOp : public OpKernel { public: explicit EVGatherOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { EmbeddingVar<TKey, TValue>* embedding_var = nullptr; OP_REQUIRES_OK(context, LookupResource(context, HandleFromInput(context, 0), &embedding_var)); int64 ev_dim_size = embedding_var->ValueLen(); const Tensor& indices = context->input(1); const int64 N = indices.NumElements(); Tensor default_values(context->input(2)); auto default_values_matrix = default_values.shaped<TValue, 2>( {default_values.NumElements() / ev_dim_size, ev_dim_size}); TensorShape result_shape = indices.shape(); TensorShape value_shape({ev_dim_size}); result_shape.AppendShape(value_shape); Tensor* out = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, result_shape, &out)); if (N > 0) { auto out_flat = out->shaped<TValue, 2>({N, out->NumElements() / N}); TValue* out_base = &out_flat(0, 0); auto indices_flat = indices.flat<TKey>(); const int64 indices_size = static_cast<int64>(indices_flat.dimension(0)); const int64 slice_elems = out_flat.dimension(1); OP_REQUIRES( context, ev_dim_size == slice_elems, errors::InvalidArgument( "hashmap's value_len should same with output's dimension(1)", std::to_string(slice_elems), std::to_string(ev_dim_size))); const size_t slice_bytes = slice_elems * sizeof(TValue); for (int64 i = 0; i < indices_size; i++) { TValue* default_v = &default_values_matrix(i, 0); TValue* mem_val = embedding_var->LookupOrCreate(indices_flat(i), default_v); memcpy(out_base + i * slice_elems, mem_val, slice_bytes); } } } }; #define REGISTER_KERNELS(ktype, vtype) \ REGISTER_KERNEL_BUILDER(Name("EVGather") \ .Device(DEVICE_CPU) \ .HostMemory("resource") \ .HostMemory("indices") \ .HostMemory("default_value") \ .HostMemory("output") \ .TypeConstraint<ktype>("Tkey") \ .TypeConstraint<vtype>("Tvalue"), \ EVGatherOp<ktype, vtype>) #define REGISTER_CPU_KERNELS(type) \ REGISTER_KERNELS(int32, type); \ REGISTER_KERNELS(int64, type) REGISTER_CPU_KERNELS(float); #undef REGISTER_CPU_KERNELS #undef REGISTER_KERNELS template <typename TKey, typename TValue, typename TStep> class EVSparseApplyGradientDescentOp : public OpKernel { public: explicit EVSparseApplyGradientDescentOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_)); } void Compute(OpKernelContext* ctx) { auto locks = MaybeLockEmbeddingVariableInputMutexesInOrder<TKey, TValue>( ctx, use_exclusive_lock_, {0}); EmbeddingVar<TKey, TValue>* embedding_var = nullptr; OP_REQUIRES_OK( ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &embedding_var)); const Tensor& lr = ctx->input(1); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr.shape()), errors::InvalidArgument("lr is not a scalar: ", lr.shape().DebugString())); const Tensor& grad = ctx->input(2); const Tensor& indices = ctx->input(3); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(indices.shape()), errors::InvalidArgument("indices must be one-dimensional")); const Tensor& global_step = ctx->input(4); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(global_step.shape()), errors::InvalidArgument("global_step is not a scalar: ", global_step.shape().DebugString())); int64 inner_dim = 1; TensorShape var_shape({embedding_var->Size(), embedding_var->ValueLen()}); for (int d = 1; d < var_shape.dims(); d++) { OP_REQUIRES(ctx, var_shape.dim_size(d) == grad.dim_size(d), errors::InvalidArgument(strings::StrCat( "var and grad must match in dimension ", d))); inner_dim *= grad.dim_size(d); } OP_REQUIRES(ctx, inner_dim > 0, errors::InvalidArgument( "Inner dimension should be greater than zero.")); const int64 N = indices.dim_size(0); OP_REQUIRES( ctx, grad.dim_size(0) == N, errors::InvalidArgument( "grad must be the same size as indices in the first dimension.")); if (N > 0) { auto indices_vec = indices.vec<TKey>(); TValue lr_scalar = lr.scalar<TValue>()(); TStep global_step_scalar = global_step.scalar<TStep>()(); if (inner_dim > 0) { auto grad_flat = grad.flat_outer_dims<TValue>(); for (int64 i = 0; i < N; i++) { const TKey index = indices_vec(i); auto g = grad_flat.template chip<0>(i); auto v = embedding_var->flat(index, global_step_scalar); v -= g.constant(lr_scalar) * g; } } } } private: bool use_exclusive_lock_; }; #define REGISTER_KERNELS(ktype, vtype, stype) \ REGISTER_KERNEL_BUILDER( \ Name("EVSparseApplyGradientDescent") \ .Device(DEVICE_CPU) \ .HostMemory("var") \ .TypeConstraint<ktype>("Tkey") \ .TypeConstraint<vtype>("Tvalue") \ .TypeConstraint<stype>("Tstep"), \ EVSparseApplyGradientDescentOp<ktype, vtype, stype>); #define REGISTER_CPU_KERNELS(T) \ REGISTER_KERNELS(int32, T, int32); \ REGISTER_KERNELS(int32, T, int64); \ REGISTER_KERNELS(int64, T, int32); \ REGISTER_KERNELS(int64, T, int64); REGISTER_CPU_KERNELS(float); #undef REGISTER_CPU_KERNELS #undef REGISTER_KERNELS template <typename TKey, typename TValue, typename TStep> class EVSparseApplyAdagradOp : public OpKernel { public: explicit EVSparseApplyAdagradOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_)); } void Compute(OpKernelContext* ctx) { auto locks = MaybeLockEmbeddingVariableInputMutexesInOrder<TKey, TValue>( ctx, use_exclusive_lock_, {0, 1}); EmbeddingVar<TKey, TValue>* var = nullptr; OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &var)); EmbeddingVar<TKey, TValue>* accum = nullptr; OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 1), &accum)); const Tensor& lr = ctx->input(2); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr.shape()), errors::InvalidArgument("lr is not a scalar: ", lr.shape().DebugString())); const Tensor& grad = ctx->input(3); const Tensor& indices = ctx->input(4); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(indices.shape()), errors::InvalidArgument("indices must be one-dimensional")); const Tensor& global_step = ctx->input(5); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(global_step.shape()), errors::InvalidArgument("global_step is not a scalar: ", global_step.shape().DebugString())); int64 inner_dim = 1; TensorShape var_shape({var->Size(), var->ValueLen()}); for (int d = 1; d < var_shape.dims(); d++) { OP_REQUIRES(ctx, var_shape.dim_size(d) == grad.dim_size(d), errors::InvalidArgument(strings::StrCat( "var and grad must match in dimension ", d))); inner_dim *= grad.dim_size(d); } const TKey N = indices.dim_size(0); OP_REQUIRES( ctx, grad.dim_size(0) == N, errors::InvalidArgument( "grad must be the same size as indices in the first dimension.")); OP_REQUIRES(ctx, inner_dim > 0, errors::InvalidArgument( "Inner dimension should be greater than zero.")); if (N > 0) { if (inner_dim > 0) { auto indices_vec = indices.vec<TKey>(); auto grad_flat = grad.flat_outer_dims<TValue>(); TValue lr_scalar = lr.scalar<TValue>()(); TStep gs = global_step.scalar<TStep>()(); for (int64 i = 0; i < N; i++) { const TKey index = indices_vec(i); auto a = accum->flat(index, gs); auto g = grad_flat.template chip<0>(i); auto v = var->flat(index, gs); a += g.square(); v -= g.constant(lr_scalar) * g * a.rsqrt(); } } } } private: bool use_exclusive_lock_; }; #define REGISTER_KERNELS(ktype, vtype, stype) \ REGISTER_KERNEL_BUILDER(Name("EVSparseApplyAdagrad") \ .Device(DEVICE_CPU) \ .TypeConstraint<ktype>("Tkey") \ .TypeConstraint<vtype>("Tvalue") \ .TypeConstraint<stype>("Tstep"), \ EVSparseApplyAdagradOp<ktype, vtype, stype>); #define REGISTER_CPU_KERNELS(T) \ REGISTER_KERNELS(int32, T, int32); \ REGISTER_KERNELS(int32, T, int64); \ REGISTER_KERNELS(int64, T, int32); \ REGISTER_KERNELS(int64, T, int64); REGISTER_CPU_KERNELS(float); #undef REGISTER_CPU_KERNELS #undef REGISTER_KERNELS template <typename TKey, typename TValue, typename TStep> class EVSparseApplyAdamOp : public OpKernel { public: explicit EVSparseApplyAdamOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_)); } void Compute(OpKernelContext* ctx) { auto locks = MaybeLockEmbeddingVariableInputMutexesInOrder<TKey, TValue>( ctx, use_exclusive_lock_, {0, 1, 2}); EmbeddingVar<TKey, TValue>* var = nullptr; OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &var)); EmbeddingVar<TKey, TValue>* m = nullptr; OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 1), &m)); EmbeddingVar<TKey, TValue>* v = nullptr; OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 2), &v)); const Tensor& beta1_power = ctx->input(3); const Tensor& beta2_power = ctx->input(4); const Tensor& lr = ctx->input(5); const Tensor& beta1 = ctx->input(6); const Tensor& beta2 = ctx->input(7); const Tensor& epsilon = ctx->input(8); const Tensor& grad = ctx->input(9); const Tensor& indices = ctx->input(10); const Tensor& global_step = ctx->input(11); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta1_power.shape()), errors::InvalidArgument("beta1_power is not a scalar: ", beta1_power.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta2_power.shape()), errors::InvalidArgument("beta2_power is not a scalar: ", beta2_power.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr.shape()), errors::InvalidArgument("lr is not a scalar: ", lr.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta1.shape()), errors::InvalidArgument("beta1 is not a scalar: ", beta1.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta2.shape()), errors::InvalidArgument("beta2 is not a scalar: ", beta2.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(epsilon.shape()), errors::InvalidArgument("epsilon is not a scalar: ", epsilon.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(indices.shape()), errors::InvalidArgument("indices must be one-dimensional")); int64 inner_dim = 1; TensorShape var_shape({var->Size(), var->ValueLen()}); for (int d = 1; d < var_shape.dims(); d++) { OP_REQUIRES(ctx, var_shape.dim_size(d) == grad.dim_size(d), errors::InvalidArgument(strings::StrCat( "var and grad must match in dimension ", d))); inner_dim *= grad.dim_size(d); } OP_REQUIRES(ctx, inner_dim > 0, errors::InvalidArgument( "Inner dimension should be greater than zero.")); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(global_step.shape()), errors::InvalidArgument("global_step is not a scalar: ", global_step.shape().DebugString())); const int64 N = indices.dim_size(0); OP_REQUIRES( ctx, grad.dim_size(0) == N, errors::InvalidArgument( "grad must be the same size as indices in the first dimension.")); if (N > 0) { TValue beta1_power_scalar = beta1_power.scalar<TValue>()(); TValue beta2_power_scalar = beta2_power.scalar<TValue>()(); TValue lr_scalar = lr.scalar<TValue>()(); TValue beta1_scalar = beta1.scalar<TValue>()(); TValue beta2_scalar = beta2.scalar<TValue>()(); TValue epsilon_scalar = epsilon.scalar<TValue>()(); const TValue alpha = lr_scalar * Eigen::numext::sqrt(static_cast<TValue>(1) - beta2_power_scalar) / (static_cast<TValue>(1) - beta1_power_scalar); auto DoWork = [this, ctx, inner_dim, &var, &m, &v, &grad, &indices, &beta1_power_scalar, &beta2_power_scalar, &lr_scalar, &beta1_scalar, &beta2_scalar, &epsilon_scalar, &alpha, &global_step](int64 start_i, int64 limit_i) { if (inner_dim > 0) { auto grad_flat = grad.flat_outer_dims<TValue>(); auto indices_vec = indices.vec<TKey>(); TStep gs = global_step.scalar<TStep>()(); for (int64 i = static_cast<int64>(start_i); i < static_cast<int64>(limit_i); i++) { const TKey index = indices_vec(i); auto var_i = var->flat(index, gs); auto m_a = m->flat(index, gs); auto v_a = v->flat(index, gs); auto g = grad_flat.template chip<0>(i); m_a += (g - m_a) * (static_cast<TValue>(1) - beta1_scalar); v_a += (g.square() - v_a) * (static_cast<TValue>(1) - beta2_scalar); var_i -= (m_a * alpha) / (v_a.sqrt() + epsilon_scalar); } } }; const int64 cost = 1000; auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads()); Shard(worker_threads.num_threads, worker_threads.workers, N, cost, DoWork); } } private: bool use_exclusive_lock_; }; #define REGISTER_KERNELS(ktype, vtype, stype) \ REGISTER_KERNEL_BUILDER(Name("EVSparseApplyAdam") \ .Device(DEVICE_CPU) \ .TypeConstraint<ktype>("Tkey") \ .TypeConstraint<vtype>("Tvalue") \ .TypeConstraint<stype>("Tstep"), \ EVSparseApplyAdamOp<ktype, vtype, stype>); #define REGISTER_CPU_KERNELS(T) \ REGISTER_KERNELS(int32, T, int32); \ REGISTER_KERNELS(int32, T, int64); \ REGISTER_KERNELS(int64, T, int32); \ REGISTER_KERNELS(int64, T, int64); REGISTER_CPU_KERNELS(float); #undef REGISTER_CPU_KERNELS #undef REGISTER_KERNELS template <typename TKey, typename TValue> class EVExportOp : public OpKernel { public: explicit EVExportOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} void Compute(OpKernelContext* ctx) { EmbeddingVar<TKey, TValue>* ev = nullptr; OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &ev)); std::vector<TKey> key_list; std::vector<TValue*> valueptr_list; int64 total_size = ev->GetSnapshot(&key_list, &valueptr_list); Tensor* key = nullptr; Tensor* val = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({total_size}), &key)); OP_REQUIRES_OK( ctx, ctx->allocate_output(1, TensorShape({total_size, ev->ValueLen()}), &val)); auto key_flat = key->flat<TKey>(); auto val_matrix = val->matrix<TValue>(); for (size_t i = 0; i < total_size; ++i) { key_flat(i) = key_list[i]; TValue* value = valueptr_list[i]; Eigen::array<Eigen::DenseIndex, 1> dims({ev->ValueLen()}); typename TTypes<TValue>::Flat value_flat = typename TTypes<TValue>::Flat(value, dims); for (int64 j = 0; j < ev->ValueLen(); ++j) { val_matrix(i, j) = value_flat(j); } } } }; #define REGISTER_KERNELS(ktype, vtype) \ REGISTER_KERNEL_BUILDER(Name("EVExport") \ .Device(DEVICE_CPU) \ .TypeConstraint<ktype>("Tkey") \ .TypeConstraint<vtype>("Tvalue"), \ EVExportOp<ktype, vtype>); #define REGISTER_CPU_KERNELS(T) \ REGISTER_KERNELS(int32, T); \ REGISTER_KERNELS(int64, T); REGISTER_CPU_KERNELS(float); #undef REGISTER_CPU_KERNELS #undef REGISTER_KERNELS template <typename TKey, typename TValue> class EVImportOp : public OpKernel { public: explicit EVImportOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} void Compute(OpKernelContext* ctx) { EmbeddingVar<TKey, TValue>* ev = nullptr; OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &ev)); Tensor key = ctx->input(1); Tensor val = ctx->input(2); auto key_flat = key.flat<TKey>(); auto val_matrix = val.matrix<TValue>(); for (size_t i = 0; i < key.NumElements(); ++i) { auto value = &val_matrix(i, 0); ev->LookupOrCreate(key_flat(i), value); } } }; #define REGISTER_KERNELS(ktype, vtype) \ REGISTER_KERNEL_BUILDER(Name("EVImport") \ .Device(DEVICE_CPU) \ .TypeConstraint<ktype>("Tkey") \ .TypeConstraint<vtype>("Tvalue"), \ EVImportOp<ktype, vtype>); #define REGISTER_CPU_KERNELS(T) \ REGISTER_KERNELS(int32, T); \ REGISTER_KERNELS(int64, T); REGISTER_CPU_KERNELS(float); #undef REGISTER_CPU_KERNELS #undef REGISTER_KERNELS } // namespace ev } // namespace tensorflow
39.923445
89
0.60127
cockroachzl
ebb37f29c1e2289098c93178b79cf1985335ada9
3,228
cpp
C++
codeforces/E - Mrx Kitayuta's Gift/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/E - Mrx Kitayuta's Gift/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/E - Mrx Kitayuta's Gift/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Mar/01/2020 04:02 * solution_verdict: Accepted language: GNU C++14 * run_time: 3400 ms memory_used: 679000 KB * problem: https://codeforces.com/contest/506/problem/E ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const long N=1e6; string ss;long p; const long mod=10007; long big(long b,long p) { long ret=1; while(p) { if(p&1)ret=(1LL*ret*b)%mod;b=(1LL*b*b)%mod;p/=2; } return ret; } vector<int>berlekampMassey(vector<int>x) { vector<int>ls,cur;int lf,ld; for(int i=0;i<(int)x.size();i++) { long t=0; for(int j=0;j<(int)cur.size();j++)t=(t+x[i-j-1]*(long)cur[j])%mod; if((t-x[i])%mod==0)continue; if(!cur.size()) { cur.resize(i+1);lf=i;ld=(t-x[i])%mod;continue; } long k=-(x[i]-t)*big(ld,mod-2)%mod; vector<int>c(i-lf-1);c.push_back(k); for(int j=0;j<ls.size();j++)c.push_back(-ls[j]*k%mod); if(c.size()<cur.size())c.resize(cur.size()); for(int j=0;j<cur.size();j++) c[j]=(c[j]+cur[j])%mod; if(i-lf+(int)ls.size()>=(int)cur.size()) ls=cur,lf=i,ld=(t-x[i])%mod; cur=c; } for(int i=0;i<cur.size();i++) cur[i]=(cur[i]%mod+mod)%mod; return cur; } int m; long a[N+2],h[N+2],t_[N+2],s[N+2],t[N+2]; void mul(long*p,long*q) { for(int i=0;i<m+m;i++)t_[i]=0; for(int i=0;i<m;i++)if(p[i]) for(int j=0;j<m;++j) t_[i+j]=(t_[i+j]+p[i]*q[j])%mod; for(int i=m+m-1;i>=m;i--)if(t_[i]) for(int j=m-1;~j;j--) t_[i-j-1]=(t_[i-j-1]+t_[i]*h[j])%mod; for(int i=0;i<m;++i)p[i]=t_[i]; } long calc(long k) { for(int i=m;~i;--i)s[i]=t[i]=0; s[0]=1;if(m!=1)t[1]=1;else t[0]=h[0]; while(k) { if(k&1)mul(s,t);mul(t,t);k>>=1; } long su=0; for(int i=0;i<m;i++)su=(su+s[i]*a[i])%mod; return (su%mod+mod)%mod; } void work(vector<int>x)//first element should be non zero { vector<int>v=berlekampMassey(x);m=v.size(); for(int i=0;i<m;i++)h[i]=v[i],a[i]=x[i]; } long dp[2000+2][200+2][200+2]; long dfs(long i,long a,long b) { long j=p-1-i; if(i>j)return a>b; if(i==j) { if(a>b)return 26;if(a==b)return 1; return 0; } if(a>b)return big(26,(p+1)/2-i); if(dp[p-i*2][a][b]!=-1)return dp[p-i*2][a][b]; //if(a==b)return pw((p+1)/2-i-1); long now=0; if(ss[a]==ss[b]) { now=(now+25*dfs(i+1,a,b))%mod; now=(now+dfs(i+1,a+1,b-1))%mod; } else { now=(now+24*dfs(i+1,a,b))%mod; now=(now+dfs(i+1,a+1,b)+dfs(i+1,a,b-1))%mod; } return dp[p-i*2][a][b]=now; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int k;cin>>ss>>k; p=ss.size()+k; vector<int>v;memset(dp,-1,sizeof(dp)); if(k<=1800)cout<<dfs(0,0,ss.size()-1)<<endl,exit(0); for(int i=1;i<=1800;i++) { p=ss.size()+i; //if(i<=5)cout<<dfs(0,0,ss.size()-1)<<endl; v.push_back(dfs(0,0,ss.size()-1)); } work(v);cout<<calc(k-1)<<endl; return 0; }
27.12605
111
0.480793
kzvd4729
ebb6fe74a054bfc18a4bfe706895f8d1fe46c452
1,100
hpp
C++
libraries/fc/include/fc/rpc/websocket_api.hpp
titans-world/titan-core
f358f48290f3501b26b26eff6a1e57bf6c077d79
[ "MIT" ]
8
2020-11-29T20:19:52.000Z
2021-11-02T21:01:41.000Z
libraries/fc/include/fc/rpc/websocket_api.hpp
titans-world/titan-core
f358f48290f3501b26b26eff6a1e57bf6c077d79
[ "MIT" ]
5
2021-03-06T10:58:34.000Z
2021-08-07T09:51:09.000Z
libraries/fc/include/fc/rpc/websocket_api.hpp
titans-world/titan-core
f358f48290f3501b26b26eff6a1e57bf6c077d79
[ "MIT" ]
5
2020-10-22T17:01:27.000Z
2022-02-02T12:53:47.000Z
#pragma once #include <fc/rpc/api_connection.hpp> #include <fc/rpc/state.hpp> #include <fc/network/http/websocket.hpp> #include <fc/io/json.hpp> #include <fc/reflect/variant.hpp> namespace fc { namespace rpc { class websocket_api_connection : public api_connection { public: websocket_api_connection( fc::http::websocket_connection& c, uint32_t max_conversion_depth ); ~websocket_api_connection(); virtual variant send_call( api_id_type api_id, string method_name, variants args = variants() ) override; virtual variant send_callback( uint64_t callback_id, variants args = variants() ) override; virtual void send_notice( uint64_t callback_id, variants args = variants() ) override; protected: std::string on_message( const std::string& message, bool send_message = true ); fc::http::websocket_connection& _connection; fc::rpc::state _rpc_state; }; } } // namespace fc::rpc
29.72973
102
0.621818
titans-world
ebba6d0cb003008045f684259ddedc4aa3d7e804
3,029
cpp
C++
tools/bin2h/bin2h.cpp
mouzedrift/alive
7c297a39c60e930933c0a93ea373226907f8b1c7
[ "MIT" ]
131
2015-03-21T14:10:21.000Z
2021-01-19T03:54:04.000Z
tools/bin2h/bin2h.cpp
mouzedrift/alive
7c297a39c60e930933c0a93ea373226907f8b1c7
[ "MIT" ]
51
2015-04-06T17:24:45.000Z
2018-02-03T14:36:37.000Z
tools/bin2h/bin2h.cpp
mouzedrift/alive
7c297a39c60e930933c0a93ea373226907f8b1c7
[ "MIT" ]
17
2015-10-07T10:20:47.000Z
2021-08-02T04:14:11.000Z
#include <iostream> #include <string> #include <fstream> #include <sstream> #include <iomanip> #include <vector> int main(int argc, char** argv) { if (argc != 4) { std::cout << "bin2h - Convert any file to a header file" << std::endl; std::cout << "Usage: Input file, output file, array name" << std::endl; return 1; } const std::string inputFileName(argv[1]); // Open input file std::fstream inFile(inputFileName.c_str(), std::ios::in | std::ios::binary); if (!inFile) { std::cout << "Failed to open " << inputFileName << " for reading" << std::endl; return 1; } // Get input file size inFile.seekg(0, inFile.end); const std::streamoff inFileSizeBytes = inFile.tellg(); inFile.seekg(0, inFile.beg); // Read input into a buffer std::vector<unsigned char> inFileBytes(static_cast<size_t>(inFileSizeBytes)); inFile.read(reinterpret_cast<char *>(inFileBytes.data()), inFileBytes.size()); // Create temporary output file const std::string outputFileName(argv[2]); std::fstream outFile(outputFileName.c_str(), std::ios::out | std::ios::binary); if (!outFile) { std::cout << "Failed to open " << outputFileName << " for writing" << std::endl; return 1; } const std::string pragmaOnce = "#pragma once"; outFile.write(pragmaOnce.data(), pragmaOnce.length()); outFile << std::endl; outFile << std::endl; const std::string generated = "// This header was generated from " + inputFileName + ", any local changes will be lost"; outFile.write(generated.data(), generated.length()); outFile << std::endl; outFile << std::endl; // Write the generated header const std::string headerStart("#include <vector>\n\nstd::vector<unsigned char> get_" + std::string(argv[3]) + "()\n{\n const static unsigned char temp[] ="); outFile.write(headerStart.data(), headerStart.length()); outFile << std::endl; const std::string arrayStart = " {"; outFile.write(arrayStart.data(), arrayStart.length()); outFile << std::endl; // Write out each byte of the input as hex std::stringstream ss; size_t breakPos = 0; for (size_t idx = 0; idx < inFileBytes.size(); idx++) { if (breakPos == 0) { ss << " "; } ss << "0x" << std::hex << std::setfill('0') << std::setw(2) << static_cast<unsigned int>(inFileBytes[idx]); if (idx+1 != inFileBytes.size()) { ss << ", "; } breakPos++; if (breakPos > 18) { breakPos = 0; ss << "\n"; } } const std::string arrayData = ss.str(); outFile.write(arrayData.data(), arrayData.length()); outFile << std::endl; const std::string arrayEnd = " };\n return std::vector<unsigned char>(std::begin(temp), std::end(temp));\n}\n"; outFile.write(arrayEnd.data(), arrayEnd.length()); outFile << std::endl; return 0; }
30.908163
164
0.585672
mouzedrift
ebbc404254ad9a5d6f52e4a62c2f759a2b16bdd5
1,231
cpp
C++
benchmarks/helmholtz/searchSpacergpu2t/hhz.baked.cpp
pssrawat/artemis
b69621553325b66f0367bf8f9d93605c885aa19d
[ "FSFAP" ]
12
2019-06-17T13:49:41.000Z
2021-11-22T08:47:18.000Z
benchmarks/helmholtz/searchSpacergpu2t/hhz.baked.cpp
pssrawat/artemis
b69621553325b66f0367bf8f9d93605c885aa19d
[ "FSFAP" ]
null
null
null
benchmarks/helmholtz/searchSpacergpu2t/hhz.baked.cpp
pssrawat/artemis
b69621553325b66f0367bf8f9d93605c885aa19d
[ "FSFAP" ]
5
2019-06-17T13:49:52.000Z
2021-11-22T08:47:19.000Z
#include "common/common.hpp" #include "common/timer.hpp" #include "hhz.gold.h" #include <cassert> #include <cstdio> #include <iostream> #include <fstream> using std::cout; #define TIMESTEPS 2 #define ORDER 2 extern "C" void host_code (double *h_in, double *h_out, double *h_t, double a, double b, double h2inv, int L, int M, int N); int main(int argc, char** argv) { int N = 512; double *out = getZero3DArray<double>(N, N, N); double *t = getZero3DArray<double>(N, N, N); double a = 0.12, b = 0.1, h2inv = 0.4; double *in_dev = new double[N * N * N]; std::ifstream infile ("test.txt",std::ofstream::binary); infile.read((char *) in_dev, N * N * N * sizeof(double)); infile.close(); double *in = new double[N * N * N]; std::ifstream goldfile ("gold.txt",std::ofstream::binary); goldfile.read((char *) in, N * N * N * sizeof(double)); goldfile.close(); host_code(in_dev, out, t, a, b, h2inv, N, N, N); double error = checkError3D<double> (N, N, (double*)in, (double*) out, TIMESTEPS * ORDER, N-TIMESTEPS * ORDER, TIMESTEPS * ORDER, N-TIMESTEPS * ORDER, TIMESTEPS * ORDER, N-TIMESTEPS * ORDER); printf("[Test] RMS Error : %e\n",error); if (error > TOLERANCE) { return -1; } }
30.02439
131
0.636881
pssrawat
ebc2fd2cfeae3b8c54f474ca848f7940b5571fc6
904
cpp
C++
CWin/CWin/events/event_exception.cpp
benbraide/CWin
0441b48a71fef0dbddabf61033d7286669772c1e
[ "MIT" ]
null
null
null
CWin/CWin/events/event_exception.cpp
benbraide/CWin
0441b48a71fef0dbddabf61033d7286669772c1e
[ "MIT" ]
null
null
null
CWin/CWin/events/event_exception.cpp
benbraide/CWin
0441b48a71fef0dbddabf61033d7286669772c1e
[ "MIT" ]
null
null
null
#include "event_exception.h" cwin::events::exception::bad_value::bad_value() : base("Cannot assign specified value to event"){} cwin::events::exception::bad_value::~bad_value() = default; cwin::events::exception::code cwin::events::exception::bad_value::get_code() const{ return code::bad_value; } cwin::events::exception::missing_arg::missing_arg() : base("Missing required argument for event"){} cwin::events::exception::missing_arg::~missing_arg() = default; cwin::events::exception::code cwin::events::exception::missing_arg::get_code() const{ return code::missing_arg; } cwin::events::exception::incompatible_arg::incompatible_arg() : base("Incompatible required argument for event"){} cwin::events::exception::incompatible_arg::~incompatible_arg() = default; cwin::events::exception::code cwin::events::exception::incompatible_arg::get_code() const{ return code::incompatible_arg; }
31.172414
90
0.753319
benbraide
ebc3c190bfbd0037971d839939f2b2fb37b2815a
996
cpp
C++
Source/modules/imogen_dsp/imogen_dsp.cpp
msameen99/imogen
7efd3054a93d91f44f22cc2d6200f550e4aedd4c
[ "MIT" ]
109
2020-11-24T05:17:12.000Z
2022-03-25T17:03:16.000Z
Source/modules/imogen_dsp/imogen_dsp.cpp
msameen99/imogen
7efd3054a93d91f44f22cc2d6200f550e4aedd4c
[ "MIT" ]
7
2021-02-19T07:22:03.000Z
2022-03-17T17:23:56.000Z
Source/modules/imogen_dsp/imogen_dsp.cpp
msameen99/imogen
7efd3054a93d91f44f22cc2d6200f550e4aedd4c
[ "MIT" ]
4
2021-04-05T14:11:42.000Z
2021-10-02T15:46:49.000Z
#include "imogen_dsp.h" #include "Engine/effects/PreHarmony/StereoReducer.cpp" #include "Engine/effects/PreHarmony/InputGain.cpp" #include "Engine/effects/PreHarmony/NoiseGate.cpp" #include "Engine/effects/PreHarmonyEffects.cpp" #include "Engine/Harmonizer/Harmonizer.cpp" #include "Engine/Harmonizer/HarmonizerVoice.cpp" #include "Engine/Lead/LeadProcessor.cpp" #include "Engine/Lead/DryPanner.cpp" #include "Engine/Lead/PitchCorrector.cpp" #include "Engine/effects/PostHarmony/EQ.cpp" #include "Engine/effects/PostHarmony/Compressor.cpp" #include "Engine/effects/PostHarmony/DeEsser.cpp" #include "Engine/effects/PostHarmony/DryWetMixer.cpp" #include "Engine/effects/PostHarmony/Delay.cpp" #include "Engine/effects/PostHarmony/Reverb.cpp" #include "Engine/effects/PostHarmony/OutputGain.cpp" #include "Engine/effects/PostHarmony/Limiter.cpp" #include "Engine/effects/PostHarmonyEffects.cpp" #include "Engine/Engine.cpp" #include "Processor/Processor.cpp"
32.129032
55
0.785141
msameen99
ebc72d51738062c83c2e26f607a74611c1b65013
7,082
cpp
C++
gui_new/mainwindow.cpp
wddcbfree/MiniWord-4th-Semester
699febced0763b70431496651013844fe415bd04
[ "MIT" ]
null
null
null
gui_new/mainwindow.cpp
wddcbfree/MiniWord-4th-Semester
699febced0763b70431496651013844fe415bd04
[ "MIT" ]
null
null
null
gui_new/mainwindow.cpp
wddcbfree/MiniWord-4th-Semester
699febced0763b70431496651013844fe415bd04
[ "MIT" ]
null
null
null
#include <QDialog> #include <QAction> #include <QWidget> #include <QDebug> #include <QFileDialog> #include <QMenuBar> #include <QMessageBox> #include <QStatusBar> #include <QToolBar> #include <QLineEdit> #include <QSize> #include <string> #include <QTextStream> #include <QDataStream> #include <vector> #include <QPushButton> #include <QLabel> #include <QPainter> #include <QKeyEvent> #include <QKeySequence> #include <QString> #include <QCloseEvent> #include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { setWindowTitle(tr("MiniWord")); this->setFixedSize(WINDOW_WIDTH,WINDOW_HEIGHT); //菜单栏 createAction = new QAction(tr("新文件"), this); createAction->setShortcuts(QKeySequence::New); createAction->setStatusTip(tr("Create a file")); connect(createAction, &QAction::triggered, this, &MainWindow::create); openAction = new QAction(tr("打开..."), this); openAction->setShortcuts(QKeySequence::Open); openAction->setStatusTip(tr("Open an existing file")); connect(openAction, &QAction::triggered, this, &MainWindow::open); saveAction = new QAction(tr("保存"), this); saveAction->setShortcuts(QKeySequence::Save); saveAction->setStatusTip(tr("Save current file")); connect(saveAction, &QAction::triggered, this, &MainWindow::save); saveasAction = new QAction(tr("另存为..."), this); saveasAction->setShortcuts(QKeySequence::SaveAs); saveasAction->setStatusTip(tr("Save as...")); connect(saveasAction, &QAction::triggered, this, &MainWindow::save_as); quitAction = new QAction(tr("退出"),this); quitAction->setShortcuts(QKeySequence::Quit); quitAction->setStatusTip(tr("Quit")); connect(quitAction,&QAction::triggered,this,&MainWindow::close); searchAction = new QAction(tr("查找..."),this); searchAction->setShortcuts(QKeySequence::Find); searchAction->setStatusTip(tr("Search...")); connect(searchAction,&QAction::triggered,this,&MainWindow::search); replaceAction = new QAction(tr("替换"),this); replaceAction->setShortcuts(QKeySequence::Replace); replaceAction->setStatusTip(tr("Replace")); connect(replaceAction,&QAction::triggered,this,&MainWindow::search); selectAction = new QAction(tr("选中块"),this); selectAction->setStatusTip(tr("Select")); QMenu *file = menuBar()->addMenu(tr("&文件")); file->addAction(createAction); file->addSection(""); file->addAction(openAction); file->addAction(saveAction); file->addAction(saveasAction); file->addSection(""); file->addAction(quitAction); QMenu *edit = menuBar()->addMenu(tr("&编辑")); edit->addAction(searchAction); edit->addAction(replaceAction); edit->addSection(""); edit->addAction(selectAction); QMenu *info = menuBar()->addMenu(tr("&关于")); //info->addAction(aboutRole); //输入框部分 Input.setParent(this); Input.setGeometry(INPUT_LEFT_BLANK,WINDOW_HEIGHT-2*LINE_HEIGHT,WINDOW_WIDTH-2*INPUT_LEFT_BLANK,LINE_HEIGHT); Input.show(); Input.setEchoMode(QLineEdit::Normal); Input.setPlaceholderText("type..."); Input.setReadOnly(1); Input.setAcceptDrops(true); Input.setClearButtonEnabled(true); connect(&Input,&QLineEdit::returnPressed,this,&MainWindow::input_return_pressed); //输入提示 InputTips.setParent(this); InputTips.setGeometry(INPUT_LEFT_BLANK,WINDOW_HEIGHT-3*LINE_HEIGHT,WINDOW_WIDTH-2*INPUT_LEFT_BLANK,LINE_HEIGHT); InputTips.show(); InputTips.setText("test"); // InitiateSceen(); //状态栏 statusBar(); } MainWindow::~MainWindow() { } void MainWindow::closeEvent(QCloseEvent *event) { if(filepart->is_edited()){ QMessageBox msgBox; msgBox.setText(tr("还有未保存的修改,是否保存?")); msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard); msgBox.setButtonText(QMessageBox::Save,"保存"); msgBox.setButtonText(QMessageBox::Discard,"不保存"); msgBox.setDefaultButton(QMessageBox::Save); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Save: save(); qDebug() << "保存!"; break; case QMessageBox::Discard: qDebug() << "不保存!"; break; } } filepart->clearData(); } void MainWindow::create(){ if(!filepart->is_edited()){ QMessageBox msgBox; msgBox.setText(tr("还有未保存的修改,是否保存?")); msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard); msgBox.setButtonText(QMessageBox::Save,"保存"); msgBox.setButtonText(QMessageBox::Discard,"不保存"); msgBox.setDefaultButton(QMessageBox::Save); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Save: save(); qDebug() << "保存!"; break; case QMessageBox::Discard: qDebug() << "不保存!"; break; } } emit SendCreateSignal(); } void MainWindow::open(){ QString FilePath = QFileDialog::getOpenFileName(this,tr("打开...")); qDebug()<<FilePath<<endl; emit SendOpenPath(FilePath); statusBar()->showMessage("打开成功!"); } void MainWindow::save(){ if(filepart->is_open()){ QString FilePath; if(filepart->is_create()){ FilePath = QFileDialog::getSaveFileName(this,tr("保存为..."),"新建文档.txt"); } emit SendSavePath(FilePath); statusBar()->showMessage("保存成功!"); } } void MainWindow::save_as(){ QString FilePath = QFileDialog::getSaveFileName(this,tr("另存为..."),"新建文档.txt"); emit SendSaveAsPath(FilePath); } void MainWindow::keyReleaseEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_1: Input.setReadOnly(0); Input.setPlaceholderText("typing..."); break; //case Qt::Key_Delete: //default: //break; } } void MainWindow::input_return_pressed(){ qDebug()<<"return success!"; /*if(Input.size() == 0) //插入空行 else //插入现有数据,然后清空*/ } void MainWindow::search(){ QDialog SearchDialog(this); SearchDialog.setSizeIncrement(410,4*LINE_HEIGHT); SearchDialog.setWindowTitle("查找"); SearchDialog.setModal(0); QLineEdit SearchInput(&SearchDialog),ReplaceInput(&SearchDialog); SearchInput.setGeometry(INPUT_LEFT_BLANK,LINE_GAP,200-2*INPUT_LEFT_BLANK,LINE_HEIGHT); SearchInput.setPlaceholderText("输入要查找的内容..."); ReplaceInput.setGeometry(210+INPUT_LEFT_BLANK,LINE_GAP,200-2*INPUT_LEFT_BLANK,LINE_HEIGHT); ReplaceInput.setPlaceholderText("替换为..."); QPushButton Search(&SearchDialog),SearchNext(&SearchDialog),Replace(&SearchDialog); Search.setGeometry(INPUT_LEFT_BLANK,2*LINE_GAP+LINE_HEIGHT,200-2*INPUT_LEFT_BLANK,LINE_HEIGHT); Search.setText("查找"); Search.setStyleSheet("color:black"); SearchNext.setGeometry(INPUT_LEFT_BLANK,3*LINE_GAP+2*LINE_HEIGHT,200-2*INPUT_LEFT_BLANK,LINE_HEIGHT); SearchNext.setText("下一个"); Replace.setGeometry(210+INPUT_LEFT_BLANK,2*LINE_GAP+LINE_HEIGHT,200-2*INPUT_LEFT_BLANK,LINE_HEIGHT); Replace.setText("替换"); SearchDialog.exec(); }
31.900901
116
0.671138
wddcbfree
ebc82ff643e64b2b2895a6ac44bae4c639ff4f58
1,342
cpp
C++
山东大学/Day03资料/cv/03imgdraw/cv03_draw_arrowline.cpp
QiangAI/AI_CPlus
8359f4ed6e94eacda6d1e9d057defad5bb9792a0
[ "Apache-2.0" ]
3
2021-01-11T03:31:55.000Z
2021-05-18T06:50:44.000Z
山东大学/Day03资料/cv/03imgdraw/cv03_draw_arrowline.cpp
QiangAI/AI_CPlus
8359f4ed6e94eacda6d1e9d057defad5bb9792a0
[ "Apache-2.0" ]
null
null
null
山东大学/Day03资料/cv/03imgdraw/cv03_draw_arrowline.cpp
QiangAI/AI_CPlus
8359f4ed6e94eacda6d1e9d057defad5bb9792a0
[ "Apache-2.0" ]
1
2021-01-12T06:48:52.000Z
2021-01-12T06:48:52.000Z
#include <opencv2/opencv.hpp> #include <iostream> #define WIN_W 400 #define WIN_H 300 int main(int argc, const char** argv) { cv::namedWindow("Win_draw", cv::WINDOW_NORMAL); cv::resizeWindow("Win_draw", WIN_W, WIN_H); cv::moveWindow("Win_draw", (1280 - WIN_W) / 2, (800 - WIN_H) / 2); /////////////////////////////////// // 构造一副图像 cv::Mat image(WIN_H, WIN_W, CV_8UC4); // 图像格式4个无符号字节(存放RGBA像素) /* void cv::arrowedLine( InputOutputArray img, Point pt1, Point pt2, const Scalar &color, int thickness=1, int line_type=8, int shift=0, double tipLength=0.1) // 头长度(整个直线的百分比) */ cv::arrowedLine( image, // 绘制的图像缓冲 cv::Point(100, 150), // 绘制直线的开始点 cv::Point(300, 150), // 绘制直线的结束点 cv::Scalar(255, 0, 0, 0), // 绘制直线的颜色(BGRA)或者使用cv::RGB()宏 1, // 线条的粗细 cv::LINE_AA, // 绘制线条的算法 0, // 坐标点的小数位数 0.1 ); cv::imshow("Win_draw", image); /////////////////////////////////// cv::waitKey(); return 0; } // 编译命令:g++ -omain cv03_draw_arrowline.cpp -std=c++11 -I/usr/local/include/opencv4 -lopencv_core -lopencv_highgui -lopencv_imgcodecs -lopencv_imgproc
32.731707
151
0.502981
QiangAI
1b0b499629d7cff396d0d7eda2be7043368bed07
2,109
cpp
C++
Codeforces/C++/1579E2.cpp
shresth12-jain/HacktoberFest2021
43bd5d99668c104f89f3efef5313e4ddadd9931a
[ "Apache-2.0" ]
11
2021-10-01T06:53:31.000Z
2022-02-05T20:36:20.000Z
Codeforces/C++/1579E2.cpp
shresth12-jain/HacktoberFest2021
43bd5d99668c104f89f3efef5313e4ddadd9931a
[ "Apache-2.0" ]
37
2021-10-01T06:54:01.000Z
2021-10-20T18:02:31.000Z
Codeforces/C++/1579E2.cpp
shresth12-jain/HacktoberFest2021
43bd5d99668c104f89f3efef5313e4ddadd9931a
[ "Apache-2.0" ]
110
2021-10-01T06:51:28.000Z
2021-10-31T18:00:55.000Z
#include<bits/stdc++.h> using namespace std; #define ll long long #define mod ((ll)1e9+7) #define test ll t; cin>>t; while(t--) #define speed ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define F first #define S second void fileIO() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } struct Query { ll l, r, x, idx; }; struct ArrayElement { ll val, idx; }; bool cmp1(Query q1, Query q2) { return q1.x < q2.x; } bool cmp2(ArrayElement x, ArrayElement y) { return x.val < y.val; } void update(ll bit[], ll idx, ll val, ll n) { for (; idx <= n; idx += idx & -idx) bit[idx] += val; } ll query(ll bit[], ll idx, ll n) { ll sum = 0; for (; idx > 0; idx -= idx & -idx) sum += bit[idx]; return sum; } void answerQueries(ll n, Query queries[], ll q, ArrayElement arr[], vector<ll>&anss) { ll bit[n + 1]; memset(bit, 0, sizeof(bit)); sort(arr, arr + n, cmp2); sort(queries, queries + q, cmp1); ll curr = 0; for (ll i = 0; i < q; i++) { while (arr[curr].val <= queries[i].x && curr < n) { update(bit, arr[curr].idx + 1, 1, n); curr++; } anss[queries[i].idx] = query(bit, queries[i].r + 1, n) - query(bit, queries[i].l, n); } } int main() { speed fileIO(); test{ ll n; cin >> n; vector<ll> a(n); ArrayElement arr[n]; for (ll i = 0; i < n; i++) { cin >> a[i]; arr[i].val = a[i]; arr[i].idx = i; } Query queries[n - 1]; for (ll i = 1; i < n; i++) { queries[i - 1].l = 0, queries[i - 1].r = i - 1, queries[i - 1].x = a[i]; queries[i - 1].idx = i - 1; } vector<ll> anss(n - 1); answerQueries(n, queries, n - 1, arr, anss); ll ans = 0; map<ll, ll> mp; for (ll i = 0; i < n; i++) { if (i == 0) { mp[a[i]]++; } else { ll smallerEqual = anss[i - 1]; ll smaller = 0; ll greater = i - smallerEqual; if (mp.find(a[i]) == mp.end()) { smaller = smallerEqual; } else smaller = smallerEqual - mp[a[i]]; ans += min(smaller, greater); mp[a[i]]++; } } cout << ans << endl; } return 0; }
18.33913
75
0.531057
shresth12-jain
1b0fbe9ed4ab59280d4294c847d3e5e2d7f29cf5
9,366
hpp
C++
src/hexgrid_impl.hpp
MaemiKozue/hexceed
11ddcdfe3f7cadc23ca8ccba950df05fe49ce60a
[ "MIT" ]
null
null
null
src/hexgrid_impl.hpp
MaemiKozue/hexceed
11ddcdfe3f7cadc23ca8ccba950df05fe49ce60a
[ "MIT" ]
null
null
null
src/hexgrid_impl.hpp
MaemiKozue/hexceed
11ddcdfe3f7cadc23ca8ccba950df05fe49ce60a
[ "MIT" ]
null
null
null
#include "hexgrid.hpp" #include <vector> #include <utility> #include <opencv2/imgproc.hpp> using namespace std; using namespace cv; static int direction(int qa, int ra, int qb, int rb) { int dir = -1; int dq = qb - qa; int dr = rb - ra; if (dq * dq > 1 || dr * dr > 1 || dq == dr) { dir = -1; } else if (dq == 1) { dir = dr == 0 ? 1 : 0; } else if (dq == 0) { dir = dr == 1 ? 2 : 5; } else if (dq == -1) { dir = dr == 0 ? 4 : 3; } else { // cerr << "Non standard direction (" << dq << ", " << dr << ")" << endl; } return dir; } static int direction(pair<int, int> a, pair<int, int> b) { return direction(a.first, a.second, b.first, b.second); } /* --------- Cell --------- */ template<typename T> Hexgrid<T>::Cell::Cell(int q, int r, T& data) : v{}, q(q), r(r), data(data) { ;; } template<typename T> Hexgrid<T>::Cell::Cell() { ;; } template<typename T> void Hexgrid<T>::Cell::link(Hexgrid<T>::Cell& other) { int dir = direction(this->q, this->r, other.q, other.r); // Error if (dir < 0) { return; } this->link(dir, &other); } template<typename T> void Hexgrid<T>::Cell::link(int i, Hexgrid<T>::Cell *other) { if (other != nullptr) { this->v[i] = other; other->v[(i+3)%6] = this; } } template<typename T> void Hexgrid<T>::Cell::unlink(int i) { if (this->v[i] != nullptr) { this->v[i].v[(i+3) % 6] = nullptr; this->v[i] = nullptr; } } template<typename T> void Hexgrid<T>::Cell::unlink_all() { for (size_t i = 0; i < 6; i ++) { this->unlink(i); } } /* --------- Hexgrid --------- */ /* Hexgrid Cells */ vector<pair<int, int>> neighbors(int q, int r) { return { {q+1, r}, {q-1, r}, {q, r+1}, {q, r-1}, {q-1, r+1}, {q+1, r-1} }; } vector<pair<int, int>> neighbors(pair<int, int> p) { return neighbors(p.first, p.second); } template<typename T> void Hexgrid<T>::add(int q, int r, T& data) { pair<int, int> pos{q, r}; if (this->has(pos)) { this->grid[pos].data = data; } else { this->grid[pos] = Cell(q, r, data); Cell &cell = this->grid[pos]; for (auto& k : neighbors(pos)) { if (this->has(k)) { cell.link(this->grid[k]); } } } } template<typename T> void Hexgrid<T>::remove(int q, int r) { if (!this->has(q, r)) { return; } else { Cell& cell this->grid[{q, r}]; cell.unlink_all(); this->grid.erase({q, r}); } } template<typename T> bool Hexgrid<T>::has(pair<int, int> p) { return this->has(p.first, p.second); } template<typename T> bool Hexgrid<T>::has(int q, int r) { return this->grid.find({q, r}) != this->grid.end(); } template<typename T> T& Hexgrid<T>::get(int q, int r) { if (this->has(q, r)) { return this->grid[{q, r}]; } else { stringstream ss; ss << "Cell (" << q << ", " << r << ") does not exist"; throw out_of_range(ss.str()); } } template<typename T> bool Hexgrid<T>::get(int q, int r, T& data) { if (this->has(q, r)) { data = this->grid[{q, r}]; return true } else { return false; } } template<typename T> void Hexgrid<T>::set(int q, int r, T& data) { if (this->has(q, r)) { this->grid[{q, r}] = data; } else { this->add(q, r, data); } } /* Hexgrid Walls */ // This makes sure coordinates of A is lexically lower than of B static void normalize(int& qa, int& ra, int& qb, int& rb) { using std::swap; if (qb > qa) { swap(qa, qb); swap(ra, rb); } else if (qa == qb) { if (rb > ra) { swap(ra, rb); } } } template<typename T> void Hexgrid<T>::add_wall(int qa, int ra, int qb, int rb) { normalize(qa, ra, qb, rb); this->walls.insert({{qa, ra}, {qb, rb}}); } template<typename T> bool Hexgrid<T>::has_wall(int qa, int ra, int qb, int rb) { normalize(qa, ra, qb, rb); return this->walls.contains({{qa, ra}, {qb, rb}}); } template<typename T> void Hexgrid<T>::remove_wall(int qa, int ra, int qb, int rb) { normalize(qa, ra, qb, rb); this->walls.erase({{qa, ra}, {qb, rb}}); } /* Hexgrid drawing */ static void draw_centered_text(Mat& out, string s, int x, int y, Scalar color, double scale, int font = FONT_HERSHEY_SIMPLEX) { Size size = getTextSize(s, font, scale, 1, nullptr); Point pos = Point((int) (x - size.width / 2.), (int) (y + size.height/ 2.)); putText(out, s, pos, font, scale, color); } template<typename T> static void draw_neighbors(Mat& out, int x, int y, T& c, Scalar color, int r) { double a = 1. / 2.; double b = sqrt(3) / 2.; double px = a*b*r*.8; double py = -b*b*r*.8; // double rotate[][] = { // {a, -b}, // {b, a} // }; for (size_t i = 0; i < 6; i++) { stringstream ss; if (c.v[i] != nullptr) { ss << c.v[i]->q << "," << c.v[i]->r; } else { ss << "."; } string text = ss.str(); int text_x = (int) (x+px); int text_y = (int) (y+py); draw_centered_text(out, text, text_x, text_y, color, 0.005*r); double next_px, next_py; next_px = a * px - b * py; next_py = b * px + a * py; px = next_px; py = next_py; } } static void draw_hex(Mat& out, int x, int y, Scalar color = Scalar::all(0), int r = 100) { double sqrt_3 = sqrt(3); int c = (int) (r*sqrt_3/2.); int s = (int) (r/2.); Mat pts = (Mat_<int>(6, 2) << x, y+r, x+c, y+s, x+c, y-s, x, y-r, x-c, y-s, x-c, y+s ); polylines(out, pts, true, color); } template<typename T> static void draw_data(Mat& out, int x, int y, T data, Scalar color = Scalar::all(0), double scale = 1) { stringstream ss; ss << data; string label = ss.str(); Size label_size = getTextSize(label, FONT_HERSHEY_SIMPLEX, scale, 1, nullptr); Point label_pos = Point((int) (x - label_size.width / 2.), (int) (y + label_size.height/ 2.)); putText(out, label, label_pos, FONT_HERSHEY_SIMPLEX, scale, color); } static void draw_label(Mat& out, int x, int y, int q, int r, Scalar color, double scale) { stringstream ss; ss << "(" << q << ", " << r << ")"; string label = ss.str(); Size label_size = getTextSize(label, FONT_HERSHEY_SIMPLEX, scale, 1, nullptr); Point label_pos = Point((int) (x - label_size.width / 2.), (int) (y + 2.875 * label_size.height)); putText(out, label, label_pos, FONT_HERSHEY_SIMPLEX, scale, color); } static void draw_wall(Mat& out, int x, int y, int dir, int size, Scalar color, int thickness) { double vx, vy; switch (dir % 3) { case 0: { vx = sqrt(3) / 2.0; vy = 0.5; break; } case 1: { vx = 0; vy = 1; break; } case 2: { vx = sqrt(3) / 2.0; vy = - 0.5; break; } default: vx = 0; vy = 0; break; } Point a = Point((int) (x - vx * size / 2.0), (int) (y - vy * size / 2.0)); Point b = Point((int) (x + vx * size / 2.0), (int) (y + vy * size / 2.0)); // circle(out, Point(x, y), 5, color); line(out, a, b, color, thickness); } template<typename T> void Hexgrid<T>::draw(Mat& out, Scalar color, int size, int padding) { int l = size; int p = padding; int wall_thickness = 3; if (l < 0 || p < 0) return; double sqrt_3 = sqrt(3); int ox = (int) (out.cols / 2.); int oy = (int) (out.rows / 2.); int w = (int) (sqrt_3 * (l+p)); int w2 = (int) (sqrt_3 * (l+p) / 2.); int h = (int) ((l+p) * 3. / 2.); // Cell drawing for (auto& pr : this->grid) { auto& pos = pr.first; Cell& cell = pr.second; int q = pos.first == cell.q ? pos.first : -1; int r = pos.second == cell.r ? pos.second : -1; int x = ox + w * (q + r/2) + (r%2 * w2); // on purpose using r%2 == -1/0/1 int y = oy + h * r; circle(out, Point(x, y), 1, color, FILLED); draw_hex(out, x, y, color, l); draw_data(out, x, y, cell.data, color, l/50.); draw_neighbors(out, x, y, cell, color, l); draw_label(out, x, y, q, r, color, 0.375*l/50.); } // Wall drawing for (auto& wall : this->walls) { auto& pa = wall.first; auto& pb = wall.second; int qa = pa.first; int ra = pa.second; int qb = pb.first; int rb = pb.second; int xa = ox + w * (qa + ra/2) + (ra%2 * w2); int ya = oy + h * ra; int xb = ox + w * (qb + rb/2) + (rb%2 * w2); int yb = oy + h * rb; int x = (xa + xb) / 2; int y = (ya + yb) / 2; // circle(out, Point(xa, ya), 2, Scalar(0, 255, 0), FILLED); // circle(out, Point(xb, yb), 2, Scalar(0, 255, 0), FILLED); // line(out, Point(xa, ya), Point(xb, yb), Scalar(0, 255, 0)); int dir = direction(pa, pb); draw_wall(out, x, y, dir, l, Scalar(0, 0, 255), wall_thickness); } }
21.190045
125
0.492846
MaemiKozue
1b111d21d79c6673f0dea478714455ceb0d6da7a
5,152
cc
C++
test/src/LiveChannel/GetLiveChannelHistoryTest.cc
FunriLy/aliyun-oss-cpp-sdk
ca8bf8a3cdd0f89b846bffcb377675d15a36f3b4
[ "Apache-2.0" ]
null
null
null
test/src/LiveChannel/GetLiveChannelHistoryTest.cc
FunriLy/aliyun-oss-cpp-sdk
ca8bf8a3cdd0f89b846bffcb377675d15a36f3b4
[ "Apache-2.0" ]
null
null
null
test/src/LiveChannel/GetLiveChannelHistoryTest.cc
FunriLy/aliyun-oss-cpp-sdk
ca8bf8a3cdd0f89b846bffcb377675d15a36f3b4
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> #include <sstream> #include <gtest/gtest.h> #include <alibabacloud/oss/OssClient.h> #include "../Config.h" #include "../Utils.h" namespace AlibabaCloud { namespace OSS { class GetLiveChannelHistoryTest : public ::testing::Test { protected: GetLiveChannelHistoryTest() { } ~GetLiveChannelHistoryTest() override { } // Sets up the stuff shared by all tests in this test case. static void SetUpTestCase() { ClientConfiguration conf; conf.enableCrc64 = false; Client = std::make_shared<OssClient>(Config::Endpoint, Config::AccessKeyId, Config::AccessKeySecret, ClientConfiguration()); BucketName = TestUtils::GetBucketName("cpp-sdk-get-live-channel-history"); CreateBucketOutcome outCome = Client->CreateBucket(CreateBucketRequest(BucketName)); EXPECT_EQ(outCome.isSuccess(), true); } // Tears down the stuff shared by all tests in this test case. static void TearDownTestCase() { TestUtils::CleanBucket(*Client, BucketName); Client = nullptr; } // Sets up the test fixture. void SetUp() override { } // Tears down the test fixture. void TearDown() override { } public: static std::shared_ptr<OssClient> Client; static std::string BucketName; }; std::shared_ptr<OssClient> GetLiveChannelHistoryTest::Client = nullptr; std::string GetLiveChannelHistoryTest::BucketName = ""; TEST_F(GetLiveChannelHistoryTest, GetLiveChannelHistoryGetTest) { std::string channelName = "test-channel"; PutLiveChannelRequest request(BucketName, channelName, "HLS"); auto putOutcome = Client->PutLiveChannel(request); EXPECT_EQ(putOutcome.isSuccess(), true); GetLiveChannelHistoryRequest request2(BucketName, channelName); auto getOutcome = Client->GetLiveChannelHistory(request2); EXPECT_EQ(getOutcome.isSuccess(), true); EXPECT_EQ(getOutcome.result().LiveRecordList().size(), 0u); GetLiveChannelHistoryRequest request3(BucketName, "not_exist"); auto getOutcome2 = Client->GetLiveChannelHistory(request3); EXPECT_EQ(getOutcome2.isSuccess(), false); EXPECT_EQ(getOutcome2.result().LiveRecordList().size(), 0u); } TEST_F(GetLiveChannelHistoryTest, GetLiveChannelHistoryResultTest) { std::string xml = R"(<?xml version="1.0" encoding="UTF-8"?> <LiveChannelHistory> <LiveRecord> <StartTime>2016-07-30T01:53:21.000Z</StartTime> <EndTime>2016-07-30T01:53:31.000Z</EndTime> <RemoteAddr>10.101.194.148:56861</RemoteAddr> </LiveRecord> <LiveRecord> <StartTime>2016-07-30T01:53:35.000Z</StartTime> <EndTime>2016-07-30T01:53:45.000Z</EndTime> <RemoteAddr>10.101.194.148:57126</RemoteAddr> </LiveRecord> <LiveRecord> <StartTime>2016-07-30T01:53:49.000Z</StartTime> <EndTime>2016-07-30T01:53:59.000Z</EndTime> <RemoteAddr>10.101.194.148:57577</RemoteAddr> </LiveRecord> <LiveRecord> <StartTime>2016-07-30T01:54:04.000Z</StartTime> <EndTime>2016-07-30T01:54:14.000Z</EndTime> <RemoteAddr>10.101.194.148:57632</RemoteAddr> </LiveRecord> </LiveChannelHistory>)"; GetLiveChannelHistoryResult result(xml); std::vector<LiveRecord>vec = result.LiveRecordList(); EXPECT_EQ(vec.size(), 4u); EXPECT_EQ(vec[0].startTime, "2016-07-30T01:53:21.000Z"); EXPECT_EQ(vec[0].endTime, "2016-07-30T01:53:31.000Z"); EXPECT_EQ(vec[0].remoteAddr, "10.101.194.148:56861"); EXPECT_EQ(vec[1].startTime, "2016-07-30T01:53:35.000Z"); EXPECT_EQ(vec[1].endTime, "2016-07-30T01:53:45.000Z"); EXPECT_EQ(vec[1].remoteAddr, "10.101.194.148:57126"); EXPECT_EQ(vec[2].startTime, "2016-07-30T01:53:49.000Z"); EXPECT_EQ(vec[2].endTime, "2016-07-30T01:53:59.000Z"); EXPECT_EQ(vec[2].remoteAddr, "10.101.194.148:57577"); EXPECT_EQ(vec[3].startTime, "2016-07-30T01:54:04.000Z"); EXPECT_EQ(vec[3].endTime, "2016-07-30T01:54:14.000Z"); EXPECT_EQ(vec[3].remoteAddr, "10.101.194.148:57632"); xml = R"(<?xml version="1.0" encoding="UTF-8"?> <LiveChannelHistory> </LiveChannelHistory>)"; GetLiveChannelHistoryResult result2(xml); EXPECT_EQ(result2.LiveRecordList().empty(), true); } } }
35.287671
132
0.657997
FunriLy
1b144dce750ee005da5bd86ad0e48b0396e078a5
6,730
cpp
C++
src/lib/shell/commands/Ota.cpp
ArekBalysNordic/sdk-connectedhomeip
80da8ab1c0aa315a6ee2ce6adf448606372b0a2d
[ "Apache-2.0" ]
null
null
null
src/lib/shell/commands/Ota.cpp
ArekBalysNordic/sdk-connectedhomeip
80da8ab1c0aa315a6ee2ce6adf448606372b0a2d
[ "Apache-2.0" ]
null
null
null
src/lib/shell/commands/Ota.cpp
ArekBalysNordic/sdk-connectedhomeip
80da8ab1c0aa315a6ee2ce6adf448606372b0a2d
[ "Apache-2.0" ]
null
null
null
/* * * Copyright (c) 2021 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <app/clusters/ota-requestor/OTARequestorInterface.h> #include <lib/shell/Commands.h> #include <lib/shell/Engine.h> #include <lib/shell/commands/Help.h> #include <lib/support/logging/CHIPLogging.h> #include <platform/CHIPDeviceLayer.h> #include <platform/OTAImageProcessor.h> using namespace chip::DeviceLayer; namespace chip { namespace Shell { namespace { Shell::Engine sSubShell; CHIP_ERROR QueryImageHandler(int argc, char ** argv) { VerifyOrReturnError(GetRequestorInstance() != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(argc == 0, CHIP_ERROR_INVALID_ARGUMENT); PlatformMgr().ScheduleWork([](intptr_t) { GetRequestorInstance()->TriggerImmediateQuery(); }); return CHIP_NO_ERROR; } CHIP_ERROR ApplyImageHandler(int argc, char ** argv) { VerifyOrReturnError(GetRequestorInstance() != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(argc == 0, CHIP_ERROR_INVALID_ARGUMENT); PlatformMgr().ScheduleWork([](intptr_t) { GetRequestorInstance()->ApplyUpdate(); }); return CHIP_NO_ERROR; } CHIP_ERROR NotifyImageHandler(int argc, char ** argv) { VerifyOrReturnError(GetRequestorInstance() != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(argc == 0, CHIP_ERROR_INVALID_ARGUMENT); PlatformMgr().ScheduleWork([](intptr_t) { GetRequestorInstance()->NotifyUpdateApplied(); }); return CHIP_NO_ERROR; } static void HandleState(intptr_t context) { app::Clusters::OtaSoftwareUpdateRequestor::OTAUpdateStateEnum state; CHIP_ERROR err = GetRequestorInstance()->GetState(0, state); if (err == CHIP_NO_ERROR) { streamer_printf(streamer_get(), "Update state: "); switch (state) { case app::Clusters::OtaSoftwareUpdateRequestor::OTAUpdateStateEnum::kUnknown: streamer_printf(streamer_get(), "unknown"); break; case app::Clusters::OtaSoftwareUpdateRequestor::OTAUpdateStateEnum::kIdle: streamer_printf(streamer_get(), "idle"); break; case app::Clusters::OtaSoftwareUpdateRequestor::OTAUpdateStateEnum::kQuerying: streamer_printf(streamer_get(), "querying"); break; case app::Clusters::OtaSoftwareUpdateRequestor::OTAUpdateStateEnum::kDelayedOnQuery: streamer_printf(streamer_get(), "delayed on query"); break; case app::Clusters::OtaSoftwareUpdateRequestor::OTAUpdateStateEnum::kDownloading: streamer_printf(streamer_get(), "downloading"); break; case app::Clusters::OtaSoftwareUpdateRequestor::OTAUpdateStateEnum::kApplying: streamer_printf(streamer_get(), "applying"); break; case app::Clusters::OtaSoftwareUpdateRequestor::OTAUpdateStateEnum::kDelayedOnApply: streamer_printf(streamer_get(), "delayed on apply"); break; case app::Clusters::OtaSoftwareUpdateRequestor::OTAUpdateStateEnum::kRollingBack: streamer_printf(streamer_get(), "rolling back"); break; case app::Clusters::OtaSoftwareUpdateRequestor::OTAUpdateStateEnum::kDelayedOnUserConsent: streamer_printf(streamer_get(), "delayed on user consent"); break; default: streamer_printf(streamer_get(), "invalid"); break; } streamer_printf(streamer_get(), "\r\n"); } else { streamer_printf(streamer_get(), "Error: %" CHIP_ERROR_FORMAT "\r\n", err.Format()); } } static void HandleProgress(intptr_t context) { chip::app::DataModel::Nullable<uint8_t> progress; CHIP_ERROR err = GetRequestorInstance()->GetUpdateProgress(0, progress); if (err == CHIP_NO_ERROR) { if (progress.IsNull()) { streamer_printf(streamer_get(), "Update progress: NULL\r\n"); } else { streamer_printf(streamer_get(), "Update progress: %d %%\r\n", progress.Value()); } } else { streamer_printf(streamer_get(), "Error: %" CHIP_ERROR_FORMAT "\r\n", err.Format()); } } CHIP_ERROR StateHandler(int argc, char ** argv) { VerifyOrReturnError(GetRequestorInstance() != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(argc == 0, CHIP_ERROR_INVALID_ARGUMENT); PlatformMgr().ScheduleWork(HandleState, reinterpret_cast<intptr_t>(nullptr)); return CHIP_NO_ERROR; } CHIP_ERROR ProgressHandler(int argc, char ** argv) { VerifyOrReturnError(GetRequestorInstance() != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(argc == 0, CHIP_ERROR_INVALID_ARGUMENT); PlatformMgr().ScheduleWork(HandleProgress, reinterpret_cast<intptr_t>(nullptr)); return CHIP_NO_ERROR; } CHIP_ERROR OtaHandler(int argc, char ** argv) { if (argc == 0) { sSubShell.ForEachCommand(PrintCommandHelp, nullptr); return CHIP_NO_ERROR; } CHIP_ERROR error = sSubShell.ExecCommand(argc, argv); if (error != CHIP_NO_ERROR) { streamer_printf(streamer_get(), "Error: %" CHIP_ERROR_FORMAT "\r\n", error.Format()); } return error; } } // namespace void RegisterOtaCommands() { // Register subcommands of the `ota` commands. static const shell_command_t subCommands[] = { { &QueryImageHandler, "query", "Query for a new image. Usage: ota query" }, { &ApplyImageHandler, "apply", "Apply the current update. Usage: ota apply" }, { &NotifyImageHandler, "notify", "Notify the new image has been applied. Usage: ota notify <version>" }, { &StateHandler, "state", "Gets state of a current image update process. Usage: ota state" }, { &ProgressHandler, "progress", "Gets progress of a current image update process. Usage: ota progress" } }; sSubShell.RegisterCommands(subCommands, ArraySize(subCommands)); // Register the root `ota` command in the top-level shell. static const shell_command_t otaCommand = { &OtaHandler, "ota", "OTA commands" }; Engine::Root().RegisterCommands(&otaCommand, 1); } } // namespace Shell } // namespace chip
35.421053
112
0.687073
ArekBalysNordic
1b19ad32fa12f2b6d9d360fec202acba1130f74b
10,336
cpp
C++
src/config.cpp
brynedwards/ncpamixer
31eb4d0c689c25582216b38c2ed1461c39649599
[ "MIT" ]
311
2016-08-11T00:04:04.000Z
2022-03-21T20:01:38.000Z
src/config.cpp
hishamhm/ncpamixer
158dc0dc874cf4bae418b61d84c21daede258e79
[ "MIT" ]
51
2016-08-16T20:08:43.000Z
2022-01-29T16:17:06.000Z
src/config.cpp
hishamhm/ncpamixer
158dc0dc874cf4bae418b61d84c21daede258e79
[ "MIT" ]
29
2016-08-17T11:57:22.000Z
2021-12-28T06:27:26.000Z
#include "config.hpp" #include <pwd.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #define MAX_LINE 300 Config config; Config::Config() { memset(&filename[0], 0, sizeof(filename)); } const char *Config::getHomeDir() { const char *homedir = getenv("HOME"); if (homedir != nullptr) { return homedir; } passwd pwd = {nullptr}; passwd *result; char *buf; size_t bufsize; bufsize = sysconf(_SC_GETPW_R_SIZE_MAX); if (bufsize == static_cast<size_t>(-1)) { bufsize = 16384; } buf = new char[bufsize]; getpwuid_r(getuid(), &pwd, buf, bufsize, &result); if (result == nullptr) { fprintf(stderr, "Unable to find home-directory\n"); exit(EXIT_FAILURE); } delete [] buf; homedir = result->pw_dir; return homedir; } bool Config::fileExists(const char *name) { struct stat buffer = {0}; return (stat(name, &buffer) == 0); } void Config::init(const char *conf) { if (strlen(conf) != 0) { if (fileExists(conf)) { snprintf(&filename[0], sizeof(filename), "%s", conf); } else { fprintf(stderr, "Unable to find config file %s.\n", conf); exit(EXIT_FAILURE); } } if (strlen(&filename[0]) == 0) { const char *confdir = getenv("XDG_CONFIG_HOME"); char file[255] = {"/ncpamixer.conf"}; if (confdir == nullptr) { snprintf(&file[0], sizeof(file), "/.ncpamixer.conf"); confdir = getHomeDir(); } snprintf(&filename[0], sizeof(filename), "%s%s", confdir, &file[0]); } for (;;) { if (!readConfig()) { fprintf( stderr, "Unable to find config file %s, creating default config.\n", &filename[0] ); createDefault(); } else { break; } } } int Config::readConfig() { FILE *f = fopen(&filename[0], "rb"); if (f != nullptr) { while (feof(f) == 0) { char line[MAX_LINE] = {0}; bool instring = false; std::string key; std::string val; std::string *current = &key; if (fgets(&line[0], MAX_LINE, f) == nullptr) { break; } char *tmp = &line[0]; while (*tmp != '\0' && *tmp != '\n' && *tmp != '\r') { if (*tmp == '=') { current = &val; } else if (*tmp == '#') { break; } else if (*tmp == '"') { instring = !instring; } else if (*tmp != ' ' || instring) { current->append(tmp, 1); } tmp++; } if (key.length() > 0) { config[key] = val; } } fclose(f); return 1; } return 0; } std::string Config::getString(const char *key, const std::string &def) { auto conf = config.find(key); if (conf == config.end()) { config[key] = def; } return config[key]; } int Config::getInt(const char *key, int def) { int ret = atoi(getString(key, std::to_string(def)).c_str()); return ret; } bool Config::getBool(const char *key, bool def) { std::string ret = getString(key, (def) ? "true" : "false"); return (ret == "1" || ret == "yes" || ret == "true"); } bool Config::keyExists(const char *key) { auto conf = config.find(key); return !(conf == config.end()); } bool Config::keyEmpty(const char *key) { if (keyExists(key)) { return (config[key].empty()); } return true; } void Config::createDefault() { // light ░ \u2593 // medium ▒ \u2592 // dark shade ▓ \u2593 // block █ \u2588 // lower ▁ \u2581 // higher ▔ \u2594 // triangle ▲ \u25b2 // https://en.wikipedia.org/wiki/Block_Elements FILE *f = fopen(&filename[0], "w"); if (f != nullptr) { fprintf( f, "\"theme\" = \"default\"\n" "\n" "# Default theme {\n" " \"theme.default.static_bar\" = false\n" " \"theme.default.default_indicator\" = \"♦ \"\n" " \"theme.default.bar_style.bg\" = \"░\"\n" " \"theme.default.bar_style.fg\" = \"█\"\n" " \"theme.default.bar_style.indicator\" = \"█\"\n" " \"theme.default.bar_style.top\" = \"▁\"\n" " \"theme.default.bar_style.bottom\" = \"▔\"\n" " \"theme.default.bar_low.front\" = 2\n" " \"theme.default.bar_low.back\" = 0\n" " \"theme.default.bar_mid.front\" = 3\n" " \"theme.default.bar_mid.back\" = 0\n" " \"theme.default.bar_high.front\" = 1\n" " \"theme.default.bar_high.back\" = 0\n" " \"theme.default.volume_low\" = 2\n" " \"theme.default.volume_mid\" = 3\n" " \"theme.default.volume_high\" = 1\n" " \"theme.default.volume_peak\" = 1\n" " \"theme.default.volume_indicator\" = -1\n" " \"theme.default.selected\" = 2\n" " \"theme.default.default\" = -1\n" " \"theme.default.border\" = -1\n" " \"theme.default.dropdown.selected_text\" = 0\n" " \"theme.default.dropdown.selected\" = 2\n" " \"theme.default.dropdown.unselected\" = -1\n" "# }\n" "# c0r73x theme {\n" " \"theme.c0r73x.static_bar\" = false\n" " \"theme.c0r73x.default_indicator\" = \"■ \"\n" " \"theme.c0r73x.bar_style.bg\" = \"■\"\n" " \"theme.c0r73x.bar_style.fg\" = \"■\"\n" " \"theme.c0r73x.bar_style.indicator\" = \"■\"\n" " \"theme.c0r73x.bar_style.top\" = \"\" \n" " \"theme.c0r73x.bar_style.bottom\" = \"\" \n" " \"theme.c0r73x.bar_low.front\" = 0\n" " \"theme.c0r73x.bar_low.back\" = -1\n" " \"theme.c0r73x.bar_mid.front\" = 0\n" " \"theme.c0r73x.bar_mid.back\" = -1\n" " \"theme.c0r73x.bar_high.front\" = 0\n" " \"theme.c0r73x.bar_high.back\" = -1\n" " \"theme.c0r73x.volume_low\" = 6\n" " \"theme.c0r73x.volume_mid\" = 6\n" " \"theme.c0r73x.volume_high\" = 6\n" " \"theme.c0r73x.volume_peak\" = 1\n" " \"theme.c0r73x.volume_indicator\" = 15\n" " \"theme.c0r73x.selected\" = 6\n" " \"theme.c0r73x.default\" = -1\n" " \"theme.c0r73x.border\" = -1\n" " \"theme.c0r73x.dropdown.selected_text\" = 0\n" " \"theme.c0r73x.dropdown.selected\" = 6\n" " \"theme.c0r73x.dropdown.unselected\" = -1\n" "# }\n" "# Keybinds {\n" " \"keycode.9\" = \"switch\" # tab\n" " \"keycode.13\" = \"select\" # enter\n" " \"keycode.27\" = \"quit\" # escape\n" " \"keycode.99\" = \"dropdown\" # c\n" " \"keycode.113\" = \"quit\" # q\n" " \"keycode.109\" = \"mute\" # m\n" " \"keycode.100\" = \"set_default\" # d\n" " \"keycode.108\" = \"volume_up\" # l\n" " \"keycode.104\" = \"volume_down\" # h\n" " \"keycode.261\" = \"volume_up\" # arrow right\n" " \"keycode.260\" = \"volume_down\" # arrow left\n" " \"keycode.107\" = \"move_up\" # k\n" " \"keycode.106\" = \"move_down\" # j\n" " \"keycode.259\" = \"move_up\" # arrow up\n" " \"keycode.258\" = \"move_down\" # arrow down\n" " \"keycode.338\" = \"page_up\" # page up\n" " \"keycode.339\" = \"page_down\" # page down\n" " \"keycode.76\" = \"tab_next\" # L\n" " \"keycode.72\" = \"tab_prev\" # H\n" " \"keycode.265\" = \"tab_playback\" # f1\n" " \"keycode.266\" = \"tab_recording\" # f2\n" " \"keycode.267\" = \"tab_output\" # f3\n" " \"keycode.268\" = \"tab_input\" # f4\n" " \"keycode.269\" = \"tab_config\" # f5\n" " \"keycode.f.80\" = \"tab_playback\" # f1 VT100\n" " \"keycode.f.81\" = \"tab_recording\" # f2 VT100\n" " \"keycode.f.82\" = \"tab_output\" # f3 VT100\n" " \"keycode.f.83\" = \"tab_input\" # f4 VT100\n" " \"keycode.f.84\" = \"tab_config\" # f5 VT100\n" " \"keycode.71\" = \"move_last\" # G\n" " \"keycode.103\" = \"move_first\" # g\n" "# \"keycode.48\" = \"set_volume_100\" # 0\n" " \"keycode.48\" = \"set_volume_0\" # 0\n" " \"keycode.49\" = \"set_volume_10\" # 1\n" " \"keycode.50\" = \"set_volume_20\" # 2\n" " \"keycode.51\" = \"set_volume_30\" # 3\n" " \"keycode.52\" = \"set_volume_40\" # 4\n" " \"keycode.53\" = \"set_volume_50\" # 5\n" " \"keycode.54\" = \"set_volume_60\" # 6\n" " \"keycode.55\" = \"set_volume_70\" # 7\n" " \"keycode.56\" = \"set_volume_80\" # 8\n" " \"keycode.57\" = \"set_volume_90\" # 9\n" "# }" ); fclose(f); } else { fprintf(stderr, "Unable to create default config!\n"); exit(EXIT_FAILURE); } }
34.112211
76
0.424439
brynedwards
1b1bd39c1d74c64d4876751d4cbc0d3aadfda6bd
2,758
cpp
C++
examples/portability/opencl/main.cpp
lcw/OCCA2
1b81616e2865c89dad05f24a522b20018e8604fa
[ "MIT" ]
null
null
null
examples/portability/opencl/main.cpp
lcw/OCCA2
1b81616e2865c89dad05f24a522b20018e8604fa
[ "MIT" ]
null
null
null
examples/portability/opencl/main.cpp
lcw/OCCA2
1b81616e2865c89dad05f24a522b20018e8604fa
[ "MIT" ]
null
null
null
#include <iostream> #include "occa.hpp" int main(int argc, char **argv){ int entries = 5; //---[ Init OpenCL ]------------------ cl_int error; cl_platform_id clPlatformID = occa::cl::platformID(0); cl_device_id clDeviceID = occa::cl::deviceID(0,0); cl_context clContext = clCreateContext(NULL, 1, &clDeviceID, NULL, NULL, &error); OCCA_CL_CHECK("Device: Creating Context", error); cl_command_queue clStream = clCreateCommandQueue(clContext, clDeviceID, CL_QUEUE_PROFILING_ENABLE, &error); OCCA_CL_CHECK("Device: createStream", error); cl_mem cl_a = clCreateBuffer(clContext, CL_MEM_READ_WRITE, entries*sizeof(float), NULL, &error); cl_mem cl_b = clCreateBuffer(clContext, CL_MEM_READ_WRITE, entries*sizeof(float), NULL, &error); cl_mem cl_ab = clCreateBuffer(clContext, CL_MEM_READ_WRITE, entries*sizeof(float), NULL, &error); //==================================== float *a = new float[entries]; float *b = new float[entries]; float *ab = new float[entries]; occa::device device = occa::cl::wrapDevice(clPlatformID, clDeviceID, clContext); occa::stream stream = device.wrapStream(&clStream); device.setStream(stream); occa::kernel addVectors; occa::memory o_a, o_b, o_ab; for(int i = 0; i < entries; ++i){ a[i] = i; b[i] = 1 - i; ab[i] = 0; } o_a = device.wrapMemory(&cl_a , entries*sizeof(float)); o_b = device.wrapMemory(&cl_b , entries*sizeof(float)); o_ab = device.wrapMemory(&cl_ab, entries*sizeof(float)); addVectors = device.buildKernelFromSource("addVectors.occa", "addVectors"); int dims = 1; int itemsPerGroup(2); int groups((entries + itemsPerGroup - 1)/itemsPerGroup); addVectors.setWorkingDims(dims, itemsPerGroup, groups); o_a.copyFrom(a); o_b.copyFrom(b); occa::initTimer(device); occa::tic("addVectors"); addVectors(entries, o_a, o_b, o_ab); double elapsedTime = occa::toc("addVectors", addVectors); o_ab.copyTo(ab); std::cout << "Elapsed time = " << elapsedTime << " s" << std::endl; occa::printTimer(); for(int i = 0; i < 5; ++i) std::cout << i << ": " << ab[i] << '\n'; addVectors.free(); o_a.free(); o_b.free(); o_ab.free(); delete [] a; delete [] b; delete [] ab; return 0; }
27.306931
86
0.531182
lcw
1b1eb00ce653b11e0d0842a5972cf39c1a6625d8
4,052
hpp
C++
src/3rd party/boost/boost/spirit/tree/tree_iterator.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/3rd party/boost/boost/spirit/tree/tree_iterator.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
null
null
null
src/3rd party/boost/boost/spirit/tree/tree_iterator.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
/*============================================================================= Spirit v1.6.0 Copyright (c) 2001-2003 Daniel Nuffer Copyright (c) 2001-2003 Hartmut Kaiser http://spirit.sourceforge.net/ Permission to copy, use, modify, sell and distribute this software is granted provided this copyright notice appears in all copies. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. =============================================================================*/ #ifndef BOOST_SPIRIT_TREE_TREE_ITERATOR_HPP #define BOOST_SPIRIT_TREE_TREE_ITERATOR_HPP #if defined(BOOST_MSVC) && (BOOST_MSVC <= 1300) #define BOOST_SPIRIT_IT_NS impl #else #define BOOST_SPIRIT_IT_NS std #endif #if (defined(BOOST_INTEL_CXX_VERSION) && !defined(_STLPORT_VERSION)) #undef BOOST_SPIRIT_IT_NS #define BOOST_SPIRIT_IT_NS impl #endif /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace spirit { /////////////////////////////////////////////////////////////////////////////// // // A parse_tree_iterator allows to parse a previously generated parse tree as // if it would be a normal input stream. // It traverses the parsetree to return only the tokens from the leaf nodes. // /////////////////////////////////////////////////////////////////////////////// template <typename ParseTreeMatchT> class parse_tree_iterator { public: typedef ParseTreeMatchT tree_match_t; typedef typename tree_match_t::container_t tree_t; typedef typename tree_match_t::parse_node_t parse_node_t; typedef typename tree_match_t::tree_iterator tree_iterator_t; typedef typename tree_match_t::const_tree_iterator const_tree_iterator_t; typedef typename parse_node_t::const_iterator_t const_iterator_t; typedef BOOST_SPIRIT_IT_NS::iterator_traits<const_iterator_t> iterator_traits; typedef typename iterator_traits::value_type value_type; typedef typename iterator_traits::pointer pointer; typedef typename iterator_traits::reference reference; typedef typename iterator_traits::difference_type difference_type; typedef std::forward_iterator_tag iterator_category; private: /////////////////////////////////////////////////////////////////////////////// // // The class node_stack contains the way back up the hierarchy from the // current parse node to the root parse node (needed, because the parsetree // itself doesn't contain uplinks). // This stack contains (node *, iterator) pairs. // /////////////////////////////////////////////////////////////////////////////// class node_stack : public std::stack<std::pair<tree_t const *, const_tree_iterator_t> > { typedef std::stack<std::pair<tree_t const *, const_tree_iterator_t> > base_t; public: void push (tree_t const &target, const_tree_iterator_t iter); void adjust_forward(); void go_up(); // goes up, 'till the next parse_node is found void go_down(); // goes down, 'till a leaf node is found // returns a reference to the current iterator of the current parse_node const_tree_iterator_t &act_iter(); // returns the current and end iterators of the current parse node const_tree_iterator_t act_const_iter() const; const_tree_iterator_t node_end() const; }; public: parse_tree_iterator(); parse_tree_iterator(tree_t const &target_, const_tree_iterator_t iter_); reference operator*() const; pointer operator->() const; parse_tree_iterator& operator++(); parse_tree_iterator operator++(int); bool operator==(tree_iterator_t const &rhs) const; bool operator!=(tree_iterator_t const &rhs) const; bool operator==(parse_tree_iterator const &rhs) const; bool operator!=(parse_tree_iterator const &rhs) const; private: node_stack nodes; }; }} // namespace boost::spirit #undef BOOST_SPIRIT_IT_NS #endif // BOOST_SPIRIT_TREE_TREE_ITERATOR_HPP
36.836364
85
0.644126
OLR-xray
1b1fa7d88e7cc4c80e965a8f1bc58b31038ee1f6
2,508
hpp
C++
modules/core/restructuring/include/nt2/core/functions/resize.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/core/restructuring/include/nt2/core/functions/resize.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/core/restructuring/include/nt2/core/functions/resize.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
//============================================================================== // Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_CORE_FUNCTIONS_RESIZE_HPP_INCLUDED #define NT2_CORE_FUNCTIONS_RESIZE_HPP_INCLUDED /*! * \file * \brief Defines and implements the nt2::resize function */ #include <nt2/include/functor.hpp> #include <nt2/sdk/meta/value_as.hpp> #include <nt2/sdk/meta/boxed_size.hpp> #include <nt2/core/container/dsl/size.hpp> #include <nt2/core/container/dsl/value_type.hpp> namespace nt2 { namespace tag { struct resize_ : ext::elementwise_<resize_> { /// @brief Parent hierarchy typedef ext::elementwise_<resize_> parent; template<class... Args> static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args) BOOST_AUTO_DECLTYPE_BODY( dispatching_resize_( ext::adl_helper(), static_cast<Args&&>(args)... ) ) }; } namespace ext { template<class Site, class... Ts> BOOST_FORCEINLINE generic_dispatcher<tag::resize_, Site> dispatching_resize_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...) { return generic_dispatcher<tag::resize_, Site>(); } template<class... Args> struct impl_resize_; } //============================================================================ /*! * resize an expression * * \param xpr Expression to resize * \param size New size of the expression */ //============================================================================ #define M0(z,n,t) \ NT2_FUNCTION_IMPLEMENTATION(nt2::tag::resize_, resize, n) \ /**/ BOOST_PP_REPEAT_FROM_TO(2,BOOST_PP_INC(BOOST_PP_INC(NT2_MAX_DIMENSIONS)),M0,~) #undef M0 } namespace nt2 { namespace ext { /// INTERNAL ONLY template<class Domain, class Expr, int N> struct value_type<nt2::tag::resize_,Domain,N,Expr> : meta::value_as<Expr,0> {}; /// INTERNAL ONLY template<class Domain, class Expr,int N> struct size_of<nt2::tag::resize_,Domain,N,Expr> : meta::boxed_size<Expr,1> {}; } } #endif
31.35
171
0.57815
psiha
1b2465175cc31b440fa49957e08c50ab243a6bee
1,101
cpp
C++
tests/UnitTests/Learning/Evolution/PositiveMakerFitnessFunctionTest.cpp
domin1101/ANNHelper
50acb5746d6dad6777532e4c7da4983a7683efe0
[ "Zlib" ]
5
2016-02-04T06:14:42.000Z
2017-02-06T02:21:43.000Z
tests/UnitTests/Learning/Evolution/PositiveMakerFitnessFunctionTest.cpp
domin1101/ANNHelper
50acb5746d6dad6777532e4c7da4983a7683efe0
[ "Zlib" ]
41
2015-04-15T21:05:45.000Z
2015-07-09T12:59:02.000Z
tests/UnitTests/Learning/Evolution/PositiveMakerFitnessFunctionTest.cpp
domin1101/LightBulb
50acb5746d6dad6777532e4c7da4983a7683efe0
[ "Zlib" ]
null
null
null
#include "LightBulb/Function/ActivationFunction/FermiFunction.hpp" #include <Mocks/MockMutationSelector.hpp> #include <Mocks/MockIndividual.hpp> #include <LightBulb/Learning/Evolution/PositiveMakerFitnessFunction.hpp> using namespace LightBulb; class PositiveMakerFitnessFunctionTest : public testing::Test { public: PositiveMakerFitnessFunction* positiveMakerFitnessFunction; void SetUp() { } virtual ~PositiveMakerFitnessFunctionTest() { delete positiveMakerFitnessFunction; } }; TEST_F(PositiveMakerFitnessFunctionTest, execute) { positiveMakerFitnessFunction = new PositiveMakerFitnessFunction(10); std::vector<std::pair<double, AbstractIndividual*>> highscore; highscore.push_back(std::make_pair(4, static_cast<AbstractIndividual*>(nullptr))); highscore.push_back(std::make_pair(-3, static_cast<AbstractIndividual*>(nullptr))); highscore.push_back(std::make_pair(-13, static_cast<AbstractIndividual*>(nullptr))); positiveMakerFitnessFunction->execute(highscore); EXPECT_EQ(14, highscore[0].first); EXPECT_EQ(7, highscore[1].first); EXPECT_EQ(0, highscore[2].first); }
29.756757
85
0.802906
domin1101
1b24bc1d80105cd66d3600866910e2e56b2a4ad7
1,167
cpp
C++
src/FalconEngine/Context/Platform/GLFW/GLFWGameEngineInput.cpp
LiuYiZhou95/FalconEngine
b798f20e9dbd01334a4e4cdbbd9a5bec74966418
[ "MIT" ]
null
null
null
src/FalconEngine/Context/Platform/GLFW/GLFWGameEngineInput.cpp
LiuYiZhou95/FalconEngine
b798f20e9dbd01334a4e4cdbbd9a5bec74966418
[ "MIT" ]
null
null
null
src/FalconEngine/Context/Platform/GLFW/GLFWGameEngineInput.cpp
LiuYiZhou95/FalconEngine
b798f20e9dbd01334a4e4cdbbd9a5bec74966418
[ "MIT" ]
1
2021-08-25T07:39:02.000Z
2021-08-25T07:39:02.000Z
#include <FalconEngine/Context/GameEngineInput.h> #include <FalconEngine/Input/MouseButton.h> #include <FalconEngine/Input/MouseState.h> #include <FalconEngine/Input/KeyboardState.h> #include <FalconEngine/Input/KeyState.h> #if defined(FALCON_ENGINE_WINDOW_GLFW) #include <FalconEngine/Context/Platform/GLFW/GLFWGameEngineData.h> #include <FalconEngine/Context/Platform/GLFW/GLFWGameEngineInputDispatcher.h> namespace FalconEngine { void GameEngineInputDispatcherDeleter::operator()(GameEngineInputDispatcher *inputDispatcher) { delete inputDispatcher; } /************************************************************************/ /* Private Members */ /************************************************************************/ void GameEngineInput::InitializePlatform() { mDispatcher = std::unique_ptr<GameEngineInputDispatcher, GameEngineInputDispatcherDeleter>( new GameEngineInputDispatcher(this), GameEngineInputDispatcherDeleter()); } void GameEngineInput::DestroyPlatform() { } void GameEngineInput::PollEvent() { glfwPollEvents(); } } #endif
25.369565
95
0.639246
LiuYiZhou95
1b25342e91994d7cbce4c3419ff1ff132d22c3ed
5,455
cpp
C++
Modules/ContourModel/IO/mitkContourModelReader.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Modules/ContourModel/IO/mitkContourModelReader.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Modules/ContourModel/IO/mitkContourModelReader.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkContourModelReader.h" #include <fstream> #include <iostream> #include <regex> #include <mitkCustomMimeType.h> #include <mitkLocaleSwitch.h> #include <tinyxml2.h> namespace { // Previous versions of the ContourModelSetWriter produced flawed // XML files with multiple XML declarations. std::string RemoveErroneousXMLDeclarations(const std::string& filename) { std::ifstream file(filename); file.seekg(0, std::ios_base::end); auto size = file.tellg(); std::string string(size, '\0'); file.seekg(0); file.read(&string[0], size); file.close(); std::regex regex("><\\?xml.+\\?>"); return std::regex_replace(string, regex, ">"); } } mitk::ContourModelReader::ContourModelReader(const mitk::ContourModelReader &other) : mitk::AbstractFileReader(other) { } mitk::ContourModelReader::ContourModelReader() : AbstractFileReader() { std::string category = "Contour File"; mitk::CustomMimeType customMimeType; customMimeType.SetCategory(category); customMimeType.AddExtension("cnt"); this->SetDescription(category); this->SetMimeType(customMimeType); m_ServiceReg = this->RegisterService(); } mitk::ContourModelReader::~ContourModelReader() { } std::vector<itk::SmartPointer<mitk::BaseData>> mitk::ContourModelReader::DoRead() { std::vector<itk::SmartPointer<mitk::BaseData>> result; std::string location = GetInputLocation(); // Switch the current locale to "C" LocaleSwitch localeSwitch("C"); try { auto string = RemoveErroneousXMLDeclarations(location); tinyxml2::XMLDocument doc; if (tinyxml2::XML_SUCCESS == doc.Parse(string.c_str())) { tinyxml2::XMLHandle docHandle(&doc); /*++++ handle n contourModels within data tags ++++*/ for (auto *currentContourElement = docHandle.FirstChildElement("contourModel").ToElement(); currentContourElement != nullptr; currentContourElement = currentContourElement->NextSiblingElement()) { mitk::ContourModel::Pointer newContourModel = mitk::ContourModel::New(); if (currentContourElement->FirstChildElement("data")->FirstChildElement("timestep") != nullptr) { /*++++ handle n timesteps within timestep tags ++++*/ for (auto *currentTimeSeries = currentContourElement->FirstChildElement("data")->FirstChildElement("timestep")->ToElement(); currentTimeSeries != nullptr; currentTimeSeries = currentTimeSeries->NextSiblingElement()) { unsigned int currentTimeStep(0); currentTimeStep = atoi(currentTimeSeries->Attribute("n")); this->ReadPoints(newContourModel, currentTimeSeries, currentTimeStep); int isClosed; currentTimeSeries->QueryIntAttribute("isClosed", &isClosed); if (isClosed) { newContourModel->Close(currentTimeStep); } } /*++++ END handle n timesteps within timestep tags ++++*/ } else { // this should not happen MITK_WARN << "wrong file format!"; // newContourModel = this->ReadPoint(newContourModel, currentContourElement, 0); } newContourModel->UpdateOutputInformation(); result.push_back(dynamic_cast<mitk::BaseData *>(newContourModel.GetPointer())); } /*++++ END handle n contourModels within data tags ++++*/ } else { MITK_WARN << "XML parser error!"; } } catch (...) { MITK_ERROR << "Cannot read contourModel."; } return result; } mitk::ContourModelReader *mitk::ContourModelReader::Clone() const { return new ContourModelReader(*this); } void mitk::ContourModelReader::ReadPoints(mitk::ContourModel::Pointer newContourModel, const tinyxml2::XMLElement *currentTimeSeries, unsigned int currentTimeStep) { // check if the timesteps in contourModel have to be expanded if (currentTimeStep != newContourModel->GetTimeSteps()) { newContourModel->Expand(currentTimeStep + 1); } // read all points within controlPoints tag if (currentTimeSeries->FirstChildElement("controlPoints")->FirstChildElement("point") != nullptr) { for (auto *currentPoint = currentTimeSeries->FirstChildElement("controlPoints")->FirstChildElement("point")->ToElement(); currentPoint != nullptr; currentPoint = currentPoint->NextSiblingElement()) { double x(0.0); double y(0.0); double z(0.0); x = atof(currentPoint->FirstChildElement("x")->GetText()); y = atof(currentPoint->FirstChildElement("y")->GetText()); z = atof(currentPoint->FirstChildElement("z")->GetText()); int isActivePoint; currentPoint->QueryIntAttribute("isActive", &isActivePoint); mitk::Point3D point; mitk::FillVector3D(point, x, y, z); newContourModel->AddVertex(point, isActivePoint, currentTimeStep); } } else { // nothing to read } }
31.350575
117
0.638497
zhaomengxiao
1b26a5d33f7ab3bf714f50b07b7aa9d72cc31e84
5,621
hpp
C++
source/backend/opengl/GLBackend.hpp
z415073783/MNN
62c5ca47964407508a5fa802582e648fc75eb0d9
[ "Apache-2.0" ]
null
null
null
source/backend/opengl/GLBackend.hpp
z415073783/MNN
62c5ca47964407508a5fa802582e648fc75eb0d9
[ "Apache-2.0" ]
1
2021-09-07T09:13:03.000Z
2021-09-07T09:13:03.000Z
source/backend/opengl/GLBackend.hpp
z415073783/MNN
62c5ca47964407508a5fa802582e648fc75eb0d9
[ "Apache-2.0" ]
1
2020-03-10T02:17:47.000Z
2020-03-10T02:17:47.000Z
// // GLBackend.h // MNN // // Created by MNN on 2019/01/31. // Copyright © 2018, Alibaba Group Holding Limited // #ifndef GLBACKEND_H #define GLBACKEND_H #include <list> #include <map> #include <memory> #include "Backend.hpp" #include "GLContext.hpp" #include "GLProgram.hpp" #include "GLSSBOBuffer.hpp" #include "GLTexture.hpp" #include "MNN_generated.h" #include "GLUtils.hpp" #include "TensorUtils.hpp" #include "GLHead.hpp" namespace MNN { namespace OpenGL { class GLBackend : public Backend { public: GLBackend(BackendConfig::PrecisionMode precision, BackendConfig::PowerMode power); virtual ~GLBackend(); void upload(GLuint textureId, const float* inputData, int d1, int d2, int d3, bool align = false) const; void download(GLuint textureId, float* outputData, int d1, int d2, int d3, bool align = false) const; void copyImageToNhwcBuffer(GLuint textureId, float *outputData, int width, int height, int channel) const; void copyNhwcBufferToImage(GLuint textureId, const float *inputData, int width, int height, int channel) const; std::shared_ptr<GLProgram> getProgram(const std::string& key, const char* content); std::shared_ptr<GLProgram> getProgram(const std::string& key, const char* content, const std::vector<std::string>& prefix); enum GPUType { ADRENO = 0, MALI = 1, OTHER = 2 }; inline GPUType gpuType() const { return mGpuType; } inline int glVersion() const { return mVersion; } void wait() const; void compute(int dim1, int dim2, int dim3, bool needWait = false) const; /*For Buffer alloc and release*/ virtual bool onAcquireBuffer(const Tensor* nativeTensor, StorageType storageType) override; // If STATIC, delete the buffer. If dynamic don't free the buffer, just set it to reused virtual bool onReleaseBuffer(const Tensor* nativeTensor, StorageType storageType) override; // Clear All Dynamic Buffer virtual bool onClearBuffer() override; virtual void onCopyBuffer(const Tensor* srcTensor, const Tensor* dstTensor) const override; virtual void onExecuteBegin() const override; virtual void onExecuteEnd() const override; /// get execution virtual Execution* onCreate(const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, const MNN::Op* op) override; class Creator { public: virtual ~Creator() = default; virtual Execution *onCreate(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &output, const MNN::Op *op, Backend *backend) const = 0; }; static bool addCreator(OpType t, Creator *c); bool isCreateError() const; bool isSupportHalf() const; bool getOpenGLExtensions(std::string extStr); GLenum getTextrueFormat() const; std::string getImageFormat() const; std::shared_ptr<GLProgram> getTreatedProgramWithPrefix(const char *content, const std::vector<std::string> &prefix); std::shared_ptr<GLProgram> getTreatedProgram(const char *content); private: struct Runtime { std::shared_ptr<GLProgram> mNchw2ImageProgram; std::shared_ptr<GLProgram> mImage2NchwProgram; std::shared_ptr<GLProgram> mNc4hw42ImageProgram; std::shared_ptr<GLProgram> mImage2Nc4hw4Program; std::shared_ptr<GLProgram> mNhwc2ImageProgram; std::shared_ptr<GLProgram> mImage2NhwcProgram; std::map<std::string, std::shared_ptr<GLProgram>> mProgramCache; std::list<std::shared_ptr<GLTexture>> mBlocks; std::list<std::pair<const Tensor*, GLuint>> mFreeTextures; mutable std::shared_ptr<GLSSBOBuffer> mTempBuffer; }; Runtime* mRuntime = nullptr; static std::unique_ptr<GLContext> mContext; GPUType mGpuType = OTHER; int mVersion = 0; int mLocalSize[3]; bool mIsCreateError{false}; bool mIsSupportHalf{false}; GLenum mTextrueFormat{GL_RGBA32F}; std::string mImageFormat{"rgba32f"}; }; inline std::vector<int> tensorShapeFormat(const Tensor *input) { int iN = std::max(1, input->batch()); int iC = std::max(1, input->channel()); int iH = std::max(1, input->height()); int iW = std::max(1, input->width()); if (input->dimensions() == 3) { iN = 1; iH = input->buffer().dim[0].extent; iW = input->buffer().dim[1].extent; iC = input->buffer().dim[2].extent; } if (input->dimensions() == 2) { iN = input->buffer().dim[0].extent; iH = 1; iW = 1; iC = input->buffer().dim[1].extent; } if (input->dimensions() == 1) { iN = 1; iH = 1; iW = 1; iC = input->buffer().dim[0].extent; } #ifdef LOG_VERBOSE MNN_PRINT("dim %d : [%d, %d, %d, %d] \n",input->dimensions(), iN, iH, iW, iC); #endif std::vector<int> shape_vec{iN, iH, iW, iC}; return shape_vec; } template <class T> class GLCreatorRegister { public: GLCreatorRegister(OpType type) { GLBackend::addCreator(type, new T); } ~GLCreatorRegister() = default; }; template <typename T> class TypedCreator : public GLBackend::Creator { public: virtual ~TypedCreator() = default; virtual Execution *onCreate(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs, const MNN::Op *op, Backend *backend) const override { return new T(inputs, op, backend); } }; } // namespace OpenGL } // namespace MNN #endif
32.680233
157
0.646682
z415073783
1b2946652bc9ff5f3eba1cefb4db9394d6107c99
13,879
cpp
C++
audio/dsp/sinc_resampler.cpp
VulkanWorks/Granite-scene-graph-gui-ffmpeg-dsp
a725ec78eeb5de2d3c25257b1a9372f5e38910f6
[ "MIT" ]
1,003
2017-08-13T17:47:04.000Z
2022-03-29T15:56:55.000Z
audio/dsp/sinc_resampler.cpp
VulkanWorks/Granite-scene-graph-gui-ffmpeg-dsp
a725ec78eeb5de2d3c25257b1a9372f5e38910f6
[ "MIT" ]
10
2017-08-14T19:11:35.000Z
2021-12-10T12:51:53.000Z
audio/dsp/sinc_resampler.cpp
VulkanWorks/Granite-scene-graph-gui-ffmpeg-dsp
a725ec78eeb5de2d3c25257b1a9372f5e38910f6
[ "MIT" ]
107
2017-08-16T16:13:26.000Z
2022-03-03T06:42:19.000Z
/* Copyright (c) 2017-2020 Hans-Kristian Arntzen * * 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. */ // Rewrote the RetroArch Sinc resampler for my purpose here. /* Copyright (C) 2010-2019 The RetroArch team * * --------------------------------------------------------------------------------------- * The following license statement only applies to this file (sinc_resampler.c). * --------------------------------------------------------------------------------------- * * 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. */ /* Copyright (C) 2010-2019 The RetroArch team * * --------------------------------------------------------------------------------------- * The following license statement only applies to this file (filters.h). * --------------------------------------------------------------------------------------- * * 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. */ /* Copyright (C) 2010-2019 The RetroArch team * * --------------------------------------------------------------------------------------- * The following license statement only applies to this file (memalign.c). * --------------------------------------------------------------------------------------- * * 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 "simd_headers.hpp" #include "sinc_resampler.hpp" #include "aligned_alloc.hpp" #include "dsp.hpp" #include <math.h> #include <stdlib.h> #include <string.h> #ifndef PI #define PI 3.14159265359 #endif namespace Granite { namespace Audio { namespace DSP { void SincResampler::init_table_kaiser(double cutoff, unsigned phase_count, unsigned num_taps, double beta) { double window_mod = DSP::kaiser_window_function(0.0, beta); const unsigned stride = 2; double sidelobes = num_taps / 2.0; for (unsigned i = 0; i < phase_count; i++) { for (unsigned j = 0; j < num_taps; j++) { unsigned n = j * phase_count + i; double window_phase = double(n) / double(phase_count * num_taps); /* [0, 1). */ window_phase = 2.0 * window_phase - 1.0; /* [-1, 1) */ double sinc_phase = sidelobes * window_phase; float val = float(cutoff * DSP::sinc(PI * sinc_phase * cutoff) * DSP::kaiser_window_function(window_phase, beta) / window_mod); phase_table[i * stride * num_taps + j] = val; } } for (unsigned p = 0; p < phase_count - 1; p++) { for (unsigned j = 0; j < num_taps; j++) { float delta = phase_table[(p + 1) * stride * num_taps + j] - phase_table[p * stride * num_taps + j]; phase_table[(p * stride + 1) * num_taps + j] = delta; } } unsigned phase = phase_count - 1; for (unsigned j = 0; j < num_taps; j++) { unsigned n = j * phase_count + (phase + 1); double window_phase = double(n) / double(phase_count * num_taps); /* (0, 1]. */ window_phase = 2.0 * window_phase - 1.0; /* (-1, 1] */ double sinc_phase = sidelobes * window_phase; float val = float(cutoff * DSP::sinc(PI * sinc_phase * cutoff) * kaiser_window_function(window_phase, beta) / window_mod); float delta = (val - phase_table[phase * stride * num_taps + j]); phase_table[(phase * stride + 1) * num_taps + j] = delta; } } SincResampler::SincResampler(float out_rate, float in_rate, Quality quality) { double cutoff; unsigned sidelobes; double kaiser_beta; switch (quality) { case Quality::Low: cutoff = 0.80; sidelobes = 4; kaiser_beta = 4.5; phase_bits = 12; subphase_bits = 10; break; case Quality::Medium: cutoff = 0.825; sidelobes = 8; kaiser_beta = 5.5; phase_bits = 8; subphase_bits = 16; break; case Quality::High: cutoff = 0.90; sidelobes = 32; kaiser_beta = 10.5; phase_bits = 10; subphase_bits = 14; break; default: std::abort(); } subphase_mask = (1u << subphase_bits) - 1u; subphase_mod = 1.0f / float(1u << subphase_bits); taps = sidelobes * 2; float bandwidth_mod = out_rate / in_rate; /* Downsampling, must lower cutoff, and extend number of * taps accordingly to keep same stopband attenuation. */ if (bandwidth_mod < 1.0f) { cutoff *= bandwidth_mod; taps = unsigned(ceil(float(taps) / bandwidth_mod)); } /* Be SIMD-friendly. */ taps = (taps + 3) & ~3; unsigned phase_elems = ((1u << phase_bits) * taps); phase_elems = phase_elems * 2; unsigned elems = phase_elems + 2 * taps; main_buffer = static_cast<float *>(Util::memalign_calloc(128, sizeof(float) * elems)); if (!main_buffer) throw std::bad_alloc(); phase_table = main_buffer; window_buffer = main_buffer + phase_elems; init_table_kaiser(cutoff, 1u << phase_bits, taps, kaiser_beta); set_sample_rate_ratio(bandwidth_mod); } void SincResampler::set_sample_rate_ratio(float ratio) noexcept { phases = 1u << (phase_bits + subphase_bits); fixed_ratio = uint32_t(round(float(phases) / ratio)); } SincResampler::~SincResampler() { Util::memalign_free(main_buffer); } size_t SincResampler::get_maximum_input_for_output_frames(size_t out_frames) const noexcept { uint64_t max_start_time = phases - 1; max_start_time += uint64_t(fixed_ratio) * out_frames; max_start_time >>= phase_bits + subphase_bits; return size_t(max_start_time); } size_t SincResampler::get_current_input_for_output_frames(size_t out_frames) const noexcept { uint64_t start_time = time; start_time += uint64_t(fixed_ratio) * out_frames; start_time >>= phase_bits + subphase_bits; return size_t(start_time); } size_t SincResampler::get_maximum_output_for_input_frames(size_t in_frames) const noexcept { uint64_t max_output_time = uint64_t(phases) * in_frames + phases - 1; max_output_time = (max_output_time + fixed_ratio - 1) / fixed_ratio; return size_t(max_output_time); } template <bool accumulate> inline void SincResampler::process(float *output) const noexcept { const float *buffer = window_buffer + ptr; unsigned num_taps = taps; unsigned phase = time >> subphase_bits; const float *sample_phase_table = phase_table + phase * num_taps * 2; const float *delta_table = sample_phase_table + num_taps; #ifdef __SSE__ __m128 sum = _mm_setzero_ps(); __m128 delta = _mm_set1_ps(float(time & subphase_mask) * subphase_mod); for (unsigned i = 0; i < num_taps; i += 4) { __m128 buf = _mm_loadu_ps(buffer + i); __m128 deltas = _mm_load_ps(delta_table + i); __m128 _sinc = _mm_add_ps(_mm_load_ps(sample_phase_table + i), _mm_mul_ps(deltas, delta)); sum = _mm_add_ps(sum, _mm_mul_ps(buf, _sinc)); } // Horizontal add. sum = _mm_add_ps(_mm_shuffle_ps(sum, sum, _MM_SHUFFLE(2, 3, 2, 3)), sum); sum = _mm_add_ss(_mm_shuffle_ps(sum, sum, _MM_SHUFFLE(1, 1, 1, 1)), sum); if (accumulate) _mm_store_ss(output, _mm_add_ss(_mm_load_ss(output), sum)); else _mm_store_ss(output, sum); #elif defined(__ARM_NEON) float delta = float(time & subphase_mask) * subphase_mod; float32x4_t sum = vdupq_n_f32(0.0f); for (unsigned i = 0; i < taps; i += 4) { float32x4_t _phases = vld1q_f32(phase_table + i); float32x4_t deltas = vld1q_f32(delta_table + i); float32x4_t buf = vld1q_f32(buffer + i); float32x4_t _sinc = vmlaq_n_f32(_phases, deltas, delta); sum = vmlaq_f32(sum, buf, _sinc); } float32x2_t half = vadd_f32(vget_low_f32(sum), vget_high_f32(sum)); float32x2_t res = vpadd_f32(half, half); if (accumulate) { float32x2_t o = vld1_dup_f32(output); res = vadd_f32(o, res); vst1_lane_f32(output, res, 0); } else vst1_lane_f32(output, res, 0); #else float delta = float(time & subphase_mask) * subphase_mod; float sum = 0.0f; for (unsigned i = 0; i < taps; i++) { float sinc_val = phase_table[i] + delta_table[i] * delta; sum += buffer[i] * sinc_val; } if (accumulate) *output += sum; else *output = sum; #endif } template <bool accumulate> inline size_t SincResampler::process_input(float *output, const float *input, size_t in_frames) noexcept { uint32_t ratio = fixed_ratio; size_t rendered_frames = 0; while (in_frames) { // Drain inputs. while (in_frames && time >= phases) { // Push in reverse to make filter more obvious. if (!ptr) ptr = taps; ptr--; const float v = *input; window_buffer[ptr + taps] = v; window_buffer[ptr] = v; time -= phases; in_frames--; input++; } // Pump out samples. while (time < phases) { process<accumulate>(output); output++; time += ratio; rendered_frames++; } } return rendered_frames; } template <bool accumulate> inline size_t SincResampler::process_output(float *output, const float *input, size_t out_frames) noexcept { uint32_t ratio = fixed_ratio; size_t consumed_frames = 0; while (out_frames) { // Pump out samples. while (out_frames && time < phases) { process<accumulate>(output); output++; out_frames--; time += ratio; } // Drain inputs. while (time >= phases) { // Push in reverse to make filter more obvious. if (!ptr) ptr = taps; ptr--; const float v = input[consumed_frames]; window_buffer[ptr + taps] = v; window_buffer[ptr] = v; consumed_frames++; time -= phases; } } return consumed_frames; } size_t SincResampler::process_output_frames(float *outputs, const float *inputs, size_t out_frames) noexcept { return process_output<false>(outputs, inputs, out_frames); } size_t SincResampler::process_input_frames(float *outputs, const float *inputs, size_t in_frames) noexcept { return process_input<false>(outputs, inputs, in_frames); } size_t SincResampler::process_and_accumulate_output_frames(float *outputs, const float *inputs, size_t out_frames) noexcept { return process_output<true>(outputs, inputs, out_frames); } size_t SincResampler::process_and_accumulate_input_frames(float *outputs, const float *inputs, size_t in_frames) noexcept { return process_input<true>(outputs, inputs, in_frames); } } } }
33.282974
130
0.68881
VulkanWorks
1b30e91fe49be2eae30b75762a9de1d23b5a92e9
1,949
hpp
C++
include/operon/nnls/residual_evaluator.hpp
ivor-dd/operon
57775816304b5df7a2f64e1505693a1fdf17a2fe
[ "MIT" ]
null
null
null
include/operon/nnls/residual_evaluator.hpp
ivor-dd/operon
57775816304b5df7a2f64e1505693a1fdf17a2fe
[ "MIT" ]
null
null
null
include/operon/nnls/residual_evaluator.hpp
ivor-dd/operon
57775816304b5df7a2f64e1505693a1fdf17a2fe
[ "MIT" ]
null
null
null
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: Copyright 2019-2022 Heal Research #ifndef OPERON_NNLS_RESIDUAL_EVALUATOR_HPP #define OPERON_NNLS_RESIDUAL_EVALUATOR_HPP #include <Eigen/Core> #include "operon/interpreter/interpreter.hpp" namespace Operon { // simple functor that wraps everything together and provides residuals struct ResidualEvaluator { ResidualEvaluator(Interpreter const& interpreter, Tree const& tree, Dataset const& dataset, const Operon::Span<const Operon::Scalar> targetValues, Range const range) : interpreter_(interpreter) , tree_(tree) , dataset_(dataset) , range_(range) , target_(targetValues) , numParameters_(tree_.get().GetCoefficients().size()) { } template <typename T> auto operator()(T const* parameters, T* residuals) const -> bool { Operon::Span<T> result(residuals, target_.size()); GetInterpreter().Evaluate<T>(tree_.get(), dataset_.get(), range_, result, parameters); Eigen::Map<Eigen::Array<T, Eigen::Dynamic, 1, Eigen::ColMajor>> resMap(residuals, target_.size()); Eigen::Map<const Eigen::Array<Operon::Scalar, Eigen::Dynamic, 1, Eigen::ColMajor>> targetMap(target_.data(), static_cast<Eigen::Index>(target_.size())); resMap -= targetMap.cast<T>(); return true; } [[nodiscard]] auto NumParameters() const -> size_t { return numParameters_; } [[nodiscard]] auto NumResiduals() const -> size_t { return target_.size(); } [[nodiscard]] auto GetInterpreter() const -> Interpreter const& { return interpreter_.get(); } private: std::reference_wrapper<Interpreter const> interpreter_; std::reference_wrapper<Tree const> tree_; std::reference_wrapper<Dataset const> dataset_; Range range_; Operon::Span<const Operon::Scalar> target_; size_t numParameters_; // cache the number of parameters in the tree }; } // namespace Operon #endif
38.98
169
0.700872
ivor-dd
1b32b952375e6c2720c0d109aaa3a0d20f4f83cf
1,911
cpp
C++
native/cli/DrEyeCli.cpp
nzh63/Ame
b15e530851d6e00ec839c749fc8e016ffae38e29
[ "MIT" ]
3
2021-05-31T08:51:55.000Z
2022-02-13T10:21:19.000Z
native/cli/DrEyeCli.cpp
nzh63/Ame
b15e530851d6e00ec839c749fc8e016ffae38e29
[ "MIT" ]
2
2021-08-04T03:15:46.000Z
2021-09-26T16:20:57.000Z
native/cli/DrEyeCli.cpp
nzh63/Ame
b15e530851d6e00ec839c749fc8e016ffae38e29
[ "MIT" ]
null
null
null
#include <Windows.h> #include <array> #include <cstdlib> #include <cstring> #include <fcntl.h> #include <io.h> #include <iostream> #include <stdio.h> #include <string> using namespace std; constexpr auto BUFFER_SIZE = 4096; array<char, BUFFER_SIZE> input; array<char, BUFFER_SIZE> output; int(__cdecl *MTInit)(int dat_index); int(__cdecl *MTEnd)(); int(__cdecl *TranTextFlow)(void *src, void *dest, int dest_size, int dat_index); int main(int argc, char **argv) { _setmode(_fileno(stdin), _O_BINARY); _setmode(_fileno(stdout), _O_BINARY); HMODULE dll = LoadLibraryA(argv[1]); if (!dll) { cout << "dll open fail" << endl; return 1; } MTInit = (int(__cdecl *)(int))GetProcAddress(dll, argv[2]); MTEnd = (int(__cdecl *)())GetProcAddress(dll, argv[3]); TranTextFlow = (int(__cdecl *)(void *, void *, int, int))GetProcAddress(dll, argv[4]); if (!MTInit || !MTEnd || !TranTextFlow) { cout << "dll open fail" << endl; return 1; } int dat_index = atoi(argv[5]); MTInit(dat_index); while (1) { memset(input.data(), 0, sizeof(input)); uint16_t s; *(uint8_t *)&s = cin.get(); *((uint8_t *)&s + 1) = cin.get(); if (s == 0) break; for (int i = 0; i < s; i++) { char c = cin.get(); if (i < BUFFER_SIZE) input[i] = c; } TranTextFlow(input.data(), output.data(), BUFFER_SIZE, dat_index); uint16_t outputSize = 0; for (int i = 0; i < BUFFER_SIZE; i++) { if (output[i] == 0) { outputSize = i; break; } } cout.put(*(uint8_t *)&outputSize); cout.put(*((uint8_t *)&outputSize + 1)); for (int i = 0; i < outputSize; i++) { cout.put(output[i]); } cout.flush(); } MTEnd(); return 0; }
27.3
90
0.536368
nzh63
1b331e92986a5f412d8acc7286beea96b8736cc2
1,690
cpp
C++
CppEditorToolBar.cpp
B1anky/CppEditor
bb68ca521c35a8d7e658f9ddf789201d7b269a08
[ "MIT" ]
1
2020-09-11T12:42:15.000Z
2020-09-11T12:42:15.000Z
CppEditorToolBar.cpp
B1anky/CppEditor
bb68ca521c35a8d7e658f9ddf789201d7b269a08
[ "MIT" ]
null
null
null
CppEditorToolBar.cpp
B1anky/CppEditor
bb68ca521c35a8d7e658f9ddf789201d7b269a08
[ "MIT" ]
null
null
null
#include "CppEditorToolBar.h" #include <QPushButton> #include <QMap> CppEditorToolBar::CppEditorToolBar(QWidget* parent) : QToolBar(parent), m_runButton(nullptr), m_buildButton(nullptr) { QSize buttonSize(64, 64); QSize iconSize(50, 50); QString buttonStyle = "QPushButton{" " border: none;" " background-color: none;" "}" "QPushButton:hover:!pressed{" " background-color: rgb(125, 125, 125)" "}" "QPushButton:hover:pressed{" " background-color: rgb(85, 85, 85)" "}"; m_runButton = new QPushButton; m_runButton->setIcon(QIcon("assets/run.png")); m_runButton->setIconSize(iconSize); m_runButton->setFixedSize(buttonSize); m_runButton->setToolTip("Run Ctrl + r"); m_runButton->setStyleSheet(buttonStyle); m_buildButton = new QPushButton; m_buildButton->setIcon(QIcon("assets/build.png")); m_buildButton->setIconSize(iconSize); m_buildButton->setFixedSize(buttonSize); m_buildButton->setToolTip("Build Ctrl + b"); m_buildButton->setStyleSheet(buttonStyle); QWidget* spacer = new QWidget(); spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); addWidget(spacer); m_actionMap[addWidget(m_runButton)] = m_runButton; m_actionMap[addWidget(m_buildButton)] = m_buildButton; setStyleSheet("QToolBar {" " background: rgb(20, 25, 31);" "}"); }
33.8
75
0.56568
B1anky
1b3926268982cd43a2b8968874101a78df724948
19,573
hh
C++
gazebo/common/Event.hh
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
8
2015-07-02T08:23:30.000Z
2020-11-17T19:00:38.000Z
gazebo/common/Event.hh
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/common/Event.hh
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
10
2015-04-22T18:33:15.000Z
2021-11-16T10:17:45.000Z
/* * Copyright 2012 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _EVENT_HH_ #define _EVENT_HH_ #include <gazebo/gazebo_config.h> #include <gazebo/common/Time.hh> #include <gazebo/common/CommonTypes.hh> #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/thread/mutex.hpp> #include <iostream> #include <vector> namespace gazebo { /// \ingroup gazebo_event /// \brief Event namespace namespace event { /// \addtogroup gazebo_event Events /// \{ /// \class Event Event.hh common/common.hh /// \brief Base class for all events class Event { /// \brief Constructor public: virtual ~Event() {} /// \brief Disconnect /// \param[in] _c A pointer to a connection public: virtual void Disconnect(ConnectionPtr _c) = 0; /// \brief Disconnect /// \param[in] _id Integer ID of a connection public: virtual void Disconnect(int _id) = 0; }; /// \brief A class that encapsulates a connection class Connection { /// \brief Constructor public: Connection() :event(NULL), id(-1) {} /// \brief Constructor /// \param[in] _e Event pointer to connect with /// \param[in] _i Unique id public: Connection(Event *_e, int _i); /// \brief Destructor public: ~Connection(); /// \brief Get the id of this connection /// \return The id of this connection public: int GetId() const; /// \brief the event for this connection private: Event *event; /// \brief the id set in the constructor private: int id; /// \brief not used. set to 0 private: static int counter; /// \brief set during the constructor private: common::Time creationTime; public: template<typename T> friend class EventT; }; /// \class EventT Event.hh common/common.hh /// \brief A class for event processing template< typename T> class EventT : public Event { /// \brief Destructor public: virtual ~EventT(); /// \brief Connect a callback to this event /// \param[in] _subscriber Pointer to a callback function /// \return A Connection object, which will automatically call /// Disconnect when it goes out of scope public: ConnectionPtr Connect(const boost::function<T> &_subscriber); /// \brief Disconnect a callback to this event /// \param[in] _c The connection to disconnect public: virtual void Disconnect(ConnectionPtr _c); /// \brief Disconnect a callback to this event /// \param[in] _id The id of the connection to disconnect public: virtual void Disconnect(int _id); /// \brief Get the number of connections. /// \return Number of connection to this Event. public: unsigned int ConnectionCount() const; /// \brief Access the signal public: void operator()() {this->Signal();} /// \brief Signal the event for all subscribers public: void Signal() { for (unsigned int i = 0; i < connections.size(); i++) { (*this->connections[i])(); } } /// \brief Signal the event with one parameter /// \param[in] _p the parameter public: template< typename P > void operator()(const P &_p) { this->Signal(_p); } /// \brief Signal the event with two parameters /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter public: template< typename P1, typename P2 > void operator()(const P1 &_p1, const P2 &_p2) { this->Signal(_p1, _p2); } /// \brief Signal the event with three parameters /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter public: template< typename P1, typename P2, typename P3 > void operator()(const P1 &_p1, const P2 &_p2, const P3 &_p3) { this->Signal(_p1, _p2, _p3); } /// \brief Signal the event with four parameters /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter /// \param[in] _p4 the first parameter public: template< typename P1, typename P2, typename P3, typename P4 > void operator()(const P1 &_p1, const P2 &_p2, const P3 &_p3, const P4 &_p4) { this->Signal(_p1, _p2, _p3, _p4); } /// \brief Signal the event with five parameters /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter /// \param[in] _p4 the first parameter /// \param[in] _p5 the fift parameter public: template< typename P1, typename P2, typename P3, typename P4, typename P5 > void operator()(const P1 &_p1, const P2 &_p2, const P3 &_p3, const P4 &_p4, const P5 &_p5) { this->Signal(_p1, _p2, _p3, _p4, _p5); } /// \brief Signal the event with six parameters /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter /// \param[in] _p4 the first parameter /// \param[in] _p5 the fift parameter /// \param[in] _p6 the sixt parameter public: template< typename P1, typename P2, typename P3, typename P4, typename P5, typename P6 > void operator()(const P1 &_p1, const P2 &_p2, const P3 &_p3, const P4 &_p4, const P5 &_p5, const P6 &_p6) { this->Signal(_p1, _p2, _p3, _p4, _p5, _p6); } /// \brief Signal the event with seven parameters /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter /// \param[in] _p4 the first parameter /// \param[in] _p5 the fifth parameter /// \param[in] _p6 the sixth parameter /// \param[in] _p7 the seventh parameter public: template< typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7 > void operator()(const P1 &_p1, const P2 &_p2, const P3 &_p3, const P4 &_p4, const P5 &_p5, const P6 &_p6, const P7 &_p7) { this->Signal(_p1, _p2, _p3, _p4, _p5, _p6, _p7); } /// \brief Signal the event with eight parameters /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter /// \param[in] _p4 the first parameter /// \param[in] _p5 the fifth parameter /// \param[in] _p6 the sixth parameter /// \param[in] _p7 the seventh parameter /// \param[in] _p8 the eighth parameter public: template< typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8 > void operator()(const P1 &_p1, const P2 &_p2, const P3 &_p3, const P4 &_p4, const P5 &_p5, const P6 &_p6, const P7 &_p7, const P8 &_p8) { this->Signal(_p1, _p2, _p3, _p4, _p5, _p6, _p7, _p8); } /// \brief Signal the event with nine parameters /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter /// \param[in] _p4 the first parameter /// \param[in] _p5 the fifth parameter /// \param[in] _p6 the sixth parameter /// \param[in] _p7 the seventh parameter /// \param[in] _p8 the eighth parameter /// \param[in] _p9 the ninth parameter public: template< typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9 > void operator()(const P1 &_p1, const P2 &_p2, const P3 &_p3, const P4 &_p4, const P5 &_p5, const P6 &_p6, const P7 &_p7, const P8 &_p8, const P9 &_p9) { this->Signal(_p1, _p2, _p3, _p4, _p5, _p6, _p7, _p8, _p9); } /// \brief Signal the event with ten parameters /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter /// \param[in] _p4 the first parameter /// \param[in] _p5 the fifth parameter /// \param[in] _p6 the sixth parameter /// \param[in] _p7 the seventh parameter /// \param[in] _p8 the eighth parameter /// \param[in] _p9 the ninth parameter /// \param[in] _p10 the tenth parameter public: template< typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9, typename P10 > void operator()(const P1 &_p1, const P2 &_p2, const P3 &_p3, const P4 &_p4, const P5 &_p5, const P6 &_p6, const P7 &_p7, const P8 &_p8, const P9 &_p9, const P10 &_p10) { this->Signal(_p1, _p2, _p3, _p4, _p5, _p6, _p7, _p8, _p9, _p10); } /// \brief Signal the event with one parameter /// \param[in] _p parameter public: template< typename P > void Signal(const P &_p) { for (unsigned int i = 0; i < connections.size(); i++) { (*this->connections[i])(_p); } } /// \brief Signal the event with two parameter /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter public: template< typename P1, typename P2 > void Signal(const P1 &_p1, const P2 &_p2) { for (unsigned int i = 0; i < connections.size(); i++) { (*this->connections[i])(_p1, _p2); } } /// \brief Signal the event with three parameter /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter public: template< typename P1, typename P2, typename P3 > void Signal(const P1 &_p1, const P2 &_p2, const P3 &_p3) { for (unsigned int i = 0; i < connections.size(); i++) { (*this->connections[i])(_p1, _p2, _p3); } } /// \brief Signal the event with four parameter /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter /// \param[in] _p4 the first parameter public: template<typename P1, typename P2, typename P3, typename P4> void Signal(const P1 &_p1, const P2 &_p2, const P3 &_p3, const P4 &_p4) { for (unsigned int i = 0; i < connections.size(); i++) { (*this->connections[i])(_p1, _p2, _p3, _p4); } } /// \brief Signal the event with five parameter /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter /// \param[in] _p4 the first parameter /// \param[in] _p5 the fifth parameter public: template<typename P1, typename P2, typename P3, typename P4, typename P5> void Signal(const P1 &_p1, const P2 &_p2, const P3 &_p3, const P4 &_p4, const P5 &_p5) { for (unsigned int i = 0; i < connections.size(); i++) { (*this->connections[i])(_p1, _p2, _p3, _p4, _p5); } } /// \brief Signal the event with six parameter /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter /// \param[in] _p4 the first parameter /// \param[in] _p5 the fifth parameter /// \param[in] _p6 the sixth parameter public: template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6> void Signal(const P1 &_p1, const P2 &_p2, const P3 &_p3, const P4 &_p4, const P5 &_p5, const P6 &_p6) { for (unsigned int i = 0; i < connections.size(); i++) { (*this->connections[i])(_p1, _p2, _p3, _p4, _p5, _p6); } } /// \brief Signal the event with seven parameter /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter /// \param[in] _p4 the first parameter /// \param[in] _p5 the fifth parameter /// \param[in] _p6 the sixth parameter /// \param[in] _p7 the seventh parameter public: template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7> void Signal(const P1 &_p1, const P2 &_p2, const P3 &_p3, const P4 &_p4, const P5 &_p5, const P6 &_p6, const P7 &_p7) { for (unsigned int i = 0; i < connections.size(); i++) { (*this->connections[i])(_p1, _p2, _p3, _p4, _p5, _p6, _p7); } } /// \brief Signal the event with eight parameter /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter /// \param[in] _p4 the first parameter /// \param[in] _p5 the fifth parameter /// \param[in] _p6 the sixth parameter /// \param[in] _p7 the seventh parameter /// \param[in] _p8 the eighth parameter public: template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8> void Signal(const P1 &_p1, const P2 &_p2, const P3 &_p3, const P4 &_p4, const P5 &_p5, const P6 &_p6, const P7 &_p7, const P8 &_p8) { for (unsigned int i = 0; i < connections.size(); i++) { (*this->connections[i])(_p1, _p2, _p3, _p4, _p5, _p6, _p7, _p8); } } /// \brief Signal the event with nine parameter /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter /// \param[in] _p4 the first parameter /// \param[in] _p5 the fifth parameter /// \param[in] _p6 the sixth parameter /// \param[in] _p7 the seventh parameter /// \param[in] _p8 the eighth parameter /// \param[in] _p9 the ninth parameter public: template< typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9 > void Signal(const P1 &_p1, const P2 &_p2, const P3 &_p3, const P4 &_p4, const P5 &_p5, const P6 &_p6, const P7 &_p7, const P8 &_p8, const P9 &_p9) { for (unsigned int i = 0; i < connections.size(); i++) { (*this->connections[i])(_p1, _p2, _p3, _p4, _p5, _p6, _p7, _p8, _p9); } } /// \brief Signal the event with ten parameter /// \param[in] _p1 the first parameter /// \param[in] _p2 the second parameter /// \param[in] _p3 the second parameter /// \param[in] _p4 the first parameter /// \param[in] _p5 the fifth parameter /// \param[in] _p6 the sixth parameter /// \param[in] _p7 the seventh parameter /// \param[in] _p8 the eighth parameter /// \param[in] _p9 the ninth parameter /// \param[in] _p10 the tenth parameter public: template< typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9, typename P10 > void Signal(const P1 &_p1, const P2 &_p2, const P3 &_p3, const P4 &_p4, const P5 &_p5, const P6 &_p6, const P7 &_p7, const P8 &_p8, const P9 &_p9, const P10 &_p10) { for (unsigned int i = 0; i < connections.size(); i++) { (*this->connections[i])(_p1, _p2, _p3, _p4, _p5, _p6, _p7, _p8, _p9, _p10); } } /// \brief array of connection callbacks private: std::vector<boost::function<T> *> connections; /// \brief array of connection indexes private: std::vector<int> connectionIds; /// \brief a thread lock private: boost::mutex lock; }; /// \brief Destructor. Deletes all the associated connections. template<typename T> EventT<T>::~EventT() { for (unsigned int i = 0; i < this->connections.size(); i++) delete this->connections[i]; this->connections.clear(); this->connectionIds.clear(); } /// \brief Adds a connection /// \param[in] _subscriber the subscriber to connect template<typename T> ConnectionPtr EventT<T>::Connect(const boost::function<T> &_subscriber) { int index = this->connections.size(); this->connections.push_back(new boost::function<T>(_subscriber)); this->connectionIds.push_back(index); return ConnectionPtr(new Connection(this, index)); } /// \brief Removes a connection /// \param[in] _c the connection template<typename T> void EventT<T>::Disconnect(ConnectionPtr _c) { if (!_c) return; this->Disconnect(_c->GetId()); _c->event = NULL; _c->id = -1; } template<typename T> unsigned int EventT<T>::ConnectionCount() const { return this->connections.size(); } /// \brief Removes a connection /// \param[in] _id the connection index template<typename T> void EventT<T>::Disconnect(int _id) { // search for index of the connection based on id for (unsigned int i = 0; i < this->connectionIds.size(); i++) { if (_id == this->connectionIds[i]) { this->connectionIds.erase(this->connectionIds.begin()+i); this->connections.erase(this->connections.begin()+i); break; } } } /// \} } } #endif
38.99004
80
0.557298
thomas-moulard
1b39f35b48b0e7d3d2750e8b7efa38d53c9f2042
7,345
hh
C++
include/tchecker/variables/variables.hh
pictavien/tchecker
5db2430b5b75a5b94cfbbe885840a4809b267be8
[ "MIT" ]
null
null
null
include/tchecker/variables/variables.hh
pictavien/tchecker
5db2430b5b75a5b94cfbbe885840a4809b267be8
[ "MIT" ]
null
null
null
include/tchecker/variables/variables.hh
pictavien/tchecker
5db2430b5b75a5b94cfbbe885840a4809b267be8
[ "MIT" ]
null
null
null
/* * This file is a part of the TChecker project. * * See files AUTHORS and LICENSE for copyright details. * */ #ifndef TCHECKER_VARIABLES_HH #define TCHECKER_VARIABLES_HH #include <sstream> #include <string> #include <boost/container/flat_map.hpp> #include "tchecker/basictypes.hh" #include "tchecker/utils/index.hh" /*! \file variables.hh \brief Definition of variables */ namespace tchecker { /*! \class variables_t \brief Definition of variables (unspecified type) \tparam ID : type of variable identifiers \tparam INFO : type of variable informations \tparam INDEX : type of variable index, should derive from tchecker::index_t */ template <class ID, class INFO, class INDEX> class variables_t { static_assert(std::is_base_of<tchecker::index_t<ID, std::string>, INDEX>::value, "Bad template parameter INDEX"); protected: /*! \brief Type of map ID -> info */ using info_map_t = boost::container::flat_map<ID, INFO>; public: /*! \brief Type of identifier */ using id_t = ID; /*! \brief Type of informations */ using info_t = INFO; /*! \brief Type of index */ using index_t = INDEX; /*! \brief Constructor */ variables_t() = default; /*! \brief Copy constructor */ variables_t(tchecker::variables_t<ID, INFO, INDEX> const &) = default; /*! \brief Move constructor */ variables_t(tchecker::variables_t<ID, INFO, INDEX> &&) = default; /*! \brief Destructor */ ~variables_t() = default; /*! \brief Assignment operator */ tchecker::variables_t<ID, INFO, INDEX> & operator= (tchecker::variables_t<ID, INFO, INDEX> const &) = default; /*! \brief Move assignment operator */ tchecker::variables_t<ID, INFO, INDEX> & operator= (tchecker::variables_t<ID, INFO, INDEX> &&) = default; /*! \brief Accessor \return index of variables */ inline INDEX const & index() const { return _index; } /*! \brief Accessor \param name : variable name \return ID of name \pre name is a declared variable \throw std::invalid_argument if precondition is violated */ inline ID id(std::string const & name) const { auto it = _index.find_value(name); if (it == _index.end_value_map()) throw std::invalid_argument("unknown variable " + name); return _index.key(*it); } /*! \brief Accessor \param id : variable id \return name of variable id \pre id is a declared variable \throw std::invalid_argument id precondition is violated */ inline std::string const & name(ID id) const { auto it = _index.find_key(id); if (it == _index.end_key_map()) throw std::invalid_argument("unknown variable ID"); return _index.value(*it); } /*! \brief Accessor \param id : variable ID \pre id is a declared variable \return informations for variable id \throw std::invalid_argument : if the precondition is violated */ inline INFO const & info(ID id) const { auto it = _info.find(id); if (it == _info.end()) throw std::invalid_argument("unknown variable ID"); return it->second; } /*! \brief Accessor \return Number of variables */ inline std::size_t size() const { return _index.size(); } /*! \brief Declare a variable \param id : variable identifier \param name : variable name \param info : variable informations \pre there is no declared variables with id or name \throw std::invalid_argument : if the precondition is violated */ void declare(ID id, std::string const & name, INFO const & info) { _index.add(id, name); _info.insert(std::make_pair(id, info)); } protected: INDEX _index; /*!< Index of variables */ info_map_t _info; /*!< Map variable ID -> informations */ }; /*! \class variables_with_layout_t \brief Definition of variables (unspecified type), with memory layout of these variables. Variable identifiers ensure that arrays are implemented as consecutive memory cells. All identifiers from 0 to layout().size()-1 are valid layout variable identifiers. \tparam ID : type of variable identifiers \tparam INFO : type of variable informations \tparam INDEX : type of variable index, should derive from tchecker::index_t */ template <class ID, class INFO, class INDEX> class variables_with_layout_t : public tchecker::variables_t<ID, INFO, INDEX> { public: /*! \brief Type of variables layout */ using layout_t = tchecker::variables_t<ID, INFO, INDEX>; /*! \brief Constructor */ variables_with_layout_t() = default; /*! \brief Copy constructor */ variables_with_layout_t(tchecker::variables_with_layout_t<ID, INFO, INDEX> const &) = default; /*! \brief Move constructor */ variables_with_layout_t(tchecker::variables_with_layout_t<ID, INFO, INDEX> &&) = default; /*! \brief Destructor */ ~variables_with_layout_t() = default; /*! \brief Assignment operator */ tchecker::variables_with_layout_t<ID, INFO, INDEX> & operator= (tchecker::variables_with_layout_t<ID, INFO, INDEX> const &) = default; /*! \brief Move assignment operator */ tchecker::variables_with_layout_t<ID, INFO, INDEX> & operator= (tchecker::variables_with_layout_t<ID, INFO, INDEX> &&) = default; /*! \brief Accessor \return layout */ inline layout_t const & layout() const { return _layout; } /*! \brief Declare an integer variable \param name : variable name \param size : size (array) \param args : extra parameters for INFO \pre variable name is not declared yet, size > 0, and INFO has a constructor with parameters (size, args) \post the variable has been added \throw std::invalid_argument : if the precondition is violated */ template <class ... ARGS> void declare(std::string const & name, unsigned int size, ARGS && ... args) { // ID ID id = static_cast<ID>(_layout.size()); // declare variable INFO info(size, args...); tchecker::variables_t<ID, INFO, INDEX>::declare(id, name, info); // declare layout variables INFO layout_info(1, args...); if (size == 1) _layout.declare(id, name, layout_info); else { std::stringstream s; for (size_t i = 0; i < size; ++i) { s << name << "[" << i << "]"; _layout.declare(static_cast<ID>(id + i), s.str(), layout_info); s.clear(); } } } protected: /*! \brief Hidden inherited declare() method */ using tchecker::variables_t<ID, INFO, INDEX>::declare; layout_t _layout; /*!< Variables layout */ }; } // end of namespace tchecker #endif // TCHECKER_VARIABLES_HH
24.401993
114
0.600408
pictavien
1b3afa8dc03ac5d7830c9a8e5ee786122510e73a
2,272
hpp
C++
Engine/Core/Headers/Molten/Gui/Widgets/ViewportWidget.hpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
2
2019-11-11T21:17:14.000Z
2019-11-11T22:07:26.000Z
Engine/Core/Headers/Molten/Gui/Widgets/ViewportWidget.hpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
null
null
null
Engine/Core/Headers/Molten/Gui/Widgets/ViewportWidget.hpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
1
2020-04-05T03:50:57.000Z
2020-04-05T03:50:57.000Z
/* * MIT License * * Copyright (c) 2022 Jimmie Bergmann * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files(the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions : * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #ifndef MOLTEN_CORE_GUI_WIDGETS_VIEWPORTWIDGET_HPP #define MOLTEN_CORE_GUI_WIDGETS_VIEWPORTWIDGET_HPP #include "Molten/Gui/Widget.hpp" #include "Molten/Gui/WidgetEvent.hpp" #include "Molten/Gui/VisibilityWidget.hpp" #include "Molten/System/Signal.hpp" #include "Molten/Renderer/RenderResource.hpp" #include "Molten/Renderer/Texture.hpp" namespace Molten::Gui { template<typename TTheme> class Viewport : public WidgetMixin<TTheme, Viewport>, public WidgetMouseEventHandler, public VisibilityWidget { public: Signal<Vector2ui32> onResize; struct State { SharedRenderResource<FramedTexture2D> framedTexture; }; explicit Viewport(WidgetMixinDescriptor<TTheme, Viewport>& desc); void SetTexture(SharedRenderResource<FramedTexture2D> framedTexture); private: void OnUpdate(WidgetUpdateContext<TTheme>& updateContext) override; bool OnMouseEvent(const WidgetMouseEvent& widgetMouseEvent) override; using Mixin = WidgetMixin<TTheme, Viewport>; Vector2f32 m_prevSize; }; } #include "Molten/Gui/Widgets/ViewportWidget.inl" #endif
31.123288
114
0.754842
jimmiebergmann
1b3b9f290a24fc4f39bdbf6f299f15e750303514
4,817
cpp
C++
Tests/CPP_Bindings/Source/BuildItems.cpp
alexanderoster/lib3mf
30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05
[ "BSD-2-Clause" ]
171
2015-04-30T21:54:02.000Z
2022-03-13T13:33:59.000Z
Tests/CPP_Bindings/Source/BuildItems.cpp
alexanderoster/lib3mf
30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05
[ "BSD-2-Clause" ]
190
2015-07-21T22:15:54.000Z
2022-03-30T15:48:37.000Z
Tests/CPP_Bindings/Source/BuildItems.cpp
alexanderoster/lib3mf
30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05
[ "BSD-2-Clause" ]
80
2015-04-30T22:15:54.000Z
2022-03-09T12:38:49.000Z
/*++ Copyright (C) 2019 3MF Consortium 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Abstract: UnitTest_BuildItems.cpp: Defines Unittests for the BuildItems class --*/ #include "UnitTest_Utilities.h" #include "lib3mf_implicit.hpp" namespace Lib3MF { class BuildItems : public Lib3MFTest { protected: virtual void SetUp() { model = wrapper->CreateModel(); auto reader3MF= model->QueryReader("3mf"); reader3MF->ReadFromFile(InFolder + "WagonWithWheels.3mf"); } virtual void TearDown() { model.reset(); } PModel model; static std::string InFolder; }; std::string BuildItems::InFolder(sTestFilesPath + "/BuildItems/"); TEST_F(BuildItems, TestIterating) { auto buildItems = BuildItems::model->GetBuildItems(); Lib3MF_uint64 nBuildItems = 0; while (buildItems->MoveNext()) { auto buildItem = buildItems->GetCurrent(); nBuildItems++; } ASSERT_EQ(nBuildItems, 2); } TEST_F(BuildItems, TestObjectID) { auto buildItems = BuildItems::model->GetBuildItems(); while (buildItems->MoveNext()) { auto buildItem = buildItems->GetCurrent(); Lib3MF_uint32 objectID = buildItem->GetObjectResource()->GetResourceID(); ASSERT_EQ(buildItem->GetObjectResourceID(), objectID); } } TEST_F(BuildItems, TestUUID) { auto buildItems = BuildItems::model->GetBuildItems(); ASSERT_TRUE(buildItems->MoveNext()); auto buildItem1 = buildItems->GetCurrent(); bool bHasUUID = false; auto uuidString = buildItem1->GetUUID(bHasUUID); ASSERT_TRUE(bHasUUID); //try { // buildItem1->SetUUID(uuidString); // ASSERT_TRUE(true) << "Self assignment of UUIDs should work"; //} //catch (ELib3MFException) { // ASSERT_TRUE(false); //} ASSERT_TRUE(buildItems->MoveNext()); auto buildItem2 = buildItems->GetCurrent(); try { buildItem2->SetUUID(uuidString); ASSERT_TRUE(false) << "Duplicate UUIDs must fail"; } catch (ELib3MFException) { ASSERT_TRUE(true); } } TEST_F(BuildItems, TestTransformations) { auto buildItems = BuildItems::model->GetBuildItems(); ASSERT_TRUE(buildItems->MoveNext()); auto buildItem = buildItems->GetCurrent(); sTransform transformation; for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) transformation.m_Fields[i][j] = Lib3MF_single(i - j); } buildItem->SetObjectTransform(transformation); ASSERT_TRUE(buildItem->HasObjectTransform()); auto newTransformation = buildItem->GetObjectTransform(); for (int i = 0; i < 4; i++) for (int j = 0; j < 3; j++) ASSERT_EQ(transformation.m_Fields[i][j], newTransformation.m_Fields[i][j]); } TEST_F(BuildItems, TestItem) { auto buildItems = BuildItems::model->GetBuildItems(); ASSERT_TRUE(buildItems->MoveNext()); { auto buildItem = buildItems->GetCurrent(); auto componentsObject = buildItem->GetObjectResource(); ASSERT_FALSE(componentsObject->IsMeshObject()); ASSERT_TRUE(componentsObject->IsComponentsObject()); ASSERT_FALSE(buildItem->HasObjectTransform()); std::string partNumber("TestComponent"); buildItem->SetPartNumber(partNumber); auto newPartNumber = buildItem->GetPartNumber(); ASSERT_TRUE(partNumber == newPartNumber); } ASSERT_TRUE(buildItems->MoveNext()); { auto buildItem = buildItems->GetCurrent(); auto meshObject = buildItem->GetObjectResource(); ASSERT_TRUE(meshObject->IsMeshObject()); ASSERT_FALSE(meshObject->IsComponentsObject()); ASSERT_TRUE(buildItem->HasObjectTransform()); auto partNumber = buildItem->GetPartNumber(); ASSERT_TRUE(partNumber == "spare wheel"); } ASSERT_FALSE(buildItems->MoveNext()); } }
29.552147
80
0.734482
alexanderoster
1b40ebfde435ab66bcc1f596504422032a7b2678
2,513
cpp
C++
src/MeshViewGamestate.cpp
codenamecpp/GrimLandsKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
14
2020-06-27T18:51:41.000Z
2022-03-30T18:20:02.000Z
src/MeshViewGamestate.cpp
codenamecpp/GLKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
1
2020-06-07T09:48:11.000Z
2020-06-07T09:48:11.000Z
src/MeshViewGamestate.cpp
codenamecpp/GrimLandsKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
2
2020-08-27T09:38:10.000Z
2021-08-12T01:17:30.000Z
#include "pch.h" #include "MeshViewGamestate.h" #include "GameMain.h" #include "RenderScene.h" #include "System.h" #include "SceneObject.h" #include "ModelAssetsManager.h" #include "RenderableModel.h" #include "TimeManager.h" #include "ToolsUIManager.h" #include "GraphicsDevice.h" ////////////////////////////////////////////////////////////////////////// #define MESH_VIEW_CAMERA_YAW_DEG 90.0f #define MESH_VIEW_CAMERA_PITCH_DEG 75.0f #define MESH_VIEW_CAMERA_DISTANCE 3.0f #define MESH_VIEW_CAMERA_NEAR 0.01f #define MESH_VIEW_CAMERA_FAR 100.0f #define MESH_VIEW_CAMERA_FOVY 60.0f ////////////////////////////////////////////////////////////////////////// void MeshViewGamestate::HandleGamestateEnter() { mOrbitCameraController.SetParams(MESH_VIEW_CAMERA_YAW_DEG, MESH_VIEW_CAMERA_PITCH_DEG, MESH_VIEW_CAMERA_DISTANCE); // setup scene camera gRenderScene.mCamera.SetPerspective(gGraphicsDevice.GetScreenResolutionAspect(), MESH_VIEW_CAMERA_FOVY, MESH_VIEW_CAMERA_NEAR, MESH_VIEW_CAMERA_FAR); gRenderScene.SetCameraController(&mOrbitCameraController); mOrbitCameraController.ResetOrientation(); ModelAsset* modelAsset = gModelsManager.LoadModelAsset("vampire-pray"); mModelObject = new RenderableModel; debug_assert(mModelObject); mModelObject->SetModelAsset(modelAsset); mModelObject->StartAnimation(24.0f, true); gToolsUIManager.AttachWindow(&mMeshViewWindow); mMeshViewWindow.SetWindowShown(true); mMeshViewWindow.Setup(this); } void MeshViewGamestate::HandleGamestateLeave() { gRenderScene.SetCameraController(nullptr); if (mModelObject) { mModelObject->DestroyObject(); mModelObject = nullptr; } gToolsUIManager.DetachWindow(&mMeshViewWindow); } void MeshViewGamestate::HandleUpdateFrame() { } void MeshViewGamestate::HandleInputEvent(MouseButtonInputEvent& inputEvent) { } void MeshViewGamestate::HandleInputEvent(MouseMovedInputEvent& inputEvent) { } void MeshViewGamestate::HandleInputEvent(MouseScrollInputEvent& inputEvent) { } void MeshViewGamestate::HandleInputEvent(KeyInputEvent& inputEvent) { } void MeshViewGamestate::HandleInputEvent(KeyCharEvent& inputEvent) { } void MeshViewGamestate::HandleScreenResolutionChanged() { gRenderScene.mCamera.SetPerspective(gGraphicsDevice.GetScreenResolutionAspect(), MESH_VIEW_CAMERA_FOVY, MESH_VIEW_CAMERA_NEAR, MESH_VIEW_CAMERA_FAR); }
28.885057
154
0.719061
codenamecpp
1b47b3f2453b67a489420e6bd3cded24f35deaab
3,087
cc
C++
server/modules/routing/pinloki/resultset.cc
crspecter/MaxScale
471fa20a09ebc954fc3304500037b6b55dbbf9f1
[ "BSD-3-Clause" ]
1
2021-02-07T01:57:32.000Z
2021-02-07T01:57:32.000Z
server/modules/routing/pinloki/resultset.cc
crspecter/MaxScale
471fa20a09ebc954fc3304500037b6b55dbbf9f1
[ "BSD-3-Clause" ]
null
null
null
server/modules/routing/pinloki/resultset.cc
crspecter/MaxScale
471fa20a09ebc954fc3304500037b6b55dbbf9f1
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2020 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2025-01-25 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #include "resultset.hh" #include "strings.h" #include <algorithm> #include <cassert> #include <iostream> #include <unistd.h> namespace maxsql { ResultSet::ResultSet(st_mysql* conn) : m_result(nullptr) , m_num_rows(0) { int ncolls = mysql_field_count(conn); if (ncolls) { if (!(m_result = mysql_use_result(conn))) { MXB_THROWCode(DatabaseError, mysql_errno(conn), "Failed to get result set. " << " : mysql_error " << mysql_error(conn)); } st_mysql_field* fields = mysql_fetch_fields(m_result); for (int i = 0; i < ncolls; ++i) { m_column_names.push_back(fields[i].name); } } } ResultSet::~ResultSet() { mysql_free_result(m_result); } void ResultSet::discard_result() { // TODO. There must be a fast way, mariadb_cancel? Iterator ite = begin(); while (ite != end()) { ++ite; } } std::vector<std::string> ResultSet::column_names() const { return m_column_names; } ResultSet::Iterator ResultSet::begin() { return Iterator(m_result); } ResultSet::Iterator ResultSet::end() { return Iterator(); } ResultSet::Iterator::Iterator() : m_current_row(0) , m_row_nr(-1) { } ResultSet::Iterator::Iterator(st_mysql_res* res) : m_result{res} , m_current_row(m_result ? mysql_num_fields(m_result) : 0) , m_row_nr{m_result ? 0 : -1} { if (m_row_nr != -1) { _read_one(); } } void ResultSet::Iterator::_read_one() { auto db_row = mysql_fetch_row(m_result); if (!db_row) { m_row_nr = -1; // end Iterator } else { int sz = m_current_row.columns.size(); for (int i = 0; i < sz; ++i) { if (db_row[i]) { m_current_row.columns[i] = db_row[i]; } else { m_current_row.columns.clear(); } } ++m_row_nr; } } ResultSet::Iterator ResultSet::Iterator::operator++() { _read_one(); return *this; } ResultSet::Iterator ResultSet::Iterator::operator++(int) { auto ret = *this; return ++(*this); } bool ResultSet::Iterator::operator==(const ResultSet::Iterator& rhs) const { return m_row_nr == rhs.m_row_nr; } bool ResultSet::Iterator::operator!=(const ResultSet::Iterator& rhs) const { return m_row_nr != rhs.m_row_nr; } const ResultSet::Row& ResultSet::Iterator::operator*() const { return m_current_row; } const ResultSet::Row* ResultSet::Iterator::operator->() { return &m_current_row; } const ResultSet::Row* ResultSet::Iterator::operator->() const { return &m_current_row; } }
19.916129
98
0.607062
crspecter
1b490b43336ba9aa1893eef5fd59424e7363523b
1,089
cpp
C++
xlloption/fms_sequence_null.t.cpp
GR6250-2019/hw6
13a78ed4474c5e37b82a3ded10eef95b706e382b
[ "MIT" ]
null
null
null
xlloption/fms_sequence_null.t.cpp
GR6250-2019/hw6
13a78ed4474c5e37b82a3ded10eef95b706e382b
[ "MIT" ]
null
null
null
xlloption/fms_sequence_null.t.cpp
GR6250-2019/hw6
13a78ed4474c5e37b82a3ded10eef95b706e382b
[ "MIT" ]
null
null
null
// fms_sequence_null.cpp - Zero terminated sequence. #include <cassert> #include "fms_sequence_null.h" #include "fms_sequence_equal.h" #include "fms_sequence_length.h" #include "fms_sequence_list.h" using namespace fms::sequence; template<class X> int test_fms_sequence_null() { { X x[] = { 1, 2, 0 }; auto s = null(x); auto s2(s); s = s2; assert(equal(s, s2)); assert(s == s2); assert(!(s != s2)); assert(s <= s2); assert(!(s < s2)); assert(s >= s2); assert(!(s > s2)); assert(2 == length(s)); assert(s); assert(*s == 1); ++s; assert(s); assert(*s == 2); ++s; assert(!s); } { auto ab = null("ab"); auto ab2(ab); ab = ab2; assert(ab); assert('a' == *ab); ++ab; assert(ab); assert('b' == *ab); ++ab; assert(!ab); } return 0; } int test_fms_sequence_char = test_fms_sequence_null<char>();
22.22449
60
0.458219
GR6250-2019
1b5530fb7296f7e47b1dd157cc2f3a842f62182b
3,686
cpp
C++
unittests/ADT/StatisticTest.cpp
URSec/Silhouette-Compiler-Legacy
28b37f3617c5543a87537decc074b168f4803d87
[ "Apache-2.0" ]
938
2015-12-03T16:45:43.000Z
2022-03-17T20:28:02.000Z
unittests/ADT/StatisticTest.cpp
URSec/Silhouette-Compiler-Legacy
28b37f3617c5543a87537decc074b168f4803d87
[ "Apache-2.0" ]
127
2015-12-03T21:42:53.000Z
2019-11-21T14:34:20.000Z
unittests/ADT/StatisticTest.cpp
URSec/Silhouette-Compiler-Legacy
28b37f3617c5543a87537decc074b168f4803d87
[ "Apache-2.0" ]
280
2015-12-03T16:51:35.000Z
2022-01-24T00:01:54.000Z
//===- llvm/unittest/ADT/StatisticTest.cpp - Statistic unit tests ---------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/ADT/Statistic.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace llvm; using OptionalStatistic = Optional<std::pair<StringRef, unsigned>>; namespace { #define DEBUG_TYPE "unittest" STATISTIC(Counter, "Counts things"); STATISTIC(Counter2, "Counts other things"); #if LLVM_ENABLE_STATS static void extractCounters(const std::vector<std::pair<StringRef, unsigned>> &Range, OptionalStatistic &S1, OptionalStatistic &S2) { for (const auto &S : Range) { if (S.first == "Counter") S1 = S; if (S.first == "Counter2") S2 = S; } } #endif TEST(StatisticTest, Count) { EnableStatistics(); Counter = 0; EXPECT_EQ(Counter, 0u); Counter++; Counter++; #if LLVM_ENABLE_STATS EXPECT_EQ(Counter, 2u); #else EXPECT_EQ(Counter, 0u); #endif } TEST(StatisticTest, Assign) { EnableStatistics(); Counter = 2; #if LLVM_ENABLE_STATS EXPECT_EQ(Counter, 2u); #else EXPECT_EQ(Counter, 0u); #endif } TEST(StatisticTest, API) { EnableStatistics(); Counter = 0; EXPECT_EQ(Counter, 0u); Counter++; Counter++; #if LLVM_ENABLE_STATS EXPECT_EQ(Counter, 2u); #else EXPECT_EQ(Counter, 0u); #endif #if LLVM_ENABLE_STATS { const auto Range1 = GetStatistics(); EXPECT_NE(Range1.begin(), Range1.end()); EXPECT_EQ(Range1.begin() + 1, Range1.end()); OptionalStatistic S1; OptionalStatistic S2; extractCounters(Range1, S1, S2); EXPECT_EQ(S1.hasValue(), true); EXPECT_EQ(S2.hasValue(), false); } // Counter2 will be registered when it's first touched. Counter2++; { const auto Range = GetStatistics(); EXPECT_NE(Range.begin(), Range.end()); EXPECT_EQ(Range.begin() + 2, Range.end()); OptionalStatistic S1; OptionalStatistic S2; extractCounters(Range, S1, S2); EXPECT_EQ(S1.hasValue(), true); EXPECT_EQ(S2.hasValue(), true); EXPECT_EQ(S1->first, "Counter"); EXPECT_EQ(S1->second, 2u); EXPECT_EQ(S2->first, "Counter2"); EXPECT_EQ(S2->second, 1u); } #else Counter2++; auto &Range = GetStatistics(); EXPECT_EQ(Range.begin(), Range.end()); #endif #if LLVM_ENABLE_STATS // Check that resetting the statistics works correctly. // It should empty the list and zero the counters. ResetStatistics(); { auto &Range = GetStatistics(); EXPECT_EQ(Range.begin(), Range.end()); EXPECT_EQ(Counter, 0u); EXPECT_EQ(Counter2, 0u); OptionalStatistic S1; OptionalStatistic S2; extractCounters(Range, S1, S2); EXPECT_EQ(S1.hasValue(), false); EXPECT_EQ(S2.hasValue(), false); } // Now check that they successfully re-register and count. Counter++; Counter2++; { auto &Range = GetStatistics(); EXPECT_EQ(Range.begin() + 2, Range.end()); EXPECT_EQ(Counter, 1u); EXPECT_EQ(Counter2, 1u); OptionalStatistic S1; OptionalStatistic S2; extractCounters(Range, S1, S2); EXPECT_EQ(S1.hasValue(), true); EXPECT_EQ(S2.hasValue(), true); EXPECT_EQ(S1->first, "Counter"); EXPECT_EQ(S1->second, 1u); EXPECT_EQ(S2->first, "Counter2"); EXPECT_EQ(S2->second, 1u); } #else // No need to test the output ResetStatistics(), there's nothing to reset so // we can't tell if it failed anyway. ResetStatistics(); #endif } } // end anonymous namespace
23.0375
80
0.654097
URSec
1b5881ae327203883104b2fd286c345f447bc5e5
7,809
cpp
C++
graph/lca/codeforces/F1486F/Solution.cpp
ashtishad/problem-solving
5dfb71b04c2334c2cce53afd089ae1634b7e8100
[ "MIT" ]
17
2020-11-12T17:41:41.000Z
2021-10-01T13:19:42.000Z
graph/lca/codeforces/F1486F/Solution.cpp
ashtishad/problem-solving
5dfb71b04c2334c2cce53afd089ae1634b7e8100
[ "MIT" ]
15
2019-09-23T06:33:47.000Z
2020-06-04T18:55:45.000Z
graph/lca/codeforces/F1486F/Solution.cpp
ashtishad/problem-solving
5dfb71b04c2334c2cce53afd089ae1634b7e8100
[ "MIT" ]
16
2019-09-21T23:19:58.000Z
2020-06-18T07:26:39.000Z
// problem name: Pairs of Paths // problem link: https://codeforces.com/contest/1486/problem/F // contest link: https://codeforces.com/contest/1486 // time: (?) // author: reyad // other_tags: combinatorics, data structures, dynamic programming, trees, dfs // difficulty_level: expert #include <bits/stdc++.h> using namespace std; #define DEBUG 1 #define N 300030 #define K 20 /** * (o) parent of u * | * (u) parent of v1, v2, ... * / / \ \ * / / \ \ * / / \ \ * / / \ \ * / / \ \ * (v1) (v2) (v3) (v4) */ /** * @var * g is graph(stores adj list) */ vector<int> g[N]; /** * @var * pt stands for parent table, it is a sparse table * helps calculating lca * lev keeps track of level i.e. depth */ int pt[N][K], lev[N]; /** * @var * cnt the number of paths(given through query) of which a node 'u' is lca */ int lca_cnt[N] = {0}; /** * @var * ssc[v1] denotes the number of paths(given in query) which's lca is the parent of v1(in this * case, 'u') * `ssc` stands for `shared single edge count`(in this case edge u->v) * note: we don't need to keep track of 'u', cause v1 parent will always be 'u' in a rooted tree */ int ssc[N] = {0}; /** * @var * spc[u][{v1, v2}] denotes the number of paths(given in query) which's lca is the parent of {v1, * v2} where v1, v2 are siblings and in this case their parent is 'u'. * `spc` stands for `shared pair edge count(in this case, u->v1 and u->v2) * note: we need to keep track of 'u' for computational purposes, otherwise we could just generate * all pair combination of `u's` children and find out their shared edge count. */ map<pair<int, int>, int> spc[N]; /** * @var * ptc stands for pass through count * it calculates the number of paths are going through a node `v` where 'v' is not a lca of the * path. That means the paths will eventually be go through `v's` parent(which is in this case * 'u') */ int ptc[N] = {0}; /** * @var * a global vaiable which hold the answer */ long long ans; /** * @function * prepares pt i.e sparse table */ void dfs(int u, int par, int lv) { lev[u] = lv; pt[u][0] = par; for(int i=1; i<K; i++) { if(pt[u][i-1] != -1) { pt[u][i] = pt[pt[u][i-1]][i-1]; } } for(int v: g[u]) { if(v != par) { dfs(v, u, lv+1); } } } /** * @function * returns lca */ int lca(int u, int v) { if(lev[u] < lev[v]) { swap(u, v); } for(int i=K-1; i>=0; i--) { if((lev[u] - (1 << i)) >= lev[v]) { u = pt[u][i]; } } if(u == v) { return u; } for(int i=K-1; i>=0; i--) { if(pt[u][i] != -1 && pt[u][i] != pt[v][i]) { u = pt[u][i]; v = pt[v][i]; } } return pt[u][0]; } /** * @function * returns nth_ancestor of a given node */ int nth_ancestor(int u, int nth) { for(int i = K-1; i >= 0; i--) { if((nth >> i) & 1) { u = pt[u][i]; } } return u; } /** * @function * calculates no of pairs for a set of given n elements */ long long count_pair(int n) { return (long long)n * (n - 1) / 2; } /** * @function * processes pass through */ void process_pass_through(int u, int par) { for(auto v: g[u]) { if(v != par) { process_pass_through(v, u); ptc[u] += ptc[v]; } } } /** * @function * calculates final answer */ void calc_ans(int u, int par) { // calculate ans for children for(auto v: g[u]) { if(v != par) { calc_ans(v, u); } } // calc ans for type 1 i.e. same lca // first add all possible pairs for which 'u' is lca ans += count_pair(lca_cnt[u]); // now subtract all pairs which has shared edge u->v1, u->v2, ... for(auto v: g[u]) { if(v != par) { ans -= count_pair(ssc[v]); } } // now, if there are some paths which goes through both two edges such as {v1, v2} // those path's pair have been subtracted twice, one for v1 and another fot v2 // so, we must add those pairs for(auto sp: spc[u]) { ans += count_pair(sp.second); } // calc ans for type 2 i.e. different lca // first calculate total possible intersection // i.e. the number of pairs where one of the path has lca 'u' // and the other path pass through 'u' to its parent ans += (long long)ptc[u] * lca_cnt[u]; // now, some path those pass through 'u'(i.e. goes to u's parent o) // has shared edge with v1 with those paths which has lca at // 'u' and also goes through v1 // this is also tru for v2, v3, ... // so, we must get rid of them // for that, first we need to determine the no of paths those goes through 'v1->u', // 'v2->u', ... but does not have lca at 'u', i.e. goes to `u's` parent `o` // we may count it by subtracting ssc[v1] from ptc[v1] // i.e. ptc[v1] - ssc[v1] // ptc[v1] contains the number of paths that passes through v1 to u // ssc[v1] contains the number of paths that has lca at 'u' for(auto v: g[u]) { if(v != par) { int ptc_vuo = ptc[v] - ssc[v]; // now, count the pairs those shared v->u edge ans -= (long long)ssc[v] * ptc_vuo; } } } /** * @function * driver function @main */ int main() { #undef DEBUG int n; scanf("%d", &n); for(int i=1; i<n; i++) { int x, y; scanf("%d %d", &x, &y); g[x].push_back(y); g[y].push_back(x); } dfs(1, 0, 0); int m; scanf("%d", &m); for(int i=0; i<m; i++) { int x, y; scanf("%d %d", &x, &y); // here, 'u' is the lca int u = lca(x, y); lca_cnt[u]++; // determining the children through which the path (x, y) // meets at 'u' int v1 = -1, v2 = -1; if(x != u) { v1 = nth_ancestor(x, lev[x] - lev[u] - 1); } if(y != u) { v2 = nth_ancestor(y, lev[y] - lev[u] - 1); } #ifdef DEBUG printf("lca of %d, %d: %d\n", x, y, u); printf("v1, v2: %d, %d\n", v1, v2); #endif // increase shared single edge count for v1 if(v1 != -1) { ssc[v1]++; } // increase shared single edge count for v1 if(v2 != -1) { ssc[v2]++; } // if v1, v2 both are used for path, then // increase count for shared pair edge count for {v1, v2} if(v1 != -1 && v2 != -1) { if(v2 < v1) { swap(v1, v2); } spc[u][{v1, v2}]++; } // now, update pass through count // ptc at x and y should be increased by 1 // which will flow upward, you'll see in process_pass_through function ptc[x]++; ptc[y]++; // and therefore, ptc at 'u' i.e. lca must be reduced to 0 ptc[u] -= 2; // in this way, ptc only contains the no of paths // that must go through a node to it's parent } process_pass_through(1, 0); #ifdef DEBUG printf("lca debug\n"); for(int i=1; i<=n; i++) { printf("lca of %d: %d\n", i, lca_cnt[i]); } printf("\n"); printf("shared single edge count debug\n"); for(int i=1; i<=n; i++) { printf("ssc of %d: %d\n", i, ssc[i]); } printf("\n"); printf("pass through count debug\n"); for(int i=1; i<=n; i++) { printf("ptc of %d: %d\n", i, ptc[i]); } printf("\n"); #endif ans = 0; calc_ans(1, 0); printf("%lld\n", ans); }
25.772277
98
0.501985
ashtishad
1b59a32a7338a36285438156b7f8ac569a3929dc
5,639
cpp
C++
littleVulkanEngine/core/lve_framebuffer.cpp
ShaverJT/littleVulkanEngine
0418380916488a1f44072ff33eb15b7b6d9fe573
[ "MIT" ]
null
null
null
littleVulkanEngine/core/lve_framebuffer.cpp
ShaverJT/littleVulkanEngine
0418380916488a1f44072ff33eb15b7b6d9fe573
[ "MIT" ]
null
null
null
littleVulkanEngine/core/lve_framebuffer.cpp
ShaverJT/littleVulkanEngine
0418380916488a1f44072ff33eb15b7b6d9fe573
[ "MIT" ]
null
null
null
#include "lve_framebuffer.hpp" #include <array> #include <cassert> #include <vector> namespace lve { // Create a frame buffer attachment LveFramebuffer::LveFramebuffer( LveDevice& device, VkRenderPass renderPass, uint32_t width, uint32_t height, std::vector<AttachmentDescription>& attachmentDescriptions) : device{device}, width{width}, height{height} { attachments.resize(attachmentDescriptions.size()); for (int i = 0; i < attachmentDescriptions.size(); i++) { createAttachment( attachmentDescriptions[i].format, attachmentDescriptions[i].usage, &attachments[i]); } createFramebuffer(renderPass); } LveFramebuffer::~LveFramebuffer() { for (auto& attachment : attachments) { vkDestroyImageView(device.device(), attachment.view, nullptr); vkDestroyImage(device.device(), attachment.image, nullptr); vkFreeMemory(device.device(), attachment.memory, nullptr); vkDestroySampler(device.device(), attachment.sampler, nullptr); } vkDestroyFramebuffer(device.device(), framebuffer, nullptr); } // Override framebuffer setup from base class void LveFramebuffer::createFramebuffer(VkRenderPass renderPass) { assert(attachments.size() > 0 && "cannot create framebuffer with no attachments"); std::vector<VkImageView> views{}; for (auto& attachment : attachments) { views.push_back(attachment.view); } VkFramebufferCreateInfo framebufferInfo = {}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = renderPass; framebufferInfo.attachmentCount = static_cast<uint32_t>(views.size()); framebufferInfo.pAttachments = views.data(); framebufferInfo.width = width; framebufferInfo.height = height; framebufferInfo.layers = 1; if (vkCreateFramebuffer(device.device(), &framebufferInfo, nullptr, &framebuffer) != VK_SUCCESS) { throw std::runtime_error("failed to create framebuffer!"); } } void LveFramebuffer::createAttachment( VkFormat format, VkImageUsageFlags usage, FramebufferAttachment* attachment) { VkImageAspectFlags aspectMask = 0; VkImageLayout imageLayout; attachment->format = format; if (usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) { aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; } if (usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; } // Don't like this, should I be using an image array instead of multiple images? VkImageCreateInfo imageInfo = lve::initializers::imageCreateInfo(); imageInfo.imageType = VK_IMAGE_TYPE_2D; imageInfo.format = format; imageInfo.extent.width = width; imageInfo.extent.height = height; imageInfo.extent.depth = 1; imageInfo.mipLevels = 1; imageInfo.arrayLayers = 1; imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageInfo.usage = usage; imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; device.createImageWithInfo( imageInfo, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, attachment->image, attachment->memory); VkImageViewCreateInfo viewInfo = lve::initializers::imageViewCreateInfo(); viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; viewInfo.format = format; viewInfo.subresourceRange = {}; viewInfo.subresourceRange.aspectMask = aspectMask; viewInfo.subresourceRange.baseMipLevel = 0; viewInfo.subresourceRange.levelCount = 1; viewInfo.subresourceRange.baseArrayLayer = 0; viewInfo.subresourceRange.layerCount = 1; viewInfo.image = attachment->image; if (vkCreateImageView(device.device(), &viewInfo, nullptr, &attachment->view) != VK_SUCCESS) { throw std::runtime_error("failed to create texture image view!"); } if (usage & VK_IMAGE_USAGE_SAMPLED_BIT) { // Create sampler to sample from the attachment in the fragment shader VkSamplerCreateInfo samplerInfo{}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerInfo.magFilter = VK_FILTER_LINEAR; samplerInfo.minFilter = VK_FILTER_LINEAR; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerInfo.addressModeV = samplerInfo.addressModeU; samplerInfo.addressModeW = samplerInfo.addressModeU; samplerInfo.mipLodBias = 0.0f; samplerInfo.maxAnisotropy = 1.0f; samplerInfo.minLod = 0.0f; samplerInfo.maxLod = 1.0f; samplerInfo.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; if (vkCreateSampler(device.device(), &samplerInfo, nullptr, &attachment->sampler) != VK_SUCCESS) { throw std::runtime_error("failed to create sampler!"); } VkImageLayout samplerImageLayout = imageLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; attachment->descriptor.imageLayout = samplerImageLayout; attachment->descriptor.imageView = attachment->view; attachment->descriptor.sampler = attachment->sampler; } } void LveFramebuffer::Builder::addAttachment(VkFormat format, VkImageUsageFlags usage) { attachmentDescriptions.push_back({format, usage}); } std::unique_ptr<LveFramebuffer> LveFramebuffer::Builder::build( LveDevice& device, VkRenderPass renderPass) { return std::make_unique<LveFramebuffer>( device, renderPass, width, height, attachmentDescriptions); } } // namespace lve
36.380645
100
0.746764
ShaverJT
1b5a394d9fc3071cfbaad9ceb2818117be4bc995
13,850
cpp
C++
Source/ocdm/open_cdm_ext.cpp
goruklu/WPEFramework
99fc7dd0732dbdd9c332df7ceccb625436ab7a4e
[ "Apache-2.0" ]
null
null
null
Source/ocdm/open_cdm_ext.cpp
goruklu/WPEFramework
99fc7dd0732dbdd9c332df7ceccb625436ab7a4e
[ "Apache-2.0" ]
null
null
null
Source/ocdm/open_cdm_ext.cpp
goruklu/WPEFramework
99fc7dd0732dbdd9c332df7ceccb625436ab7a4e
[ "Apache-2.0" ]
null
null
null
#include "open_cdm_ext.h" #include "open_cdm_impl.h" #include "ExtendedOpenCDMSession.h" #define ASSERT_NOT_EXECUTED() \ { \ fprintf(stderr, "Error: didn't expect to use %s (%s:%d)!!\n", \ __PRETTY_FUNCTION__, __FILE__, __LINE__); \ abort(); \ } struct OpenCDMSystemExt { OpenCDMAccessor* m_accessor; std::string m_keySystem; }; struct ExtendedOpenCDMSessionExt : public ExtendedOpenCDMSession { public: ExtendedOpenCDMSessionExt() = delete; ExtendedOpenCDMSessionExt(const ExtendedOpenCDMSessionExt&) = delete; ExtendedOpenCDMSessionExt& operator=(ExtendedOpenCDMSessionExt&) = delete; public: ExtendedOpenCDMSessionExt(const string keySystem, OpenCDMAccessor* system, const uint8_t drmHeader[], uint32_t drmHeaderLength, OpenCDMSessionCallbacks* callbacks) : ExtendedOpenCDMSession(callbacks) , _userData(nullptr) , _realSession(nullptr) { OCDM::ISessionExt* realSession = nullptr; system->CreateSessionExt(keySystem, drmHeader, drmHeaderLength, &_sink, _sessionId, realSession); if (realSession == nullptr) { TRACE_L1("Creating a Session failed. %d", __LINE__); } else { OpenCDMSession::SessionExt(realSession); } _realSession = realSession; } virtual ~ExtendedOpenCDMSessionExt() { OpenCDMSession::SessionExt(nullptr); } uint32_t SessionIdExt() const { return _realSession->SessionIdExt(); } OCDM::OCDM_RESULT SetDrmHeader(const uint8_t drmHeader[], uint32_t drmHeaderLength) { return _realSession->SetDrmHeader(drmHeader, drmHeaderLength); } OCDM::OCDM_RESULT GetChallengeDataExt(uint8_t* challenge, uint32_t& challengeSize, uint32_t isLDL) { return _realSession->GetChallengeDataExt(challenge, challengeSize, isLDL); } OCDM::OCDM_RESULT CancelChallengeDataExt() { return _realSession->CancelChallengeDataExt(); } OCDM::OCDM_RESULT StoreLicenseData(const uint8_t licenseData[], uint32_t licenseDataSize, uint8_t* secureStopId) { return _realSession->StoreLicenseData(licenseData, licenseDataSize, secureStopId); } OCDM::OCDM_RESULT InitDecryptContextByKid() { return _realSession->InitDecryptContextByKid(); } OCDM::OCDM_RESULT CleanDecryptContext() { return _realSession->CleanDecryptContext(); } private: void* _userData; OCDM::ISessionExt* _realSession; }; struct OpenCDMSystemExt* opencdm_create_system_ext(struct OpenCDMAccessor* system, const char keySystem[]) { ASSERT(system != nullptr); OpenCDMAccessor* accessor = system; accessor->CreateSystemExt(keySystem); accessor->InitSystemExt(keySystem); OpenCDMSystemExt* output = new OpenCDMSystemExt; output->m_accessor = accessor; output->m_keySystem = keySystem; return output; } OpenCDMError opencdm_destruct_system_ext(struct OpenCDMSystemExt* system) { if (system != nullptr) { delete system; } return ERROR_NONE; } OpenCDMError opencdm_system_get_version(struct OpenCDMAccessor* system, const char keySystem[], char versionStr[]) { versionStr[0] = '\0'; std::string versionStdStr = system->GetVersionExt(keySystem); assert(versionStdStr.length() < 64); strcpy(versionStr, versionStdStr.c_str()); return ERROR_NONE; } OpenCDMError opencdm_system_ext_get_ldl_session_limit(OpenCDMSystemExt* system, uint32_t* ldlLimit) { OpenCDMAccessor* accessor = system->m_accessor; std::string keySystem = system->m_keySystem; *ldlLimit = accessor->GetLdlSessionLimit(keySystem); return ERROR_NONE; } bool opencdm_system_ext_is_secure_stop_enabled( struct OpenCDMSystemExt* system) { OpenCDMAccessor* accessor = system->m_accessor; return (OpenCDMError)accessor->IsSecureStopEnabled(system->m_keySystem); } OpenCDMError opencdm_system_ext_enable_secure_stop(struct OpenCDMSystemExt* system, uint32_t use) { OpenCDMAccessor* accessor = system->m_accessor; return (OpenCDMError)accessor->EnableSecureStop(system->m_keySystem, use != 0); } uint32_t opencdm_system_ext_reset_secure_stop(struct OpenCDMSystemExt* system) { OpenCDMAccessor* accessor = system->m_accessor; return (OpenCDMError)accessor->ResetSecureStops(system->m_keySystem); } OpenCDMError opencdm_system_ext_get_secure_stop_ids(OpenCDMSystemExt* system, uint8_t ids[], uint8_t idSize, uint32_t* count) { OpenCDMAccessor* accessor = system->m_accessor; return (OpenCDMError)accessor->GetSecureStopIds(system->m_keySystem, ids, idSize, *count); } OpenCDMError opencdm_system_ext_get_secure_stop(OpenCDMSystemExt* system, const uint8_t sessionID[], uint32_t sessionIDLength, uint8_t rawData[], uint16_t* rawSize) { OpenCDMAccessor* accessor = system->m_accessor; return (OpenCDMError)accessor->GetSecureStop( system->m_keySystem, sessionID, sessionIDLength, rawData, *rawSize); } OpenCDMError opencdm_system_ext_commit_secure_stop( OpenCDMSystemExt* system, const uint8_t sessionID[], uint32_t sessionIDLength, const uint8_t serverResponse[], uint32_t serverResponseLength) { OpenCDMAccessor* accessor = system->m_accessor; return (OpenCDMError)accessor->CommitSecureStop( system->m_keySystem, sessionID, sessionIDLength, serverResponse, serverResponseLength); } OpenCDMError opencdm_system_get_drm_time(struct OpenCDMAccessor* system, const char keySystem[], uint64_t* time) { OpenCDMError result(ERROR_INVALID_ACCESSOR); if (system != nullptr) { time_t cTime; cTime = system->GetDrmSystemTime(keySystem); *time = static_cast<uint64_t>(cTime); result = ERROR_NONE; } return (result); } uint32_t opencdm_session_get_session_id_ext(struct OpenCDMSession* opencdmSession) { ExtendedOpenCDMSessionExt* sessionExt = static_cast<ExtendedOpenCDMSessionExt*>(opencdmSession); return sessionExt->SessionIdExt(); } OpenCDMError opencdm_destruct_session_ext(OpenCDMSession* opencdmSession) { OpenCDMError result(OpenCDMError::ERROR_INVALID_SESSION); if (opencdmSession != nullptr) { result = OpenCDMError::ERROR_NONE; opencdmSession->Release(); } return (result); } OpenCDMError opencdm_session_set_drm_header(struct OpenCDMSession* opencdmSession, const uint8_t drmHeader[], uint32_t drmHeaderSize) { ExtendedOpenCDMSessionExt* sessionExt = static_cast<ExtendedOpenCDMSessionExt*>(opencdmSession); return (OpenCDMError)sessionExt->SetDrmHeader(drmHeader, drmHeaderSize); } OpenCDMError opencdm_session_get_challenge_data(struct OpenCDMSession* mOpenCDMSession, uint8_t* challenge, uint32_t* challengeSize, uint32_t isLDL) { ExtendedOpenCDMSessionExt* sessionExt = static_cast<ExtendedOpenCDMSessionExt*>(mOpenCDMSession); return (OpenCDMError)sessionExt->GetChallengeDataExt(challenge, *challengeSize, isLDL); } OpenCDMError opencdm_session_cancel_challenge_data(struct OpenCDMSession* mOpenCDMSession) { ExtendedOpenCDMSessionExt* sessionExt = static_cast<ExtendedOpenCDMSessionExt*>(mOpenCDMSession); return (OpenCDMError)sessionExt->CancelChallengeDataExt(); } OpenCDMError opencdm_session_store_license_data( struct OpenCDMSession* mOpenCDMSession, const uint8_t licenseData[], uint32_t licenseDataSize, uint8_t* secureStopId) { ExtendedOpenCDMSessionExt* sessionExt = static_cast<ExtendedOpenCDMSessionExt*>(mOpenCDMSession); return (OpenCDMError)sessionExt->StoreLicenseData( licenseData, licenseDataSize, secureStopId); } OpenCDMError opencdm_session_init_decrypt_context_by_kid( struct OpenCDMSession* mOpenCDMSession) { ExtendedOpenCDMSessionExt* sessionExt = static_cast<ExtendedOpenCDMSessionExt*>(mOpenCDMSession); OpenCDMError output = (OpenCDMError)sessionExt->InitDecryptContextByKid(); return output; } OpenCDMError opencdm_session_clean_decrypt_context(struct OpenCDMSession* mOpenCDMSession) { ExtendedOpenCDMSessionExt* sessionExt = static_cast<ExtendedOpenCDMSessionExt*>(mOpenCDMSession); return (OpenCDMError)sessionExt->CleanDecryptContext(); } OpenCDMError opencdm_delete_key_store(struct OpenCDMSystemExt* system) { OpenCDMError result(ERROR_INVALID_ACCESSOR); if (system != nullptr) { OpenCDMAccessor* accessor = system->m_accessor; std::string keySystem = system->m_keySystem; result = (OpenCDMError)accessor->DeleteKeyStore(keySystem); } return (result); } OpenCDMError opencdm_delete_secure_store(struct OpenCDMSystemExt* system) { OpenCDMError result(ERROR_INVALID_ACCESSOR); if (system != nullptr) { OpenCDMAccessor* accessor = system->m_accessor; std::string keySystem = system->m_keySystem; result = (OpenCDMError)accessor->DeleteSecureStore(keySystem); } return (result); } OpenCDMError opencdm_get_key_store_hash_ext(struct OpenCDMSystemExt* system, uint8_t keyStoreHash[], uint32_t keyStoreHashLength) { OpenCDMError result(ERROR_INVALID_ACCESSOR); if (system != nullptr) { OpenCDMAccessor* accessor = system->m_accessor; std::string keySystem = system->m_keySystem; result = (OpenCDMError)accessor->GetKeyStoreHash(keySystem, keyStoreHash, keyStoreHashLength); } return (result); } OpenCDMError opencdm_get_secure_store_hash_ext(struct OpenCDMSystemExt* system, uint8_t secureStoreHash[], uint32_t secureStoreHashLength) { OpenCDMError result(ERROR_INVALID_ACCESSOR); if (system != nullptr) { OpenCDMAccessor* accessor = system->m_accessor; std::string keySystem = system->m_keySystem; result = (OpenCDMError)accessor->GetSecureStoreHash( keySystem, secureStoreHash, secureStoreHashLength); } return (result); } OpenCDMError opencdm_system_teardown(struct OpenCDMSystemExt* system) { OpenCDMError result(ERROR_INVALID_ACCESSOR); if (system != nullptr) { OpenCDMAccessor* accessor = system->m_accessor; std::string keySystem = system->m_keySystem; result = (OpenCDMError)accessor->TeardownSystemExt(keySystem); } return (result); } /** * \brief Create DRM session (for actual decrypting of data). * * Creates an instance of \ref OpenCDMSession using initialization data. * \param keySystem DRM system to create the session for. * \param licenseType DRM specifc signed integer selecting License Type (e.g. "Limited Duration" for PlayReady). * \param initDataType Type of data passed in \ref initData. * \param initData Initialization data. * \param initDataLength Length (in bytes) of initialization data. * \param CDMData CDM data. * \param CDMDataLength Length (in bytes) of \ref CDMData. * \param session Output parameter that will contain pointer to instance of \ref OpenCDMSession. * \return Zero on success, non-zero on error. */ OpenCDMError opencdm_create_session(struct OpenCDMAccessor* system, const char keySystem[], const LicenseType licenseType, const char initDataType[], const uint8_t initData[], const uint16_t initDataLength, const uint8_t CDMData[], const uint16_t CDMDataLength, OpenCDMSessionCallbacks* callbacks, struct OpenCDMSession** session) { return opencdm_construct_session(system, keySystem, licenseType, initDataType, initData, initDataLength, CDMData, CDMDataLength, callbacks, nullptr, session); } /** * \brief Create DRM session (for actual decrypting of data). * * Creates an instance of \ref OpenCDMSession using initialization data. * \param keySystem DRM system to create the session for. * \param licenseType DRM specifc signed integer selecting License Type (e.g. * "Limited Duration" for PlayReady). * \param initDataType Type of data passed in \ref initData. * \param initData Initialization data. * \param initDataLength Length (in bytes) of initialization data. * \param CDMData CDM data. * \param CDMDataLength Length (in bytes) of \ref CDMData. * \param session Output parameter that will contain pointer to instance of \ref * OpenCDMSession. * \return Zero on success, non-zero on error. */ OpenCDMError opencdm_construct_session(struct OpenCDMAccessor* system, const char keySystem[], const LicenseType licenseType, const char initDataType[], const uint8_t initData[], const uint16_t initDataLength, const uint8_t CDMData[], const uint16_t CDMDataLength, OpenCDMSessionCallbacks* callbacks, void* userData, struct OpenCDMSession** session) { OpenCDMError result(ERROR_INVALID_ACCESSOR); // TODO: Since we are passing key system name anyway, not need for if here. if (strcmp(keySystem, "com.netflix.playready") != 0) { if (system != nullptr) { *session = new ExtendedOpenCDMSession( static_cast<OCDM::IAccessorOCDM*>(system), std::string(keySystem), std::string(initDataType), initData, initDataLength, CDMData, CDMDataLength, licenseType, callbacks, userData); result = (*session != nullptr ? OpenCDMError::ERROR_NONE : OpenCDMError::ERROR_INVALID_SESSION); } } else { if (system != nullptr) { *session = new ExtendedOpenCDMSessionExt(std::string(keySystem), system, initData, initDataLength, callbacks); result = OpenCDMError::ERROR_NONE; } } return (result); }
32.819905
122
0.719495
goruklu
1b5dc92d2be3674dcf5feb6b1fc933fcc7f88832
6,127
hpp
C++
indexer/succinct_trie_builder.hpp
EVi1b7wO/omim
1aafdb102a200149f7ad0cd3173aa7ca2cc32300
[ "Apache-2.0" ]
null
null
null
indexer/succinct_trie_builder.hpp
EVi1b7wO/omim
1aafdb102a200149f7ad0cd3173aa7ca2cc32300
[ "Apache-2.0" ]
null
null
null
indexer/succinct_trie_builder.hpp
EVi1b7wO/omim
1aafdb102a200149f7ad0cd3173aa7ca2cc32300
[ "Apache-2.0" ]
null
null
null
#pragma once #include "coding/bit_streams.hpp" #include "coding/byte_stream.hpp" #include "coding/huffman.hpp" #include "coding/reader.hpp" #include "coding/varint.hpp" #include "coding/writer.hpp" #include "base/buffer_vector.hpp" #include "base/checked_cast.hpp" #include "base/scope_guard.hpp" #include "base/string_utils.hpp" #include <algorithm> #include <functional> #include <vector> // Trie format: // -- Serialized Huffman encoding. // -- Topology of the trie built on Huffman-encoded input strings [2 bits per node, level-order representation]. // -- List of pairs (node id, offset). One pair per final node (i.e. a node where a string ends). // The lists of node ids and offsets are both non-decreasing and are delta-encoded with // varuints. // -- Values of final nodes in level-order. The values for final node |id| start at offset |offset| // if there is a pair (id, offset) in the list above. namespace trie { // Node is a temporary struct that is used to store the trie in memory // before it is converted to a succinct representation and put to disk. // It is rather verbose but hopefully is small enough to fit in memory. template <class TValueList> struct Node { // The left child is reached by 0, the right by 1. Node *l, *r; // A node is final if a key string ends in it. // In particular, all non-final nodes' valueLists are empty // and it is expected that a final node's valueList is non-empty. bool m_isFinal; // m_valueLists stores all the additional information that is related // to the key string which leads to this node. TValueList m_valueList; Node() : l(nullptr), r(nullptr), m_isFinal(false) {} }; template <class TNode, class TReader> TNode * AddToTrie(TNode * root, TReader & bitEncoding, uint32_t numBits) { ReaderSource<TReader> src(bitEncoding); // String size. ReadVarUint<uint32_t, ReaderSource<TReader>>(src); BitReader<ReaderSource<TReader>> bitReader(src); auto cur = root; for (uint32_t i = 0; i < numBits; ++i) { auto nxt = bitReader.Read(1) == 0 ? &cur->l : &cur->r; if (!*nxt) *nxt = new TNode(); cur = *nxt; } return cur; } template <class TNode> void DeleteTrie(TNode * root) { if (!root) return; DeleteTrie(root->l); DeleteTrie(root->r); delete root; } template <typename TNode> void WriteInLevelOrder(TNode * root, std::vector<TNode *> & levelOrder) { ASSERT(root, ()); levelOrder.push_back(root); size_t i = 0; while (i < levelOrder.size()) { TNode * cur = levelOrder[i++]; if (cur->l) levelOrder.push_back(cur->l); if (cur->r) levelOrder.push_back(cur->r); } } template <typename TWriter, typename TIter, typename TValueList> void BuildSuccinctTrie(TWriter & writer, TIter const beg, TIter const end) { using TrieChar = uint32_t; using TTrieString = buffer_vector<TrieChar, 32>; using TNode = Node<TValueList>; using TEntry = typename TIter::value_type; TNode * root = new TNode(); MY_SCOPE_GUARD(cleanup, std::bind(&DeleteTrie<TNode>, root)); TTrieString prevKey; TEntry prevEntry; std::vector<TEntry> entries; std::vector<strings::UniString> entryStrings; for (TIter it = beg; it != end; ++it) { TEntry entry = *it; if (it != beg && entry == prevEntry) continue; TrieChar const * const keyData = entry.GetKeyData(); TTrieString key(keyData, keyData + entry.GetKeySize()); using namespace std::rel_ops; // ">=" for keys. CHECK_GREATER_OR_EQUAL(key, prevKey, (key, prevKey)); entries.push_back(entry); entryStrings.push_back(strings::UniString(keyData, keyData + entry.GetKeySize())); prevKey.swap(key); prevEntry.Swap(entry); } coding::HuffmanCoder huffman; huffman.Init(entryStrings); huffman.WriteEncoding(writer); for (size_t i = 0; i < entries.size(); ++i) { TEntry const & entry = entries[i]; auto const & key = entryStrings[i]; std::vector<uint8_t> buf; MemWriter<std::vector<uint8_t>> memWriter(buf); uint32_t numBits = huffman.EncodeAndWrite(memWriter, key); MemReader bitEncoding(&buf[0], buf.size()); TNode * cur = AddToTrie(root, bitEncoding, numBits); cur->m_isFinal = true; cur->m_valueList.Append(entry.GetValue()); } std::vector<TNode *> levelOrder; WriteInLevelOrder(root, levelOrder); { // Trie topology. BitWriter<TWriter> bitWriter(writer); WriteVarUint(writer, levelOrder.size()); for (size_t i = 0; i < levelOrder.size(); ++i) { auto const & cur = levelOrder[i]; bitWriter.Write(cur->l ? 1 : 0, 1 /* numBits */); bitWriter.Write(cur->r ? 1 : 0, 1 /* numBits */); } } std::vector<uint32_t> finalNodeIds; std::vector<uint32_t> offsetTable; std::vector<uint8_t> valueBuf; MemWriter<std::vector<uint8_t>> valueWriter(valueBuf); for (size_t i = 0; i < levelOrder.size(); ++i) { TNode const * node = levelOrder[i]; if (!node->m_isFinal) continue; finalNodeIds.push_back(static_cast<uint32_t>(i)); offsetTable.push_back(base::asserted_cast<uint32_t>(valueWriter.Pos())); node->m_valueList.Dump(valueWriter); } WriteVarUint(writer, finalNodeIds.size()); for (size_t i = 0; i < finalNodeIds.size(); ++i) { if (i == 0) { WriteVarUint(writer, finalNodeIds[i]); WriteVarUint(writer, offsetTable[i]); } else { WriteVarUint(writer, finalNodeIds[i] - finalNodeIds[i - 1]); WriteVarUint(writer, offsetTable[i] - offsetTable[i - 1]); } } writer.Write(valueBuf.data(), valueBuf.size()); // todo(@pimenov): // 1. Investigate the possibility of path compression (short edges + lcp table). // 2. It is highly probable that valueList will be only a list of feature ids in our // future implementations of the search. // We can then dispose of offsetTable and store finalNodeIds as another bit vector. // Alternatively (and probably better), we can append a special symbol to all those // strings that have non-empty value lists. We can then get the leaf number // of a final node by doing rank0. } } // namespace trie
30.182266
114
0.674718
EVi1b7wO
1b5e2f15157dbfffe730e0d5fcecb1426320a7e8
207
cc
C++
tests/channel_test.cc
salahsheikh/mithril
020c9c6ad645e0a2767653cd158460ab1c6c13ca
[ "0BSD" ]
1
2021-08-01T16:31:11.000Z
2021-08-01T16:31:11.000Z
tests/channel_test.cc
salahsheikh/mithril
020c9c6ad645e0a2767653cd158460ab1c6c13ca
[ "0BSD" ]
null
null
null
tests/channel_test.cc
salahsheikh/mithril
020c9c6ad645e0a2767653cd158460ab1c6c13ca
[ "0BSD" ]
null
null
null
// // Created by ssheikh on 2021-02-20. // #include "test_channel.hh" #include <gtest/gtest.h> TEST(ChannelTest, Creation) { ASSERT_NO_THROW(test_channel()); ASSERT_FALSE(test_channel().pipeline()); }
15.923077
42
0.710145
salahsheikh
1b5feabdf120d5382073440d1817d0482f223c27
1,401
cpp
C++
Osiris/Hacks/Triggerbot.cpp
lukizel/Osiris
d611056daea2cdd06d79b0fb6d162b505ab2af6c
[ "MIT" ]
1
2020-02-02T22:49:30.000Z
2020-02-02T22:49:30.000Z
Osiris/Hacks/Triggerbot.cpp
lukizel/Osiris
d611056daea2cdd06d79b0fb6d162b505ab2af6c
[ "MIT" ]
null
null
null
Osiris/Hacks/Triggerbot.cpp
lukizel/Osiris
d611056daea2cdd06d79b0fb6d162b505ab2af6c
[ "MIT" ]
null
null
null
#include <Windows.h> #include "../Config.h" #include "../Interfaces.h" #include "../Memory.h" #include "../SDK/Entity.h" #include "../SDK/WeaponId.h" #include "Triggerbot.h" void Triggerbot::run(UserCmd* cmd) noexcept { if (config.triggerbot.enabled) { const auto localPlayer = interfaces.entityList->getEntity(interfaces.engine->getLocalPlayer()); const auto activeWeapon = interfaces.entityList->getEntityFromHandle(localPlayer->getProperty<int>("m_hActiveWeapon")); if (!activeWeapon || !activeWeapon->getProperty<int>("m_iClip1") || !getWeaponIndex(activeWeapon->getProperty<WeaponId>("m_iItemDefinitionIndex"))) return; static auto lastTime = memory.globalVars->realtime; auto now = memory.globalVars->realtime; if ((GetAsyncKeyState(config.triggerbot.key) || !config.triggerbot.onKey) && now - lastTime >= config.triggerbot.shotDelay / 1000.0f) { auto inCrosshair = localPlayer->getProperty<int>("m_bHasDefuser", 92); if (inCrosshair > 0 && inCrosshair <= 64) { auto target = interfaces.entityList->getEntity(inCrosshair); if (target->isEnemy() && !target->getProperty<bool>("m_bGunGameImmunity")) { cmd->buttons |= UserCmd::IN_ATTACK; } } lastTime = now; } } }
38.916667
127
0.621699
lukizel
1b6057a14be1d19e499aeaf64282d9e54da9e0eb
8,414
cpp
C++
samples/SerializeNodeSet/SerializeNodeSet.cpp
kidaa/xalan-c
bb666d0ab3d0a192410823e6857c203d83c27b16
[ "Apache-2.0" ]
null
null
null
samples/SerializeNodeSet/SerializeNodeSet.cpp
kidaa/xalan-c
bb666d0ab3d0a192410823e6857c203d83c27b16
[ "Apache-2.0" ]
1
2021-08-18T12:32:31.000Z
2021-08-18T12:32:31.000Z
samples/SerializeNodeSet/SerializeNodeSet.cpp
AaronNGray/xalan
6741bbdcb64a9d33df8bd7e21b558d66bb4292ec
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <xalanc/Include/PlatformDefinitions.hpp> #include <cassert> #if defined(XALAN_CLASSIC_IOSTREAMS) #include <iostream.h> #else #include <iostream> #endif #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/framework/LocalFileInputSource.hpp> #include <xalanc/XalanDOM/XalanDocument.hpp> #include <xalanc/XalanDOM/XalanElement.hpp> #include <xalanc/PlatformSupport/XalanOutputStreamPrintWriter.hpp> #include <xalanc/PlatformSupport/XalanStdOutputStream.hpp> #include <xalanc/XPath/NodeRefList.hpp> #include <xalanc/XPath/XObject.hpp> #include <xalanc/XPath/XPathEvaluator.hpp> #include <xalanc/XMLSupport/FormatterToXML.hpp> #include <xalanc/XMLSupport/FormatterTreeWalker.hpp> #include <xalanc/XMLSupport/XMLSupportInit.hpp> #include <xalanc/XalanSourceTree/XalanSourceTreeDOMSupport.hpp> #include <xalanc/XalanSourceTree/XalanSourceTreeInit.hpp> #include <xalanc/XalanSourceTree/XalanSourceTreeParserLiaison.hpp> int main( int argc, char* argv[]) { XALAN_USING_STD(cerr) XALAN_USING_STD(cout) XALAN_USING_STD(endl) int theResult = 0; if (argc != 4) { cerr << "Usage: SerializeNodeSet XMLFilePath Context XPathExpression" << endl; theResult = -1; } else { try { XALAN_USING_XERCES(XMLPlatformUtils) XALAN_USING_XALAN(XPathEvaluator) XMLPlatformUtils::Initialize(); XPathEvaluator::initialize(); { XALAN_USING_XERCES(LocalFileInputSource) XALAN_USING_XALAN(NodeRefList) XALAN_USING_XALAN(XalanDocument) XALAN_USING_XALAN(XalanDOMString) XALAN_USING_XALAN(XalanNode) XALAN_USING_XALAN(XalanSourceTreeInit) XALAN_USING_XALAN(XMLSupportInit) XALAN_USING_XALAN(XalanSourceTreeDOMSupport) XALAN_USING_XALAN(XalanSourceTreeParserLiaison) // Initialize the XalanSourceTree subsystem... XalanSourceTreeInit theSourceTreeInit; // Initialize the XMLSupport subsystem... XMLSupportInit theXMLSupportInit; // We'll use these to parse the XML file. XalanSourceTreeDOMSupport theDOMSupport; XalanSourceTreeParserLiaison theLiaison(theDOMSupport); // Hook the two together... theDOMSupport.setParserLiaison(&theLiaison); const XalanDOMString theFileName(argv[1]); // Create an input source that represents a local file... const LocalFileInputSource theInputSource(theFileName.c_str()); // Parse the document... XalanDocument* const theDocument = theLiaison.parseXMLStream(theInputSource); assert(theDocument != 0); XPathEvaluator theEvaluator; // OK, let's find the context node... XalanNode* const theContextNode = theEvaluator.selectSingleNode( theDOMSupport, theDocument, XalanDOMString(argv[2]).c_str(), theDocument->getDocumentElement()); if (theContextNode == 0) { cerr << "Error: No nodes matched the location path \"" << argv[2] << "\"." << endl << "Execution cannot continue." << endl << endl; } else { // OK, let's evaluate the expression... NodeRefList theResult; theEvaluator.selectNodeList( theResult, theDOMSupport, theContextNode, XalanDOMString(argv[3]).c_str(), theDocument->getDocumentElement()); const NodeRefList::size_type theLength = theResult.getLength(); if (theLength == 0) { cerr << endl << "Warning: No nodes matched the location path \"" << argv[3] << "\"." << endl << endl; } else { XALAN_USING_XALAN(XalanStdOutputStream) XALAN_USING_XALAN(XalanOutputStreamPrintWriter) XALAN_USING_XALAN(FormatterToXML) XALAN_USING_XALAN(FormatterTreeWalker) // OK, we're going to serialize the nodes that were // found. We should really check to make sure the // root (document) has not been selected, since we // really can't serialize a node list with the root. XalanStdOutputStream theStream(cout); XalanOutputStreamPrintWriter thePrintWriter(theStream); FormatterToXML theFormatter(thePrintWriter); FormatterTreeWalker theWalker(theFormatter); // Don't write a header... theFormatter.setShouldWriteXMLHeader(false); // It's required that we do this... theFormatter.startDocument(); // Traverse the subtree of the document rooted at // each node we've selected... for (NodeRefList::size_type i = 0; i < theLength; ++i) { const XalanNode* const theNode = theResult.item(i); assert(theNode != 0); const XalanNode::NodeType theNodeType = theNode->getNodeType(); if (theNodeType == XalanNode::DOCUMENT_NODE) { cerr << endl << "Warning: The root was selected. The root cannot be serialized." << endl; } else if (theNodeType == XalanNode::ATTRIBUTE_NODE) { cerr << endl << "Warning: An attribute or namespace node was selected. Attribute and namespace nodes cannot be serialized." << endl; } else { theWalker.traverseSubtree(theNode); } } // It's required that we do this... theFormatter.endDocument(); } } } XPathEvaluator::terminate(); XMLPlatformUtils::Terminate(); } catch(...) { cerr << "Exception caught!" << endl; theResult = -1; } } return theResult; }
34.342857
148
0.509151
kidaa
1b60d469822f483a8db9866d9a4f4768aee27f27
165
hpp
C++
Software/STM/APP/APP.hpp
ProrokWielki/Wooden-Clock
96226750ab4b679764b0b254d3c3c21deb658252
[ "MIT" ]
1
2018-12-14T07:05:33.000Z
2018-12-14T07:05:33.000Z
Software/STM/APP/APP.hpp
ProrokWielki/Wooden-Clock
96226750ab4b679764b0b254d3c3c21deb658252
[ "MIT" ]
null
null
null
Software/STM/APP/APP.hpp
ProrokWielki/Wooden-Clock
96226750ab4b679764b0b254d3c3c21deb658252
[ "MIT" ]
null
null
null
/** * APP.hpp * * Created on: 03-03-2019 * @author: Paweł Warzecha */ #ifndef APP_APP_HPP_ #define APP_APP_HPP_ void APP_init(); #endif /* APP_APP_HPP_ */
11.785714
27
0.648485
ProrokWielki
1b61aa4137545ca8c93d8f44d1abdf2f84555538
4,577
cpp
C++
Blaze/util/DeviceSelection.cpp
KidRigger/Blaze
7e76de71e2e22f3b5e8c4c2c50c58e6d205646c6
[ "MIT" ]
14
2019-12-10T03:57:03.000Z
2021-09-16T14:58:39.000Z
Blaze/util/DeviceSelection.cpp
kidrigger/Blaze
7e76de71e2e22f3b5e8c4c2c50c58e6d205646c6
[ "MIT" ]
null
null
null
Blaze/util/DeviceSelection.cpp
kidrigger/Blaze
7e76de71e2e22f3b5e8c4c2c50c58e6d205646c6
[ "MIT" ]
null
null
null
#include "DeviceSelection.hpp" #include <cstring> #include <set> #include <string> namespace blaze::util { QueueFamilyIndices getQueueFamilies(VkPhysicalDevice device, VkSurfaceKHR surface) { QueueFamilyIndices indices; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data()); int i = 0; for (const auto& queueFamily : queueFamilies) { if (queueFamily.queueCount > 0 && queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { indices.graphicsIndex = i; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport); if (queueFamily.queueCount > 0 && presentSupport) { indices.presentIndex = i; } i++; } return indices; } SwapchainSupportDetails getSwapchainSupport(VkPhysicalDevice device, VkSurfaceKHR surface) { SwapchainSupportDetails details; vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities); uint32_t formatCount = 0; vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr); details.formats.resize(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data()); uint32_t presentModesCount = 0; vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModesCount, nullptr); details.presentModes.resize(presentModesCount); vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModesCount, details.presentModes.data()); return details; } bool checkDeviceExtensionSupport(VkPhysicalDevice device, const std::vector<const char*>& deviceExtensions) { uint32_t extensionCount = 0; vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> availableExtensions(extensionCount); vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data()); std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); for (const auto& extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } return requiredExtensions.empty(); } bool isDeviceSuitable(VkPhysicalDevice device, VkSurfaceKHR surface, const std::vector<const char*>& deviceExtensions) { VkPhysicalDeviceProperties properties; vkGetPhysicalDeviceProperties(device, &properties); if (properties.deviceType != VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) { return false; } QueueFamilyIndices queueFamilyIndices = getQueueFamilies(device, surface); bool extensionsSupported = checkDeviceExtensionSupport(device, deviceExtensions); bool swapchainAdequate = false; if (extensionsSupported) { auto swapchainSupport = getSwapchainSupport(device, surface); swapchainAdequate = !swapchainSupport.formats.empty() && !swapchainSupport.presentModes.empty(); } VkPhysicalDeviceFeatures physicalDeviceFeatures; vkGetPhysicalDeviceFeatures(device, &physicalDeviceFeatures); return queueFamilyIndices.complete() && extensionsSupported && swapchainAdequate && physicalDeviceFeatures.samplerAnisotropy && physicalDeviceFeatures.shaderSampledImageArrayDynamicIndexing && physicalDeviceFeatures.depthClamp; } bool checkValidationLayerSupport(const std::vector<const char*>& validationLayers) { uint32_t layerCount = 0; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<VkLayerProperties> availableLayers(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); for (const char* layerName : validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { return false; } } return true; } VkFormat findSupportedFormat(VkPhysicalDevice device, const std::vector<VkFormat>& candidates, VkImageTiling tiling, VkFormatFeatureFlags features) { for (VkFormat format : candidates) { VkFormatProperties props; vkGetPhysicalDeviceFormatProperties(device, format, &props); if (tiling == VK_IMAGE_TILING_LINEAR && (props.linearTilingFeatures & features) == features) { return format; } else if (tiling == VK_IMAGE_TILING_OPTIMAL && (props.optimalTilingFeatures & features) == features) { return format; } } return VK_FORMAT_UNDEFINED; } } // namespace blaze::util
30.311258
118
0.790037
KidRigger
1b671e8b627016f099f4e4c11703727192bf3ef5
916
hpp
C++
include/libp2p/protocol/kademlia/impl/response_handler.hpp
GaroRobe/cpp-libp2p
533d4a7f9981cb944ecb337f3ce4f98ea48b65f3
[ "Apache-2.0", "MIT" ]
135
2020-06-13T08:57:36.000Z
2022-03-27T05:26:11.000Z
include/libp2p/protocol/kademlia/impl/response_handler.hpp
igor-egorov/cpp-libp2p
7c9d83bf0760a5f653d86ddbb00645414c61d4fc
[ "Apache-2.0", "MIT" ]
41
2020-06-12T15:45:05.000Z
2022-03-07T23:10:33.000Z
include/libp2p/protocol/kademlia/impl/response_handler.hpp
igor-egorov/cpp-libp2p
7c9d83bf0760a5f653d86ddbb00645414c61d4fc
[ "Apache-2.0", "MIT" ]
43
2020-06-15T10:12:45.000Z
2022-03-21T03:04:50.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef LIBP2P_PROTOCOL_KADEMLIA_RESPONSEHANDLER #define LIBP2P_PROTOCOL_KADEMLIA_RESPONSEHANDLER #include <libp2p/outcome/outcome.hpp> #include <libp2p/protocol/kademlia/message.hpp> namespace libp2p::protocol::kademlia { class Session; class ResponseHandler { public: virtual ~ResponseHandler() = default; /// @returns timeout for response waiting virtual Time responseTimeout() const = 0; /// Check if message is accorded to request virtual bool match(const Message &msg) const = 0; /// Tries to apply @param res, @returns true if success virtual void onResult(const std::shared_ptr<Session> &session, outcome::result<Message> msg_res) = 0; }; } // namespace libp2p::protocol::kademlia #endif // LIBP2P_PROTOCOL_KADEMLIA_RESPONSEHANDLER
26.941176
66
0.717249
GaroRobe
1b68ae9e91b47b8260fe6fa6336bcf6244b7507f
935
hpp
C++
include/RED4ext/Scripting/Natives/Generated/scn/AnimationRid.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/scn/AnimationRid.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/scn/AnimationRid.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Handle.hpp> #include <RED4ext/Scripting/Natives/Generated/Transform.hpp> #include <RED4ext/Scripting/Natives/Generated/scn/RidTag.hpp> namespace RED4ext { namespace anim { struct Animation; } namespace anim { struct EventsContainer; } namespace scn { struct AnimationRid { static constexpr const char* NAME = "scnAnimationRid"; static constexpr const char* ALIAS = NAME; scn::RidTag tag; // 00 Handle<anim::Animation> animation; // 10 Handle<anim::EventsContainer> events; // 20 bool motionExtracted; // 30 uint8_t unk31[0x40 - 0x31]; // 31 Transform offset; // 40 uint32_t bonesCount; // 60 int32_t trajectoryBoneIndex; // 64 uint8_t unk68[0x80 - 0x68]; // 68 }; RED4EXT_ASSERT_SIZE(AnimationRid, 0x80); } // namespace scn } // namespace RED4ext
26.714286
61
0.717647
jackhumbert
1b69cf139691097c20b87e749b80cc247c4f001e
2,509
cpp
C++
cod_mov_buscalocal.cpp
BrunoBertozzi/tcc-2021
d1a1837d28f7507598e96818ade50671a1050efc
[ "MIT" ]
null
null
null
cod_mov_buscalocal.cpp
BrunoBertozzi/tcc-2021
d1a1837d28f7507598e96818ade50671a1050efc
[ "MIT" ]
null
null
null
cod_mov_buscalocal.cpp
BrunoBertozzi/tcc-2021
d1a1837d28f7507598e96818ade50671a1050efc
[ "MIT" ]
null
null
null
/*************************************************************** * Nome: Bruno Oswaldo Bertozzi Oliveira * File name: main.cpp * Data 17/02/2021 * ***************************************************************/ #include <iostream> #include <vector> using namespace std; //HEADERS #include "head_struct.h" #include "head_mov_buscalocal.h" void realocate(int id_item, int id_bin1, int id_bin2, vector<Tbin> &bins, const vector<Titem> itens, const int **matriz_adj, const int quant_itens){ for(unsigned int i = 0; i <bins[id_bin1].items.size(); i++){ //procura o item a ser excluido if(bins[id_bin1].items[i] == id_item){ erase_int(bins[id_bin1].items, i); //exclui o item do bim break; } } bins[id_bin1].pesoUsado -= itens[id_item-1].peso; bins[id_bin1].pesoLivre += itens[id_item-1].peso; for(const auto& iten: bins[id_bin1].items){ if(matriz_adj[iten-1][id_item-1] == 1 || matriz_adj[id_item-1][iten-1] == 1){ bins[id_bin1].numConflitos -= 2; } } bins[id_bin2].items.push_back(id_item); bins[id_bin2].pesoUsado += itens[id_item-1].peso; bins[id_bin2].pesoLivre -= itens[id_item-1].peso; for(const auto& iten: bins[id_bin2].items){ if(iten != id_item) if(matriz_adj[iten-1][id_item-1] == 1 || matriz_adj[id_item-1][iten-1] == 1) bins[id_bin2].numConflitos += 2; } } void erase_int (vector<int> &v, int pos){ if(!v.empty()){ std::swap(v[pos], v.back()); v.pop_back(); } } void Swap (const int id_item1, const int id_item2, const int id_bin1, const int id_bin2, vector<Tbin> &bins, const vector<Titem> itens, const int **matriz_adj, const int quant_itens){ realocate(id_item1, id_bin1, id_bin2, bins, itens, (const int**)matriz_adj, quant_itens); realocate(id_item2, id_bin2, id_bin1, bins, itens, (const int**)matriz_adj, quant_itens); } void Swap2_1(const int id_item1, const int id_item2, const int id_item3, const int id_bin1, const int id_bin2, vector<Tbin> &bins, const vector<Titem> itens, const int **matriz_adj, const int quant_itens){ realocate(id_item1, id_bin1, id_bin2, bins, itens, (const int**)matriz_adj, quant_itens); realocate(id_item2, id_bin1, id_bin2, bins, itens, (const int**)matriz_adj, quant_itens); realocate(id_item3, id_bin2, id_bin1, bins, itens, (const int**)matriz_adj, quant_itens); }
40.467742
206
0.606616
BrunoBertozzi
1b6ae3a78896427c9272d64148ab978f975f9725
9,062
cpp
C++
WinLib/Net/Ftp.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
67
2018-03-02T10:50:02.000Z
2022-03-23T18:20:29.000Z
WinLib/Net/Ftp.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
null
null
null
WinLib/Net/Ftp.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
9
2018-03-01T16:38:28.000Z
2021-03-02T16:17:09.000Z
//---------------------------------- // (c) Reliable Software 2003 - 2008 //---------------------------------- #include <WinLibBase.h> #include "Ftp.h" #include <File/File.h> #include <File/Vpath.h> #include <Ex/Error.h> namespace Ftp { bool Handle::GetFile ( char const * remotePath, char const * localPath, ::File::Attributes attr, Internet::Callback * callback) { bool success = ::FtpGetFile (ToNative (), remotePath, localPath, FALSE, // fail if exists attr.ToNative (), FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_HYPERLINK, reinterpret_cast<DWORD_PTR> (callback)) != FALSE; if (!success && callback != 0 && Win::GetError () == ERROR_IO_PENDING) { Win::ClearError (); success = true; } return success; } bool Handle::PutFile ( char const * localPath, char const * remotePath, Internet::Callback * callback) { bool success = ::FtpPutFile (ToNative (), localPath, remotePath, FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_HYPERLINK, reinterpret_cast<DWORD_PTR> (callback)) != FALSE; if (!success && callback != 0 && Win::GetError () == ERROR_IO_PENDING) { Win::ClearError (); success = true; } return success; } std::string Handle::GetCurrentDirectory () { std::string buf; buf.reserve (MAX_PATH); unsigned long bufLen = buf.capacity (); if (::FtpGetCurrentDirectory (ToNative (), writable_string (buf), &bufLen) == FALSE) buf.clear (); return buf; } bool Handle::Exists (std::string const & path, bool & isFolder) const { bool exists = true; try { Ftp::FileSeq seq (*this, path); if (seq.AtEnd ()) return false; isFolder = seq.IsFolder (); } catch (...) { exists = false; } return exists; } class CWDUser { public: CWDUser (Ftp::Handle hFtp) : _hFtp (hFtp) { // Remember current directory on the server _currentWorkingDirectory = _hFtp.GetCurrentDirectory (); if (_currentWorkingDirectory.empty ()) { LastSysErr lastSysErr; if (lastSysErr.IsInternetError ()) { LastInternetError lastInternetError; throw Win::InternalException ("Cannot retrieve the current directory on the specified FTP sever.", lastInternetError.Text ().c_str ()); } else { throw Win::Exception ("Cannot retrieve the current directory on the specified FTP sever."); } } } ~CWDUser () { // Return server to its previous current directory _hFtp.SetCurrentDirectory (_currentWorkingDirectory.c_str ()); } private: std::string _currentWorkingDirectory; Ftp::Handle _hFtp; }; ::File::Size Handle::GetFileSize () const { unsigned long high, low; low = ::FtpGetFileSize (ToNative (), &high); return ::File::Size (low, high); } void Handle::MaterializeFolderPath (std::string const & path) { CWDUser cwd (*this); ::File::Vpath workPath(::File::Vpath::UseFwdSlash); if (path.empty() || path [0] == '/') { if (!SetCurrentDirectory ("/")) { LastSysErr lastSysErr; if (lastSysErr.IsInternetError ()) { LastInternetError lastInternetError; throw Win::InternalException ("Cannot change the current directory on the specified FTP sever.", lastInternetError.Text ().c_str ()); } else { throw Win::Exception ("Cannot change the current directory on the specified FTP sever."); } } } if (!path.empty()) { if (path [0] == '/') { if (path.length() > 1) workPath.SetPath (&path [1]); } else { workPath.SetPath (path); } } for (Vpath::const_iterator iter = workPath.begin (); iter != workPath.end (); ++iter) { std::string const & segment = *iter; if (SetCurrentDirectory (segment.c_str ())) { // Changed current directory successfully continue; } else { // Cannot change current directory on the server if (CreateDirectory (segment.c_str ())) { // Created folder on the server if (SetCurrentDirectory (segment.c_str ())) continue; // Changed current directory to the newly created folder } LastSysErr lastSysErr; if (lastSysErr.IsInternetError ()) { LastInternetError lastInternetError; throw Win::InternalException ("Cannot create folder path on the specified FTP sever.", lastInternetError.Text ().c_str ()); } else { throw Win::Exception ("Cannot create folder path on the specified FTP sever.", path.c_str ()); } } } // Done - the current directory on the server is set to the materialized path // Destructor of CWDUser will bring server to its previous current directory. } Ftp::AutoHandle Session::Connect (Internet::Protocol protocol, Internet::Callback * callback) { INTERNET_PORT port; DWORD service; switch (protocol) { case Internet::FTP: port = INTERNET_DEFAULT_FTP_PORT; service = INTERNET_SERVICE_FTP; break; case Internet::HTTP: port = INTERNET_DEFAULT_HTTP_PORT; service = INTERNET_SERVICE_HTTP; break; case Internet::GOPHER: port = INTERNET_DEFAULT_GOPHER_PORT; service = INTERNET_SERVICE_GOPHER; break; default: throw Win::Exception("Unknown internet protocol."); }; Ftp::AutoHandle h (::InternetConnect ( _internetHandle.ToNative (), _server.c_str (), port, _user.c_str (), _passwd.c_str (), service, 0, reinterpret_cast<DWORD_PTR> (callback))); if (!h.IsNull()) return h; if (callback != 0 && Win::GetError() == ERROR_IO_PENDING) return h; // empty // Real error unsigned long error = 0; char buffer[256]; unsigned long len = sizeof(buffer) - 1; ::InternetGetLastResponseInfo(&error, buffer, &len); throw Internet::Exception("Cannot connect to FTP server", buffer, error); } // Couldn't figure out how to work it asynchronously FileSeq::FileSeq (Ftp::Handle hFtp, std::string const & pattern, Internet::Callback * callback) : _atEnd (false), _callback (callback), _handle (::FtpFindFirstFile ( hFtp.ToNative (), pattern.c_str (), &_data, 0, reinterpret_cast<DWORD_PTR> (callback))) { Assert (callback == 0); // not tested if (_handle == INVALID_HANDLE_VALUE || _handle.IsNull ()) { LastSysErr lastSysErr; if (_callback != 0 && lastSysErr.IsIOPending ()) return; if (lastSysErr.IsFileNotFound () || lastSysErr.IsNoMoreFiles ()) { _atEnd = true; Win::ClearError (); } else if (lastSysErr.IsInternetError ()) { LastInternetError lastError; throw Win::Exception ("FTP: Cannot list files.", lastError.Text ().c_str ()); } else { throw Internet::Exception ("FTP: Cannot list files.", pattern.c_str ()); } } SkipPseudoDirs (); } void FileSeq::SkipPseudoDirs () { // skip "." and ".." directories while (!AtEnd () && IsFolder () && IsDots ()) Advance (); } void FileSeq::Advance () { _atEnd = !::InternetFindNextFile (_handle.ToNative (), &_data); if (_atEnd) Win::ClearError (); } char const * FileSeq::GetName () const { Assert (!_atEnd); return _data.cFileName; } RemoteFile::RemoteFile (Ftp::Handle hFtp, char const * path, Access access, Internet::Callback * callback) : _h (::FtpOpenFile (hFtp.ToNative (), path, access, FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_HYPERLINK, reinterpret_cast<DWORD_PTR> (callback))) { Assert (callback == 0); // not tested if (_h.IsNull ()) { LastSysErr lastSysErr; if (lastSysErr.IsInternetError ()) { LastInternetError lastError; throw Win::Exception ("Cannot open file.", lastError.Text ().c_str ()); } else { throw Internet::Exception ("Cannot open file.", path); } } // Note: only one file can be opened in an FTP session } FileReadable::FileReadable (Ftp::Handle ftpSessionHandle, char const * path, Internet::Callback * callback) : Ftp::RemoteFile (ftpSessionHandle, path, Ftp::RemoteFile::GenericRead, callback) {} FileWritable::FileWritable (Ftp::Handle ftpSessionHandle, char const * path, Internet::Callback * callback) : Ftp::RemoteFile (ftpSessionHandle, path, Ftp::RemoteFile::GenericWrite, callback) {} File::File (Ftp::Handle ftpSessionHandle, std::string const & path) : _ftpSessionHandle (ftpSessionHandle), _path (path) { } void File::OpenRead () { _file.reset (new Ftp::FileReadable (_ftpSessionHandle, _path.c_str ())); } void File::OpenWrite () { _file.reset (new Ftp::FileWritable (_ftpSessionHandle, _path.c_str ())); } ::File::Size File::GetSize () { Assume (_file.get () == 0, "Ftp::File::GetSize called during transfer"); Ftp::FileReadable file (_ftpSessionHandle, _path.c_str ()); return file.GetSize (); } void File::Commit () { _file.reset (); // close file } void File::Abort () { _file.reset (); // close file _ftpSessionHandle.DeleteFile (_path.c_str ()); } }
25.24234
108
0.633194
BartoszMilewski
1b6e199d8c7f0262e324e46d47b750a3451b5475
1,760
hpp
C++
modules/arm_plugin/src/opset/conv_arm.hpp
IvanNovoselov/openvino_contrib
5fe8fd389d57972bd470b447c606138679ab5d49
[ "Apache-2.0" ]
null
null
null
modules/arm_plugin/src/opset/conv_arm.hpp
IvanNovoselov/openvino_contrib
5fe8fd389d57972bd470b447c606138679ab5d49
[ "Apache-2.0" ]
null
null
null
modules/arm_plugin/src/opset/conv_arm.hpp
IvanNovoselov/openvino_contrib
5fe8fd389d57972bd470b447c606138679ab5d49
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2020-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include "ngraph/coordinate_diff.hpp" #include "ngraph_opset.hpp" #include "utils.hpp" namespace ArmPlugin { namespace opset { class ArmConvolution : public Convolution { public: static constexpr ngraph::NodeTypeInfo type_info{"ArmConvolution", 0}; const ngraph::NodeTypeInfo& get_type_info() const override { return type_info; } ArmConvolution() = default; ~ArmConvolution() override; ArmConvolution(const ngraph::Output<ngraph::Node>& data_batch, const ngraph::Output<ngraph::Node>& filters, const ngraph::Strides& strides, const ngraph::CoordinateDiff& pads_begin, const ngraph::CoordinateDiff& pads_end, const ngraph::Strides& dilations, const ngraph::op::PadType& auto_pad, const ActivationInfo& activation); ArmConvolution(const ngraph::Output<ngraph::Node>& data_batch, const ngraph::Output<ngraph::Node>& filters, const ngraph::Output<ngraph::Node>& bias, const ngraph::Strides& strides, const ngraph::CoordinateDiff& pads_begin, const ngraph::CoordinateDiff& pads_end, const ngraph::Strides& dilations, const ngraph::op::PadType& auto_pad, const ActivationInfo& activation); std::shared_ptr<ngraph::Node> clone_with_new_inputs(const ngraph::OutputVector& new_args) const override; const ActivationInfo& get_info() const { return m_info; } private: ActivationInfo m_info; }; } // namespace opset } // namespace ArmPlugin
36.666667
109
0.639205
IvanNovoselov
1b6e8fbbe46298adbb9c798be4be16a286cc21d9
1,347
cpp
C++
src/render/weapon_action_renderer.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
null
null
null
src/render/weapon_action_renderer.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
null
null
null
src/render/weapon_action_renderer.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
1
2020-09-22T15:41:51.000Z
2020-09-22T15:41:51.000Z
#include "render/weapon_action_renderer.h" #include "platform/auto_id.h" #include "core/i_inventory_component.h" namespace render { WeaponActionRenderer::WeaponActionRenderer( int32_t Id ) : ActionRenderer( Id ) { } void WeaponActionRenderer::Init( const Actor& actor ) { Opt<Weapon> weapon = actor.Get<IInventoryComponent>()->GetSelectedWeapon(); if ( !weapon.IsValid() ) { return; } SpriteCollection const& Sprites = mRenderableRepo( actor.GetId() ); Sprite const& Spr = Sprites( weapon->GetId() ); if( Spr.IsValid() ) { mSecsToEnd = Spr.GetSecsToEnd(); } } void WeaponActionRenderer::FillRenderableSprites( const Actor& actor, IRenderableComponent const& renderableC, RenderableSprites_t& renderableSprites ) { Opt<Weapon> weapon = actor.Get<IInventoryComponent>()->GetSelectedWeapon(); if ( !weapon.IsValid() ) { return; } SpriteCollection const& Sprites = mRenderableRepo( actor.GetId() ); Sprite const& Spr = Sprites( weapon->GetId() ); if( Spr.IsValid() ) { SpritePhase const& Phase = Spr( ( int32_t )GetState() ); glm::vec4 col = GetCloakColor( actor ) * GetColor( actor ); renderableSprites.push_back( RenderableSprite( &actor, &renderableC, weapon->GetId(), &Spr, &Phase, col ) ); } } } // namespace render
29.282609
151
0.668894
MrPepperoni
1b757a93cb8ed2c608f0b2ee63f6ffeb6f99afcb
1,034
cpp
C++
3Tree/872. Leaf-Similar Trees.cpp
lingqtan/myLeetcode
54cc538b640660c0d64420442466af4df2ed0225
[ "Apache-2.0" ]
null
null
null
3Tree/872. Leaf-Similar Trees.cpp
lingqtan/myLeetcode
54cc538b640660c0d64420442466af4df2ed0225
[ "Apache-2.0" ]
null
null
null
3Tree/872. Leaf-Similar Trees.cpp
lingqtan/myLeetcode
54cc538b640660c0d64420442466af4df2ed0225
[ "Apache-2.0" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { vector<int> leaves1, leaves2; bool isLeaf(TreeNode* root) { return root && root->left == NULL && root->right == NULL; } void traverse(TreeNode* root, int k) { if (root == NULL) return; traverse(root->left, k); traverse(root->right, k); if (isLeaf(root)) { if (k == 1) leaves1.push_back(root->val); else leaves2.push_back(root->val); return; } } public: bool leafSimilar(TreeNode* root1, TreeNode* root2) { leaves1.clear(), leaves2.clear(); traverse(root1, 1); traverse(root2, 2); if (leaves1.size() != leaves2.size()) return false; for (int i = 0; i < leaves1.size(); i++) { if (leaves1[i] != leaves2[i]) return false; } return true; } };
28.722222
65
0.526112
lingqtan
1b77bd1c6d61aef315137df8767934be474b95ab
5,499
cc
C++
src/loki/height_action.cc
komoot/valhalla
8f2010b0724257f1c3511d4b6d5e9b0f7bddec2f
[ "MIT" ]
null
null
null
src/loki/height_action.cc
komoot/valhalla
8f2010b0724257f1c3511d4b6d5e9b0f7bddec2f
[ "MIT" ]
null
null
null
src/loki/height_action.cc
komoot/valhalla
8f2010b0724257f1c3511d4b6d5e9b0f7bddec2f
[ "MIT" ]
1
2021-07-20T23:07:11.000Z
2021-07-20T23:07:11.000Z
#include <functional> #include <string> #include <stdexcept> #include <vector> #include <unordered_map> #include <unordered_set> #include <cstdint> #include <cmath> #include <sstream> #include <boost/property_tree/ptree.hpp> #include "midgard/logging.h" #include "baldr/location.h" #include "midgard/util.h" #include "midgard/encoded.h" #include "baldr/rapidjson_utils.h" #include "loki/worker.h" using namespace valhalla; using namespace valhalla::tyr; using namespace valhalla::midgard; using namespace valhalla::baldr; using namespace valhalla::skadi; namespace { json::ArrayPtr serialize_range_height(const std::vector<float>& ranges, const std::vector<double>& heights, const double no_data_value) { auto array = json::array({}); //for each posting auto range = ranges.cbegin(); for (const auto height : heights) { auto element = json::array({json::fp_t{*range,0}}); if(height == no_data_value) element->push_back(nullptr); else { element->push_back({json::fp_t{height, 0}}); } array->push_back(element); ++range; } return array; } json::ArrayPtr serialize_height(const std::vector<double>& heights, const double no_data_value) { auto array = json::array({}); for (const auto height : heights) { //add all heights's to an array if(height == no_data_value) array->push_back(nullptr); else array->push_back({json::fp_t{height, 0}}); } return array; } json::ArrayPtr serialize_shape(const std::vector<PointLL>& shape) { auto array = json::array({}); for(const auto& p : shape) { array->emplace_back(json::map({ {"lon", json::fp_t{p.first, 6}}, {"lat", json::fp_t{p.second, 6}} })); } return array; } } namespace valhalla { namespace loki { void loki_worker_t::init_height(rapidjson::Document& request) { //get some parameters range = GetFromRapidJson(request, "/range", false); auto input_shape = GetOptionalFromRapidJson<rapidjson::Value::Array>(request, "/shape"); encoded_polyline = GetOptionalFromRapidJson<std::string>(request, "/encoded_polyline"); auto resample_distance = GetOptionalFromRapidJson<double>(request, "/resample_distance"); //we require shape or encoded polyline but we dont know which at first try { //uncompressed shape if (input_shape) { for (const auto& latlng : *input_shape) shape.push_back(baldr::Location::FromRapidJson(latlng).latlng_); }//compressed shape else if (encoded_polyline) { shape = midgard::decode<std::vector<midgard::PointLL> >(*encoded_polyline); }//no shape else throw valhalla_exception_t{310}; //not enough shape if (shape.size() < 1) throw valhalla_exception_t{311}; } catch (...) { throw valhalla_exception_t{312}; } //resample the shape bool resampled = false; if(resample_distance) { if(*resample_distance < min_resample) throw valhalla_exception_t{313, " " + std::to_string(min_resample) + " meters"}; if(shape.size() > 1) { //resample the shape but make sure to keep the first and last shapepoint auto last = shape.back(); shape = midgard::resample_spherical_polyline(shape, *resample_distance); shape.emplace_back(std::move(last)); //reencode it for display if they sent it encoded if(encoded_polyline) *encoded_polyline = midgard::encode(shape); resampled = true; } } //there are limits though if(shape.size() > max_elevation_shape) { throw valhalla_exception_t{314, " (" + std::to_string(shape.size()) + (resampled ? " after resampling" : "") + "). The limit is " + std::to_string(max_elevation_shape)}; } } /* example height with range response: { "shape": [ {"lat": 40.712433, "lon": -76.504913}, {"lat": 40.712276, "lon": -76.605263} ], "range_height": [ [0,303], [8467,275], [25380,198] ] } */ json::MapPtr loki_worker_t::height(rapidjson::Document& request) { init_height(request); //get the elevation of each posting std::vector<double> heights = sample.get_all(shape); if (!healthcheck) valhalla::midgard::logging::Log("sample_count::" + std::to_string(shape.size()), " [ANALYTICS] "); boost::optional<std::string> id = GetOptionalFromRapidJson<std::string>(request, "/id"); auto json = json::map({}); //get the distances between the postings if (range) { std::vector<float> ranges; ranges.reserve(shape.size()); ranges.emplace_back(0); for(auto point = std::next(shape.cbegin()); point != shape.cend(); ++point) ranges.emplace_back(ranges.back() + point->Distance(*std::prev(point))); json = json::map({ {"range_height", serialize_range_height(ranges, heights, sample.get_no_data_value())} }); }//just the postings else { json = json::map({ {"height", serialize_height(heights, sample.get_no_data_value())} }); } //send back the shape as well if(encoded_polyline) json->emplace("encoded_polyline", *encoded_polyline); else json->emplace("shape", serialize_shape(shape)); if (id) json->emplace("id", *id); return json; } } }
32.538462
139
0.62375
komoot
1b81d2f15f00c4d4d5ade047bfd05a56b3986011
2,788
hpp
C++
src/calc/specs/parse.hpp
Globidev/reverse-calculator
239849bccfccedd504876dad4e5978bf51bf678c
[ "MIT" ]
null
null
null
src/calc/specs/parse.hpp
Globidev/reverse-calculator
239849bccfccedd504876dad4e5978bf51bf678c
[ "MIT" ]
null
null
null
src/calc/specs/parse.hpp
Globidev/reverse-calculator
239849bccfccedd504876dad4e5978bf51bf678c
[ "MIT" ]
null
null
null
#pragma once #include "calc/buttons.hpp" #include "calc/specs/detail/spec.hpp" #include "calc/specs/detail/parse.hpp" namespace calc::buttons::specs { namespace hana = boost::hana; namespace qi = boost::spirit::qi; using detail::spec; // Concept map for parsing buttons // All buttons MUST implement it {*1} template <class It, class Skipper> const auto parse_spec_map = detail::make_parse_spec_map<It, Skipper>( // rhs bound buttons will be prefix parsed followed by a number_t parser // {*d2} spec <add> = "+", spec <sub> = "-", spec <mul> = "x", spec <div> = "/", spec <power> = "^", spec <append> = ":", spec <meta_add> = "[+]", // stateful buttons will be parsed using a custom given parser rule // {*d3} spec <replace> = detail::parse_replace<It, Skipper>, spec <store> = detail::parse_store<It, Skipper>, // non rhs bound / non stateful buttons will be parsed literally // {*d4} spec <rotate_left> = "shift<", spec <rotate_right> = "shift>", spec <erase_last> = "<<", spec <opposite> = "+/-", spec <reverse> = "reverse", spec <sum> = "sum", spec <mirror> = "mirror", spec <inv10> = "inv10" ); template <class It, class... Ts> constexpr auto make_grammar(hana::basic_type<It>, hana::basic_type<std::variant<Ts...>>) { using skipper_t = qi::blank_type; using synthetized_rule_t = qi::rule<It, std::variant<Ts...>(), skipper_t>; // {*1} static_assert( hana::all_of( hana::make_tuple(hana::type_c<Ts>...), [](auto type) { return type ^hana::in^ parse_spec_map<It, skipper_t>; } ), "Missing parser spec for button" ); // Variadic alternative of all the button rules return synthetized_rule_t { ( parse_spec_map<It, skipper_t>[hana::type_c<Ts>] | ... ) }; } constexpr auto parse = [](auto input) -> std::optional<button_v> { static const auto grammar = make_grammar( hana::decltype_(std::begin(input)), hana::type_c<button_v> ); button_v buttonv; auto begin_it = std::begin(input), end_it = std::end(input); auto parsed = qi::phrase_parse( begin_it, end_it, grammar, qi::blank, buttonv ); if (parsed && begin_it == end_it) return buttonv; else return std::nullopt; }; }
30.304348
94
0.511478
Globidev
1b83f0dbde37057a5ebd674f60ef0fda926d83d6
7,893
cpp
C++
src/lib/tls/tls_text_policy.cpp
ssd71/botan
d6b5b4a31af102bd6405e4f381e2ea21d2317a1c
[ "BSD-2-Clause" ]
56
2019-04-25T19:06:11.000Z
2022-03-25T20:26:25.000Z
src/lib/tls/tls_text_policy.cpp
Liujiunan/botan
b36dea33cb5c0552642a3ce0218b9bafd6f3e43b
[ "BSD-2-Clause" ]
184
2019-04-24T18:20:08.000Z
2022-03-22T18:56:45.000Z
src/lib/tls/tls_text_policy.cpp
Liujiunan/botan
b36dea33cb5c0552642a3ce0218b9bafd6f3e43b
[ "BSD-2-Clause" ]
34
2019-04-03T15:21:16.000Z
2022-03-20T04:26:53.000Z
/* * Text-Based TLS Policy * (C) 2016,2017 Jack Lloyd * 2017 Harry Reimann, Rohde & Schwarz Cybersecurity * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/tls_policy.h> #include <botan/exceptn.h> #include <botan/parsing.h> #include <sstream> namespace Botan { namespace TLS { std::vector<std::string> Text_Policy::allowed_ciphers() const { return get_list("ciphers", Policy::allowed_ciphers()); } std::vector<std::string> Text_Policy::allowed_signature_hashes() const { return get_list("signature_hashes", Policy::allowed_signature_hashes()); } std::vector<std::string> Text_Policy::allowed_macs() const { return get_list("macs", Policy::allowed_macs()); } std::vector<std::string> Text_Policy::allowed_key_exchange_methods() const { return get_list("key_exchange_methods", Policy::allowed_key_exchange_methods()); } std::vector<std::string> Text_Policy::allowed_signature_methods() const { return get_list("signature_methods", Policy::allowed_signature_methods()); } bool Text_Policy::use_ecc_point_compression() const { return get_bool("use_ecc_point_compression", Policy::use_ecc_point_compression()); } bool Text_Policy::allow_tls10() const { return get_bool("allow_tls10", Policy::allow_tls10()); } bool Text_Policy::allow_tls11() const { return get_bool("allow_tls11", Policy::allow_tls11()); } bool Text_Policy::allow_tls12() const { return get_bool("allow_tls12", Policy::allow_tls12()); } bool Text_Policy::allow_dtls10() const { return get_bool("allow_dtls10", Policy::allow_dtls10()); } bool Text_Policy::allow_dtls12() const { return get_bool("allow_dtls12", Policy::allow_dtls12()); } bool Text_Policy::allow_insecure_renegotiation() const { return get_bool("allow_insecure_renegotiation", Policy::allow_insecure_renegotiation()); } bool Text_Policy::include_time_in_hello_random() const { return get_bool("include_time_in_hello_random", Policy::include_time_in_hello_random()); } bool Text_Policy::require_client_certificate_authentication() const { return get_bool("require_client_certificate_authentication", Policy::require_client_certificate_authentication()); } bool Text_Policy::allow_client_initiated_renegotiation() const { return get_bool("allow_client_initiated_renegotiation", Policy::allow_client_initiated_renegotiation()); } bool Text_Policy::allow_server_initiated_renegotiation() const { return get_bool("allow_server_initiated_renegotiation", Policy::allow_server_initiated_renegotiation()); } bool Text_Policy::server_uses_own_ciphersuite_preferences() const { return get_bool("server_uses_own_ciphersuite_preferences", Policy::server_uses_own_ciphersuite_preferences()); } bool Text_Policy::negotiate_encrypt_then_mac() const { return get_bool("negotiate_encrypt_then_mac", Policy::negotiate_encrypt_then_mac()); } bool Text_Policy::support_cert_status_message() const { return get_bool("support_cert_status_message", Policy::support_cert_status_message()); } std::vector<Group_Params> Text_Policy::key_exchange_groups() const { std::string group_str = get_str("key_exchange_groups"); if(group_str.empty()) { // fall back to previously used name group_str = get_str("groups"); } if(group_str.empty()) { return Policy::key_exchange_groups(); } std::vector<Group_Params> groups; for(std::string group_name : split_on(group_str, ' ')) { Group_Params group_id = group_param_from_string(group_name); if(group_id == Group_Params::NONE) { try { size_t consumed = 0; unsigned long ll_id = std::stoul(group_name, &consumed, 0); if(consumed != group_name.size()) continue; // some other cruft const uint16_t id = static_cast<uint16_t>(ll_id); if(id != ll_id) continue; // integer too large group_id = static_cast<Group_Params>(id); } catch(...) { continue; } } if(group_id != Group_Params::NONE) groups.push_back(group_id); } return groups; } size_t Text_Policy::minimum_ecdh_group_size() const { return get_len("minimum_ecdh_group_size", Policy::minimum_ecdh_group_size()); } size_t Text_Policy::minimum_ecdsa_group_size() const { return get_len("minimum_ecdsa_group_size", Policy::minimum_ecdsa_group_size()); } size_t Text_Policy::minimum_dh_group_size() const { return get_len("minimum_dh_group_size", Policy::minimum_dh_group_size()); } size_t Text_Policy::minimum_rsa_bits() const { return get_len("minimum_rsa_bits", Policy::minimum_rsa_bits()); } size_t Text_Policy::minimum_signature_strength() const { return get_len("minimum_signature_strength", Policy::minimum_signature_strength()); } size_t Text_Policy::dtls_default_mtu() const { return get_len("dtls_default_mtu", Policy::dtls_default_mtu()); } size_t Text_Policy::dtls_initial_timeout() const { return get_len("dtls_initial_timeout", Policy::dtls_initial_timeout()); } size_t Text_Policy::dtls_maximum_timeout() const { return get_len("dtls_maximum_timeout", Policy::dtls_maximum_timeout()); } bool Text_Policy::require_cert_revocation_info() const { return get_bool("require_cert_revocation_info", Policy::require_cert_revocation_info()); } bool Text_Policy::hide_unknown_users() const { return get_bool("hide_unknown_users", Policy::hide_unknown_users()); } uint32_t Text_Policy::session_ticket_lifetime() const { return static_cast<uint32_t>(get_len("session_ticket_lifetime", Policy::session_ticket_lifetime())); } bool Text_Policy::send_fallback_scsv(Protocol_Version version) const { return get_bool("send_fallback_scsv", false) ? Policy::send_fallback_scsv(version) : false; } std::vector<uint16_t> Text_Policy::srtp_profiles() const { std::vector<uint16_t> r; for(std::string p : get_list("srtp_profiles", std::vector<std::string>())) { r.push_back(to_uint16(p)); } return r; } void Text_Policy::set(const std::string& k, const std::string& v) { m_kv[k] = v; } Text_Policy::Text_Policy(const std::string& s) { std::istringstream iss(s); m_kv = read_cfg(iss); } Text_Policy::Text_Policy(std::istream& in) : m_kv(read_cfg(in)) {} std::vector<std::string> Text_Policy::get_list(const std::string& key, const std::vector<std::string>& def) const { const std::string v = get_str(key); if(v.empty()) { return def; } return split_on(v, ' '); } size_t Text_Policy::get_len(const std::string& key, size_t def) const { const std::string v = get_str(key); if(v.empty()) { return def; } return to_u32bit(v); } bool Text_Policy::get_bool(const std::string& key, bool def) const { const std::string v = get_str(key); if(v.empty()) { return def; } if(v == "true" || v == "True") { return true; } else if(v == "false" || v == "False") { return false; } else { throw Decoding_Error("Invalid boolean '" + v + "'"); } } std::string Text_Policy::get_str(const std::string& key, const std::string& def) const { auto i = m_kv.find(key); if(i == m_kv.end()) { return def; } return i->second; } bool Text_Policy::set_value(const std::string& key, const std::string& val, bool overwrite) { auto i = m_kv.find(key); if(overwrite == false && i != m_kv.end()) return false; m_kv.insert(i, std::make_pair(key, val)); return true; } } }
24.665625
117
0.677816
ssd71
1b842d9930a65bd56daabe81c8eb38320dedd3d8
4,530
hpp
C++
src/Video/ParticleSystemRenderer.hpp
Chainsawkitten/Deathcap
37ed5afccd3113d34612d89c6e6508e8da9a0d7f
[ "MIT" ]
3
2017-09-08T06:05:10.000Z
2017-10-28T04:22:20.000Z
src/Video/ParticleSystemRenderer.hpp
Chainsawkitten/Deathcap
37ed5afccd3113d34612d89c6e6508e8da9a0d7f
[ "MIT" ]
894
2017-08-30T09:57:28.000Z
2018-01-30T12:35:38.000Z
src/Video/ParticleSystemRenderer.hpp
Chainsawkitten/LargeGameProjectEngine
37ed5afccd3113d34612d89c6e6508e8da9a0d7f
[ "MIT" ]
1
2020-11-06T23:59:58.000Z
2020-11-06T23:59:58.000Z
#pragma once #include <glm/glm.hpp> #include <Video/Shader/Shader.hpp> #include <Video/Shader/ShaderProgram.hpp> #include "linking.hpp" namespace Particles { struct ParticlePos { float x; float y; float z; float w; }; struct ParticleVelocity { float vx; float vy; float vz; float life; }; struct ParticleColor { float cx; float cy; float cz; float ca; }; } struct ParticleModelMatrix { glm::mat4 m = glm::mat4(1); }; namespace Video { class Texture2D; /// Represents a particle system that can be simulated and rendered. class ParticleSystemRenderer { public: struct EmitterSettings { /// Number of particles. int nr_particles = 1024; /// Position. glm::vec3 worldPos; /// Size. glm::vec2 size; /// Life (in seconds). float life; /// Lifetime (in seconds). float lifetime = 10; /// Initial velocity. glm::vec3 velocity; /// Start, mid and end of life alpha of particle. glm::vec3 alpha; /// Color of the particle. glm::vec3 color = glm::vec3(0, 0, 0); /// Fire rate. float rate = 1.0f; /// Texture index (for the texture atlas, left to right, top to bottom indexing) int textureIndex = 0; /// Multiply velocity. float velocityMultiplier = 10.0f; /// Gives spread to the particles int spread = 1; /// Used to give random velocity to particles at all time. glm::vec3 randomVec = glm::vec3(1, 1, 1); /// Scale. float scale = 1.0f; /// Particle mass. float mass = 0.01f; /// Alpha control float alpha_control = 1.0f; /// Nr Of new particles per emitt, max is 32. int nr_new_particles = 31; }; EmitterSettings emitterSettings; /// Constructor. VIDEO_API ParticleSystemRenderer(); /// Construct a particle system with a given number of particles. /** * @param count Number of particles. */ VIDEO_API ParticleSystemRenderer(int count); /// Destructor. VIDEO_API ~ParticleSystemRenderer(); /// Initialize the particle system. VIDEO_API void Init(); /// Creates storage buffers for particles. VIDEO_API void CreateStorageBuffers(); /// Particles are sent to the compute shader and we compute their the new positions/velocities. /** * @param dt Deltatime. * @param settings Emitter settings. */ VIDEO_API void Update(float dt, EmitterSettings settings); ///Render the particles. /** * @param textureAtlas The texture atlas for the particles. * @param textureAtlasRows how many rows in texture atlas. * @param viewMatrix The camera's view matrix. * @param projectionMatrix The camera's projection matrix. * @param settings Settings for the emitter. */ VIDEO_API void Draw(Texture2D* textureAtlas, unsigned int textureAtlasRows, const glm::mat4& viewMatrix, const glm::mat4& ProjectionMatrix, ParticleSystemRenderer::EmitterSettings settings); private: Video::ShaderProgram* computeShaderProgram; Video::ShaderProgram* shaderProgram; int WORK_GROUP_SIZE = 128; unsigned int nr_particles = 1024 * 32; glm::vec2 particleShootIndex = glm::vec2(0, 30); int nr_new_particles = 31; float rate = 1000.0f; float delta_time = 0.0f; Particles::ParticlePos* points; Particles::ParticleVelocity* vels; Particles::ParticleColor* col; ParticleModelMatrix* rots; glm::mat4 rotMat; float timer = 0.0f; GLuint posSSbo; GLuint velSSbo; GLuint colSSbo; GLuint mmSSbo; GLuint m_glDrawVAO; }; } // namespace Video
28.490566
202
0.524945
Chainsawkitten
1b865f7dde3bde77fda558c517c8ef7c43725de7
4,641
cpp
C++
core/src/database/query/QueryBuilder.cpp
kiroboio/lib-ledger-core
b2def5f4aed64dcb43b1f4ecaa66103a40f02adc
[ "MIT" ]
2
2019-06-25T15:10:40.000Z
2019-07-08T12:22:37.000Z
core/src/database/query/QueryBuilder.cpp
kiroboio/lib-ledger-core
b2def5f4aed64dcb43b1f4ecaa66103a40f02adc
[ "MIT" ]
1
2020-02-28T17:12:42.000Z
2020-02-28T17:12:42.000Z
core/src/database/query/QueryBuilder.cpp
kiroboio/lib-ledger-core
b2def5f4aed64dcb43b1f4ecaa66103a40f02adc
[ "MIT" ]
3
2018-03-07T14:17:41.000Z
2018-11-28T10:50:10.000Z
/* * * QueryBuilder * ledger-core * * Created by Pierre Pollastri on 27/06/2017. * * The MIT License (MIT) * * Copyright (c) 2016 Ledger * * 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 "QueryBuilder.h" #include <fmt/format.h> namespace ledger { namespace core { soci::details::prepare_temp_type QueryBuilder::execute(soci::session &sql) { std::stringstream query; query << "SELECT " << _keys << " FROM " << _table<< " AS " << _output; if (!_outerJoins.empty()) { for (auto &outerJoin : _outerJoins) { if (outerJoin.nonEmpty()) { query << " LEFT OUTER JOIN " << std::get<0>(outerJoin.getValue()) << " ON " << std::get<1>(outerJoin.getValue()); } } } if (_filter) { query << " WHERE "; std::string sFilter = _filter->getHead()->toString(); query << sFilter; } if (_order.size() > 0) { query << " ORDER BY "; for (auto it = _order.begin(); it != _order.end(); it++) { auto& order = *it; query << std::get<0>(order) << (std::get<1>(order) ? " DESC" : " ASC"); if (std::distance(it, _order.end()) > 1) { query << ","; } } } if (_limit.nonEmpty()) { query << " LIMIT " << _limit.getValue(); } if (_offset.nonEmpty()) { query << " OFFSET " << _offset.getValue(); } soci::details::prepare_temp_type statement = sql.prepare << query.str(); if (_filter) { _filter->getHead()->bindValue(statement); } return statement; } QueryBuilder &QueryBuilder::select(const std::string &keys) { _keys = std::move(keys); return *this; } QueryBuilder &QueryBuilder::select(std::string &&keys) { _keys = keys; return *this; } QueryBuilder &QueryBuilder::from(const std::string &table) { _table = std::move(table); return *this; } QueryBuilder &QueryBuilder::from(std::string &&table) { _table = table; return *this; } QueryBuilder &QueryBuilder::to(const std::string &output) { _output = std::move(output); return *this; } QueryBuilder &QueryBuilder::to(std::string &&output) { _output = output; return *this; } QueryBuilder &QueryBuilder::where(const std::shared_ptr<api::QueryFilter> &filter) { _filter = std::dynamic_pointer_cast<QueryFilter>(filter); return *this; } QueryBuilder &QueryBuilder::order(std::string &&keys, bool&& descending) { _order.push_back(std::move(std::make_tuple(keys, descending))); return *this; } QueryBuilder &QueryBuilder::limit(int32_t limit) { _limit = limit; return *this; } QueryBuilder &QueryBuilder::offset(int32_t offset) { _offset = offset; return *this; } QueryBuilder& QueryBuilder::outerJoin(const std::string &table, const std::string &condition) { _outerJoins.emplace_back(Option<LeftOuterJoin>(std::make_tuple(table, condition))); return *this; } } }
33.875912
137
0.552467
kiroboio
1b8775c26055a97b1d4d5828fe060ecfebe6131c
1,910
cpp
C++
acm/hdu/5428.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
17
2016-01-01T12:57:25.000Z
2022-02-06T09:55:12.000Z
acm/hdu/5428.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
null
null
null
acm/hdu/5428.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
8
2018-12-27T01:31:49.000Z
2022-02-06T09:55:12.000Z
#include <iostream> #include <sstream> #include <ios> #include <iomanip> #include <functional> #include <algorithm> #include <vector> #include <string> #include <list> #include <queue> #include <deque> #include <stack> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <climits> #include <cctype> using namespace std; #define XINF INT_MAX #define INF 0x3FFFFFFF #define MP(X,Y) make_pair(X,Y) #define PB(X) push_back(X) #define REP(X,N) for(int X=0;X<N;X++) #define REP2(X,L,R) for(int X=L;X<=R;X++) #define DEP(X,R,L) for(int X=R;X>=L;X--) #define CLR(A,X) memset(A,X,sizeof(A)) #define IT iterator typedef long long ll; typedef pair<int,int> PII; typedef vector<PII> VII; typedef vector<int> VI; //const int MAXN = 10010; ll a[101]; ll b[101]; int T; bool yns[101]; int main(){ cin>>T; while(T--){ int n; cin>>n; REP(i,n)cin>>a[i]; CLR(yns,0); ll min1 = INF,min2 = INF;int t; REP(i,n) { for(int j = 2;j*j<=a[i];j++) {//int ta = a[i]; while(a[i]%j==0&&a[i]) { a[i]/=j; if(min1>j) min1 = j; else if(min2>j)min2 = j; else break; } } if(min1>a[i]&&a[i] != 1) min1 = a[i]; else if(min2>a[i]&&a[i] != 1)min2 = a[i]; //cout<<"i"<<i<<min1<<" "<<min2<<endl; } /*{ if(a[i]%j == 0) {b[i] = j; yns[i] = 1;break;} } if(yns[i] == 0&&b[i] != 1)b[i] = a[i]; if(b[i] == 1)b[i] = INF; } REP(i,n) {if(min1>b[i]){min1 = b[i];t = i;}} b[t] = INF; REP(i,n) {if(min2>b[i]){min2 = b[i];}}*/ if(min1 == INF||min2 == INF)cout<<"-1"<<endl; else cout<<min1*min2<<endl; } }
24.487179
61
0.474869
xiaohuihuigh
b8442fd96bdc271ff7513cc8231d9cef817d018c
2,433
cpp
C++
src/Graphics/Texture.cpp
Szczurox/OpenGL-3D-Engine
255757681fdbcac015c43104eaf0b03af54d412e
[ "MIT" ]
null
null
null
src/Graphics/Texture.cpp
Szczurox/OpenGL-3D-Engine
255757681fdbcac015c43104eaf0b03af54d412e
[ "MIT" ]
null
null
null
src/Graphics/Texture.cpp
Szczurox/OpenGL-3D-Engine
255757681fdbcac015c43104eaf0b03af54d412e
[ "MIT" ]
null
null
null
#include"Texture.hpp" // Constructor that generates Texture Texture::Texture(const char* image, const char* texType, GLuint slot) { type = texType; // image width, height and number of color channels int widthImg, heightImg, numColCh; // Flips the image so it appears right side up stbi_set_flip_vertically_on_load(true); // Reads the image from a file and stores it in bytes unsigned char* bytes = stbi_load(image, &widthImg, &heightImg, &numColCh, 0); // Generates a texture object glGenTextures(1, &ID); // Assigns the texture to a Texture Unit glActiveTexture(GL_TEXTURE0 + slot); unit = slot; glBindTexture(GL_TEXTURE_2D, ID); // Configures algorithm used to make the image smaller or bigger glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Configures the way the texture repeats glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Automatically recognizes texture type and assigns the image to the Texture object switch (numColCh) { case 4: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, widthImg, heightImg, 0, GL_RGBA, GL_UNSIGNED_BYTE, bytes); break; case 3: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, widthImg, heightImg, 0, GL_RGB, GL_UNSIGNED_BYTE, bytes); break; case 1: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, widthImg, heightImg, 0, GL_RED, GL_UNSIGNED_BYTE, bytes); break; default: throw std::invalid_argument("Texture type recognition failed"); } // Generates MipMaps glGenerateMipmap(GL_TEXTURE_2D); // Deletes the image data stbi_image_free(bytes); // Unbinds the OpenGL Texture object so that it can't accidentally be modified glBindTexture(GL_TEXTURE_2D, 0); } // Assigns a texture unit to a texture void Texture::texUnit(Shader& shader, const char* uniform, GLuint unit) { // Gets the location of the uniform GLuint texUni = glGetUniformLocation(shader.ID, uniform); // Activates shader (required before uniform can be accessed)) shader.Activate(); // Sets the value of the uniform glUniform1i(texUni, unit); } // Binds Texture void Texture::Bind() { glActiveTexture(GL_TEXTURE0 + unit); glBindTexture(GL_TEXTURE_2D, ID); } // Unbinds Texture void Texture::Unbind() { glBindTexture(GL_TEXTURE_2D, 0); } // Deletes Texture void Texture::Delete() { glDeleteTextures(1, &ID); }
31.192308
101
0.755446
Szczurox
b8458daf57b83b66d5177234b6a65ed33ba70366
660
cpp
C++
POSN Camp1/whereru.cpp
ParamaaS/ParamaaS-Cpp-code-
a6c78151defe38d1460cde2b005a67be5a1d092d
[ "MIT" ]
null
null
null
POSN Camp1/whereru.cpp
ParamaaS/ParamaaS-Cpp-code-
a6c78151defe38d1460cde2b005a67be5a1d092d
[ "MIT" ]
null
null
null
POSN Camp1/whereru.cpp
ParamaaS/ParamaaS-Cpp-code-
a6c78151defe38d1460cde2b005a67be5a1d092d
[ "MIT" ]
null
null
null
#include<stdio.h> #include<string.h> int n,m,c,c2,idx; char s[25][25]; main() { scanf("%d%d",&m,&n); for(c=0;c<m;c++) { scanf("%s",s[c]); } for(c=0;c<m;c++) { for(c2=0;c2<n-2;c2++) { if(s[c][c2]=='s'||s[c][c2]=='S') { if(s[c][c2+1]=='k'||s[c][c2+1]=='K') { if(s[c][c2+2]=='s'||s[c][c2+2]=='S') { idx++; } } } } } for(c=0;c<n;c++) { for(c2=0;c2<m-2;c2++) { if(s[c2][c]=='s'||s[c2][c]=='S') { if(s[c2+1][c]=='k'||s[c2+1][c]=='K') { if(s[c2+2][c]=='s'||s[c2+2][c]=='S') { idx++; } } } } } printf("%d",idx); }
14.347826
42
0.321212
ParamaaS
b8475ea4e466b1e3c5a9991b684da83b9e89f5b0
2,220
hpp
C++
include/codegen/include/System/Text/EncoderExceptionFallback.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Text/EncoderExceptionFallback.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Text/EncoderExceptionFallback.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:42 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Text.EncoderFallback #include "System/Text/EncoderFallback.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Text namespace System::Text { // Forward declaring type: EncoderFallbackBuffer class EncoderFallbackBuffer; } // Completed forward declares // Type namespace: System.Text namespace System::Text { // Autogenerated type: System.Text.EncoderExceptionFallback class EncoderExceptionFallback : public System::Text::EncoderFallback { public: // public System.Void .ctor() // Offset: 0x12D7F74 // Implemented from: System.Text.EncoderFallback // Base method: System.Void EncoderFallback::.ctor() // Base method: System.Void Object::.ctor() static EncoderExceptionFallback* New_ctor(); // public override System.Text.EncoderFallbackBuffer CreateFallbackBuffer() // Offset: 0x12D7F84 // Implemented from: System.Text.EncoderFallback // Base method: System.Text.EncoderFallbackBuffer EncoderFallback::CreateFallbackBuffer() System::Text::EncoderFallbackBuffer* CreateFallbackBuffer(); // public override System.Int32 get_MaxCharCount() // Offset: 0x12D7FE8 // Implemented from: System.Text.EncoderFallback // Base method: System.Int32 EncoderFallback::get_MaxCharCount() int get_MaxCharCount(); // public override System.Boolean Equals(System.Object value) // Offset: 0x12D7FF0 // Implemented from: System.Object // Base method: System.Boolean Object::Equals(System.Object value) bool Equals(::Il2CppObject* value); // public override System.Int32 GetHashCode() // Offset: 0x12D8054 // Implemented from: System.Object // Base method: System.Int32 Object::GetHashCode() int GetHashCode(); }; // System.Text.EncoderExceptionFallback } DEFINE_IL2CPP_ARG_TYPE(System::Text::EncoderExceptionFallback*, "System.Text", "EncoderExceptionFallback"); #pragma pack(pop)
41.111111
107
0.718919
Futuremappermydud
b849cc603269e9ed36a9e77c3d7913727992ebdc
8,549
hpp
C++
sol/table.hpp
bananu7/sol
599673150ebadfcbfd87e21701a021b4d228debb
[ "MIT" ]
1
2015-03-27T12:36:25.000Z
2015-03-27T12:36:25.000Z
sol/table.hpp
bananu7/sol
599673150ebadfcbfd87e21701a021b4d228debb
[ "MIT" ]
null
null
null
sol/table.hpp
bananu7/sol
599673150ebadfcbfd87e21701a021b4d228debb
[ "MIT" ]
null
null
null
// The MIT License (MIT) // Copyright (c) 2013 Danny Y., Rapptz // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef SOL_TABLE_HPP #define SOL_TABLE_HPP #include "stack.hpp" #include "lua_function.hpp" #include <unordered_map> #include <array> #include <memory> #include <cstring> namespace sol { namespace detail { template<typename T> T* get_ptr(T& val) { return std::addressof(val); } template<typename T> T* get_ptr(T* val) { return val; } } class table : virtual public reference { private: std::unordered_map<std::string, std::shared_ptr<lua_func>> funcs; public: table() noexcept: reference(), funcs() {} table(lua_State* L, int index = -1): reference(L, index), funcs() { type_assert(L, index, type::table); } template<typename T, typename U> T get(U&& key) const { push(); stack::push(state(), std::forward<U>(key)); lua_gettable(state(), -2); type_assert(state(), -1, type_of<T>()); auto result = stack::pop<T>(state()); lua_pop(state(), 1); return result; } template<typename T, typename U> table& set(T&& key, U&& value) { push(); stack::push(state(), std::forward<T>(key)); stack::push(state(), std::forward<U>(value)); lua_settable(state(), -3); lua_pop(state(), 1); return *this; } template<typename T, typename TFx> table& set_function(T&& key, TFx&& fx) { typedef typename std::remove_pointer<typename std::decay<TFx>::type>::type clean_fx; return set_isfunction_fx(std::is_function<clean_fx>(), std::forward<T>(key), std::forward<TFx>(fx)); } template<typename T, typename TFx, typename TObj> table& set_function(T&& key, TFx&& fx, TObj&& obj) { return set_lvalue_fx(std::integral_constant<bool, std::is_lvalue_reference<TObj>::value || std::is_pointer<TObj>::value>(), std::forward<T>(key), std::forward<TFx>(fx), std::forward<TObj>(obj)); } size_t size() const { push(); return lua_rawlen(state(), -1); } private: template<typename T, typename TFx> table& set_isfunction_fx(std::true_type, T&& key, TFx&& fx) { return set_fx(std::false_type(), std::forward<T>(key), std::forward<TFx>(fx)); } template<typename T, typename TFx> table& set_isfunction_fx(std::false_type, T&& key, TFx&& fx) { typedef typename std::decay<TFx>::type clean_lambda; typedef typename detail::function_traits<decltype(&clean_lambda::operator())>::free_function_pointer_type raw_func_t; typedef std::is_convertible<clean_lambda, raw_func_t> isconvertible; return set_isconvertible_fx(isconvertible(), std::forward<T>(key), std::forward<TFx>(fx)); } template<typename T, typename TFx> table& set_isconvertible_fx(std::true_type, T&& key, TFx&& fx) { typedef typename std::decay<TFx>::type clean_lambda; typedef typename detail::function_traits<decltype(&clean_lambda::operator())>::free_function_pointer_type raw_func_t; return set_isfunction_fx(std::true_type(), std::forward<T>(key), raw_func_t(std::forward<TFx>(fx))); } template<typename T, typename TFx> table& set_isconvertible_fx(std::false_type, T&& key, TFx&& fx) { typedef typename std::remove_pointer<typename std::decay<TFx>::type>::type clean_fx; std::unique_ptr<lua_func> sptr(new lambda_lua_func<clean_fx>(std::forward<TFx>(fx))); return set_fx(std::forward<T>(key), std::move(sptr)); } template<typename T, typename TFx, typename TObj> table& set_lvalue_fx(std::true_type, T&& key, TFx&& fx, TObj&& obj) { return set_fx(std::true_type(), std::forward<T>(key), std::forward<TFx>(fx), std::forward<TObj>(obj)); } template<typename T, typename TFx, typename TObj> table& set_lvalue_fx(std::false_type, T&& key, TFx&& fx, TObj&& obj) { typedef typename std::remove_pointer<typename std::decay<TFx>::type>::type clean_fx; std::unique_ptr<lua_func> sptr(new explicit_lua_func<clean_fx, TObj>(std::forward<TObj>( obj ), std::forward<TFx>(fx))); return set_fx(std::forward<T>(key), std::move(sptr)); } template<typename T, typename TFx, typename TObj> table& set_fx(std::true_type, T&& key, TFx&& fx, TObj&& obj) { typedef typename std::decay<TObj>::type decay_of_to; typedef typename std::decay<TFx>::type decay_of_tfx; const static std::size_t data_t_count = (sizeof(decay_of_tfx)+(sizeof(void*)-1)) / sizeof(void*); typedef std::array<void*, data_t_count> data_t; std::string fkey(key); // Layout: // idx 1...n: verbatim data of member function pointer // idx n + 1: is the object's void pointer // We don't need to store the size, because the other side is templated // with the same member function pointer type decay_of_tfx fxptr(std::forward<TFx>(fx)); data_t fxptrdata; std::size_t fxptrsize = sizeof(fxptr); std::memcpy(std::addressof(fxptrdata[ 0 ]), std::addressof(fxptr), fxptrsize); void* userobjdata = static_cast<void*>(detail::get_ptr(obj)); lua_CFunction freefunc = &static_object_lua_func<decay_of_to, TFx>::call; const char* freefuncname = fkey.c_str(); const luaL_Reg funcreg[ 2 ] = { { freefuncname, freefunc }, { nullptr, nullptr } }; push(); stack::push(state(), fxptrdata); stack::push(state(), userobjdata); luaL_setfuncs(state(), funcreg, fxptrdata.size() + 1); lua_pop(state(), 1); return *this; } template<typename T, typename TFx> table& set_fx(std::false_type, T&& key, TFx&& fx) { typedef typename std::decay<TFx>::type ptr_fx; std::string fkey(key); ptr_fx target(std::forward<TFx>(fx)); void* userdata = reinterpret_cast<void*>(target); lua_CFunction freefunc = &static_lua_func<TFx>::call; const char* freefuncname = fkey.c_str(); const luaL_Reg funcreg[ 2 ] = { { freefuncname, freefunc }, { nullptr, nullptr } }; push(); stack::push(state(), userdata); luaL_setfuncs(state(), funcreg, 1); lua_pop(state(), 1); return *this; } template<typename T> table& set_fx(T&& key, std::unique_ptr<lua_func> luafunc) { std::string fkey(key); auto hint = funcs.find(fkey); if (hint == funcs.end()) { std::shared_ptr<lua_func> sptr(luafunc.release()); hint = funcs.emplace_hint(hint, fkey, std::move(sptr)); } else { hint->second.reset(luafunc.release()); } lua_func* target = hint->second.get(); void* userdata = reinterpret_cast<void*>(target); lua_CFunction freefunc = &lua_func::call; const char* freefuncname = hint->first.c_str(); const luaL_Reg funcreg[ 2 ] = { { freefuncname, freefunc }, { nullptr, nullptr } }; push(); stack::push(state(), userdata); luaL_setfuncs(state(), funcreg, 1); lua_pop(state(), 1); return *this; } }; } // sol #endif // SOL_TABLE_HPP
38.683258
133
0.619137
bananu7
b84a0cfd3e8da068d3ef99fd64963fa50dab34bc
22
cpp
C++
src/queries/model/insert.cpp
enerc/zsearch
60cdcd245b66d14fe4e2be1d26eb2b1877d4b098
[ "Apache-2.0" ]
null
null
null
src/queries/model/insert.cpp
enerc/zsearch
60cdcd245b66d14fe4e2be1d26eb2b1877d4b098
[ "Apache-2.0" ]
null
null
null
src/queries/model/insert.cpp
enerc/zsearch
60cdcd245b66d14fe4e2be1d26eb2b1877d4b098
[ "Apache-2.0" ]
null
null
null
#include "insert.hpp"
11
21
0.727273
enerc
b84b6ed2dfd208f12d4b6a168df6aac912ec9512
2,816
cpp
C++
util.cpp
rdhafidh/pki
fb69d04c8bc014ae10b107379146bac9b4d5970a
[ "MIT" ]
null
null
null
util.cpp
rdhafidh/pki
fb69d04c8bc014ae10b107379146bac9b4d5970a
[ "MIT" ]
null
null
null
util.cpp
rdhafidh/pki
fb69d04c8bc014ae10b107379146bac9b4d5970a
[ "MIT" ]
null
null
null
#include "util.h" #include <z85.h> #include <QDateTime> #include <QFile> #include <QFileInfo> #include <QStandardPaths> #include <QtGlobal> #include <cstdio> #include <iostream> bool Util::readFile(const QString &name, std::string &buffer) { QFile fn(name); if (!fn.open(QIODevice::ReadOnly)) { return false; } buffer.clear(); buffer = fn.readAll().toStdString(); fn.close(); return true; } bool Util::saveFile(const QString &fname, const std::string buffer) { QFile fn(fname); if (!fn.open(QIODevice::WriteOnly)) { return false; } fn.write(buffer.c_str(), buffer.size()); fn.close(); return true; } std::string Util::encode85(const std::string &buffer) { std::string ret; size_t len = Z85_encode_with_padding_bound(buffer.size()); if (len == 0) return ""; ret.resize(len); len = Z85_encode_with_padding(buffer.c_str(), ret.data(), buffer.size()); if (len == 0) { Util::logging("\nencode problem len 0\n"); ret = ""; return ret; } return ret; } std::string Util::decode85(const std::string &buffer) { std::string ret; size_t len = Z85_decode_with_padding_bound(buffer.c_str(), buffer.size()); if (len == 0) { Util::logging("Z85_decode_with_padding_bound failed"); return ""; } ret.resize(len); len = Z85_decode_with_padding(buffer.c_str(), ret.data(), buffer.size()); if (len == 0) { Util::logging("\ndecode problem len 0\n"); ret = ""; return ret; } return ret; } bool Util::logging(const QString &buffer) { QString pathfile = ""; #if defined(Q_OS_ANDROID) || defined(Q_OS_IOS) auto pth = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); pathfile = pth + "/"; #endif pathfile += "logging.log"; QFile fl(pathfile); if (!fl.open(QIODevice::WriteOnly | QIODevice::Append)) { return false; } QDateTime tm = QDateTime::currentDateTime(); std::string buf = tm.toString("d/M/yyyy hh:m:s").toStdString() + " : " + buffer.toStdString(); buf.insert(0, "\n"); buf += "\n"; fl.write(buf.c_str(), buf.size()); fl.close(); return true; } QByteArray Util::readLog() { QString pathfile = ""; #if defined(Q_OS_ANDROID) || defined(Q_OS_IOS) auto pth = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); pathfile = pth + "/"; #endif pathfile += "logging.log"; QFile fl(pathfile); if (!fl.open(QIODevice::ReadOnly)) { return ""; } QByteArray data = ""; while (!fl.atEnd()) { data += fl.readLine(); } return data; } bool Util::resetLog() { QString pathfile = ""; #if defined(Q_OS_ANDROID) || defined(Q_OS_IOS) auto pth = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); pathfile = pth + "/"; #endif pathfile += "logging.log"; return std::remove(pathfile.toStdString().c_str()) == 0; }
25.369369
79
0.649858
rdhafidh
b84ed822b2fb128fb48e2f2ba75c9078eb7f0b08
16,191
cpp
C++
wpb_ai_behaviors/src/wpb_ai_grab_action.cpp
6-dl/wpb_ai_tx2
6109627e72f32431b1460556c5b8aebc3a436e07
[ "BSD-3-Clause" ]
null
null
null
wpb_ai_behaviors/src/wpb_ai_grab_action.cpp
6-dl/wpb_ai_tx2
6109627e72f32431b1460556c5b8aebc3a436e07
[ "BSD-3-Clause" ]
null
null
null
wpb_ai_behaviors/src/wpb_ai_grab_action.cpp
6-dl/wpb_ai_tx2
6109627e72f32431b1460556c5b8aebc3a436e07
[ "BSD-3-Clause" ]
null
null
null
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2017-2020, Waterplus http://www.6-robot.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the WaterPlus nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * FOOTPRINTAL, 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. *********************************************************************/ /*!****************************************************************** @author ZhangWanjie ********************************************************************/ #include <ros/ros.h> #include <geometry_msgs/Pose2D.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/Twist.h> #include <visualization_msgs/Marker.h> #include <sensor_msgs/JointState.h> #include <std_msgs/String.h> #include <tf/transform_broadcaster.h> // 抓取参数调节(单位:米)(Modified in wpb_ai.yaml!!) static float grab_y_offset = 0.0f; //抓取前,对准物品,机器人的横向位移偏移量 static float grab_lift_offset = 0.0f; //手臂抬起高度的补偿偏移量 static float grab_forward_offset = 0.0f; //手臂抬起后,机器人向前抓取物品移动的位移偏移量 static float grab_gripper_value = 0.032; //抓取物品时,手爪闭合后的手指间距 #define STEP_WAIT 0 #define STEP_FIND_PLANE 1 #define STEP_PLANE_DIST 2 #define STEP_FIND_OBJ 3 #define STEP_OBJ_DIST 4 #define STEP_HAND_UP 5 #define STEP_FORWARD 6 #define STEP_GRAB 7 #define STEP_OBJ_UP 8 #define STEP_BACKWARD 9 #define STEP_DONE 10 static int nStep = STEP_WAIT; static std::string pc_topic; static ros::Publisher pc_pub; static ros::Publisher marker_pub; static ros::Publisher vel_pub; static ros::Publisher mani_ctrl_pub; static sensor_msgs::JointState mani_ctrl_msg; static ros::Publisher result_pub; void DrawBox(float inMinX, float inMaxX, float inMinY, float inMaxY, float inMinZ, float inMaxZ, float inR, float inG, float inB); void DrawText(std::string inText, float inScale, float inX, float inY, float inZ, float inR, float inG, float inB); void DrawPath(float inX, float inY, float inZ); void RemoveBoxes(); void VelCmd(float inVx , float inVy, float inTz); static visualization_msgs::Marker line_box; static visualization_msgs::Marker line_follow; static visualization_msgs::Marker text_marker; static std_msgs::String result_msg; static ros::Publisher odom_ctrl_pub; static std_msgs::String ctrl_msg; static geometry_msgs::Pose2D pose_diff; static float fObjGrabX = 0; static float fObjGrabY = 0; static float fObjGrabZ = 0; static float fMoveTargetX = 0; static float fMoveTargetY = 0; typedef struct stBoxMarker { float xMax; float xMin; float yMax; float yMin; float zMax; float zMin; }stBoxMarker; static stBoxMarker boxMarker; static stBoxMarker boxPlane; static stBoxMarker obj_to_track; static int nTimeDelayCounter = 0; static float fPlaneDist = 0; static float fTargetPlaneDist = 0.6; //与桌子之间的目标距离 static float fTargetGrabX = 0.9; //抓取时目标物品的x坐标 static float fTargetGrabY = 0.0; //抓取时目标物品的y坐标 void GrabPoseCallback(const geometry_msgs::Pose::ConstPtr& msg) { // 目标物品的坐标 fObjGrabX = msg->position.x; fObjGrabY = msg->position.y; fObjGrabZ = msg->position.z; ROS_WARN("[OBJ_TO_GRAB] x = %.2f y= %.2f ,z= %.2f " ,fObjGrabX, fObjGrabY, fObjGrabZ); ctrl_msg.data = "pose_diff reset"; odom_ctrl_pub.publish(ctrl_msg); // ajudge the dist to obj fMoveTargetX = fObjGrabX - fTargetGrabX; fMoveTargetY = fObjGrabY - fTargetGrabY + grab_y_offset; ROS_WARN("[MOVE_TARGET] x = %.2f y= %.2f " ,fMoveTargetX, fMoveTargetY); nStep = STEP_OBJ_DIST; } void PoseDiffCallback(const geometry_msgs::Pose2D::ConstPtr& msg) { pose_diff.x = msg->x; pose_diff.y = msg->y; pose_diff.theta = msg->theta; } void DrawBox(float inMinX, float inMaxX, float inMinY, float inMaxY, float inMinZ, float inMaxZ, float inR, float inG, float inB) { line_box.header.frame_id = "base_footprint"; line_box.ns = "line_box"; line_box.action = visualization_msgs::Marker::ADD; line_box.id = 0; line_box.type = visualization_msgs::Marker::LINE_LIST; line_box.scale.x = 0.005; line_box.color.r = inR; line_box.color.g = inG; line_box.color.b = inB; line_box.color.a = 1.0; geometry_msgs::Point p; p.z = inMinZ; p.x = inMinX; p.y = inMinY; line_box.points.push_back(p); p.x = inMinX; p.y = inMaxY; line_box.points.push_back(p); p.x = inMinX; p.y = inMaxY; line_box.points.push_back(p); p.x = inMaxX; p.y = inMaxY; line_box.points.push_back(p); p.x = inMaxX; p.y = inMaxY; line_box.points.push_back(p); p.x = inMaxX; p.y = inMinY; line_box.points.push_back(p); p.x = inMaxX; p.y = inMinY; line_box.points.push_back(p); p.x = inMinX; p.y = inMinY; line_box.points.push_back(p); p.z = inMaxZ; p.x = inMinX; p.y = inMinY; line_box.points.push_back(p); p.x = inMinX; p.y = inMaxY; line_box.points.push_back(p); p.x = inMinX; p.y = inMaxY; line_box.points.push_back(p); p.x = inMaxX; p.y = inMaxY; line_box.points.push_back(p); p.x = inMaxX; p.y = inMaxY; line_box.points.push_back(p); p.x = inMaxX; p.y = inMinY; line_box.points.push_back(p); p.x = inMaxX; p.y = inMinY; line_box.points.push_back(p); p.x = inMinX; p.y = inMinY; line_box.points.push_back(p); p.x = inMinX; p.y = inMinY; p.z = inMinZ; line_box.points.push_back(p); p.x = inMinX; p.y = inMinY; p.z = inMaxZ; line_box.points.push_back(p); p.x = inMinX; p.y = inMaxY; p.z = inMinZ; line_box.points.push_back(p); p.x = inMinX; p.y = inMaxY; p.z = inMaxZ; line_box.points.push_back(p); p.x = inMaxX; p.y = inMaxY; p.z = inMinZ; line_box.points.push_back(p); p.x = inMaxX; p.y = inMaxY; p.z = inMaxZ; line_box.points.push_back(p); p.x = inMaxX; p.y = inMinY; p.z = inMinZ; line_box.points.push_back(p); p.x = inMaxX; p.y = inMinY; p.z = inMaxZ; line_box.points.push_back(p); marker_pub.publish(line_box); } static int nTextNum = 2; void DrawText(std::string inText, float inScale, float inX, float inY, float inZ, float inR, float inG, float inB) { text_marker.header.frame_id = "base_footprint"; text_marker.ns = "line_obj"; text_marker.action = visualization_msgs::Marker::ADD; text_marker.id = nTextNum; nTextNum ++; text_marker.type = visualization_msgs::Marker::TEXT_VIEW_FACING; text_marker.scale.z = inScale; text_marker.color.r = inR; text_marker.color.g = inG; text_marker.color.b = inB; text_marker.color.a = 1.0; text_marker.pose.position.x = inX; text_marker.pose.position.y = inY; text_marker.pose.position.z = inZ; text_marker.pose.orientation=tf::createQuaternionMsgFromYaw(1.0); text_marker.text = inText; marker_pub.publish(text_marker); } void RemoveBoxes() { line_box.action = 3; line_box.points.clear(); marker_pub.publish(line_box); line_follow.action = 3; line_follow.points.clear(); marker_pub.publish(line_follow); text_marker.action = 3; marker_pub.publish(text_marker); } void VelCmd(float inVx , float inVy, float inTz) { geometry_msgs::Twist vel_cmd; vel_cmd.linear.x = inVx; vel_cmd.linear.y = inVy; vel_cmd.angular.z = inTz; vel_pub.publish(vel_cmd); } void BehaviorCB(const std_msgs::String::ConstPtr &msg) { int nFindIndex = msg->data.find("grab stop"); if( nFindIndex >= 0 ) { ROS_WARN("[grab_stop] "); nStep = STEP_WAIT; geometry_msgs::Twist vel_cmd; vel_cmd.linear.x = 0; vel_cmd.linear.y = 0; vel_cmd.linear.z = 0; vel_cmd.angular.x = 0; vel_cmd.angular.y = 0; vel_cmd.angular.z = 0; vel_pub.publish(vel_cmd); } } int main(int argc, char **argv) { ros::init(argc, argv, "wpb_ai_grab_action"); ROS_INFO("wpb_ai_grab_action"); ros::NodeHandle nh; marker_pub = nh.advertise<visualization_msgs::Marker>("obj_marker", 10); vel_pub = nh.advertise<geometry_msgs::Twist>("/cmd_vel", 30); mani_ctrl_pub = nh.advertise<sensor_msgs::JointState>("/wpb_ai/mani_ctrl", 30); result_pub = nh.advertise<std_msgs::String>("/wpb_ai/grab_result", 30); ros::Subscriber sub_grab_pose = nh.subscribe("/wpb_ai/grab_pose", 1, GrabPoseCallback); ros::Subscriber sub_beh = nh.subscribe("/wpb_ai/behaviors", 1, BehaviorCB); odom_ctrl_pub = nh.advertise<std_msgs::String>("/wpb_ai/ctrl", 30); ros::Subscriber pose_diff_sub = nh.subscribe("/wpb_ai/pose_diff", 1, PoseDiffCallback); mani_ctrl_msg.name.resize(2); mani_ctrl_msg.position.resize(2); mani_ctrl_msg.velocity.resize(2); mani_ctrl_msg.name[0] = "lift"; mani_ctrl_msg.name[1] = "gripper"; mani_ctrl_msg.position[0] = 0; mani_ctrl_msg.velocity[0] = 0.5; //升降速度(单位:米/秒) mani_ctrl_msg.position[1] = 0.16; mani_ctrl_msg.velocity[1] = 5; //手爪开合角速度(单位:度/秒) ros::NodeHandle nh_param("~"); nh_param.getParam("grab/grab_y_offset", grab_y_offset); nh_param.getParam("grab/grab_lift_offset", grab_lift_offset); nh_param.getParam("grab/grab_forward_offset", grab_forward_offset); nh_param.getParam("grab/grab_gripper_value", grab_gripper_value); ros::Rate r(30); while(nh.ok()) { //4、左右平移对准目标物品 if(nStep == STEP_OBJ_DIST) { float vx,vy; vx = (fMoveTargetX - pose_diff.x)/2; vy = (fMoveTargetY - pose_diff.y)/2; VelCmd(vx,vy,0); //ROS_INFO("[MOVE] T(%.2f %.2f) od(%.2f , %.2f) v(%.2f,%.2f)" ,fMoveTargetX, fMoveTargetY, pose_diff.x ,pose_diff.y,vx,vy); if(fabs(vx) < 0.01 && fabs(vy) < 0.01) { VelCmd(0,0,0); ctrl_msg.data = "pose_diff reset"; odom_ctrl_pub.publish(ctrl_msg); nTimeDelayCounter = 0; nStep = STEP_HAND_UP; } result_msg.data = "object x"; result_pub.publish(result_msg); } //5、抬起手臂 if(nStep == STEP_HAND_UP) { if(nTimeDelayCounter == 0) { mani_ctrl_msg.position[0] = fObjGrabZ + grab_lift_offset; mani_ctrl_msg.position[1] = 0.16; mani_ctrl_pub.publish(mani_ctrl_msg); ROS_WARN("[STEP_HAND_UP] lift= %.2f gripper= %.2f " ,mani_ctrl_msg.position[0], mani_ctrl_msg.position[1]); result_msg.data = "hand up"; result_pub.publish(result_msg); } nTimeDelayCounter ++; mani_ctrl_pub.publish(mani_ctrl_msg); VelCmd(0,0,0); if(nTimeDelayCounter > 15*30) { fMoveTargetX = fTargetGrabX -0.65 + grab_forward_offset; fMoveTargetY = 0; ROS_WARN("[STEP_FORWARD] x = %.2f y= %.2f " ,fMoveTargetX, fMoveTargetY); nTimeDelayCounter = 0; //ctrl_msg.data = "pose_diff reset"; //odom_ctrl_pub.publish(ctrl_msg); nStep = STEP_FORWARD; } } //6、前进靠近物品 if(nStep == STEP_FORWARD) { float vx,vy; vx = (fMoveTargetX - pose_diff.x)/2; vy = (fMoveTargetY - pose_diff.y)/2; VelCmd(vx,vy,0); //ROS_INFO("[STEP_FORWARD] T(%.2f %.2f) od(%.2f , %.2f) v(%.2f,%.2f)" ,fMoveTargetX, fMoveTargetY, pose_diff.x ,pose_diff.y,vx,vy); if(fabs(vx) < 0.01 && fabs(vy) < 0.01) { VelCmd(0,0,0); ctrl_msg.data = "pose_diff reset"; odom_ctrl_pub.publish(ctrl_msg); nTimeDelayCounter = 0; ROS_WARN("[STEP_GRAB] grab_gripper_value = %.2f",grab_gripper_value); nStep = STEP_GRAB; } result_msg.data = "forward"; result_pub.publish(result_msg); } //7、抓取物品 if(nStep == STEP_GRAB) { if(nTimeDelayCounter == 0) { result_msg.data = "grab"; result_pub.publish(result_msg); } mani_ctrl_msg.position[1] = grab_gripper_value; //抓取物品手爪闭合宽度 mani_ctrl_pub.publish(mani_ctrl_msg); //ROS_WARN("[STEP_GRAB] lift= %.2f gripper= %.2f " ,mani_ctrl_msg.position[0], mani_ctrl_msg.position[1]); nTimeDelayCounter++; VelCmd(0,0,0); if(nTimeDelayCounter > 8*30) { nTimeDelayCounter = 0; ROS_WARN("[STEP_OBJ_UP]"); nStep = STEP_OBJ_UP; } } //8、拿起物品 if(nStep == STEP_OBJ_UP) { if(nTimeDelayCounter == 0) { mani_ctrl_msg.position[0] += 0.03; mani_ctrl_pub.publish(mani_ctrl_msg); //ROS_WARN("[MANI_CTRL] lift= %.2f gripper= %.2f " ,mani_ctrl_msg.position[0], mani_ctrl_msg.position[1]); result_msg.data = "object up"; result_pub.publish(result_msg); } nTimeDelayCounter++; VelCmd(0,0,0); if(nTimeDelayCounter > 3*30) { fMoveTargetX = -(fObjGrabX -0.55 + grab_forward_offset); fMoveTargetY = -(fObjGrabY + grab_y_offset); ROS_WARN("[STEP_BACKWARD] x= %.2f y= %.2f " ,fMoveTargetX, fMoveTargetY); nTimeDelayCounter = 0; nStep = STEP_BACKWARD; } } //9、带着物品后退 if(nStep == STEP_BACKWARD) { //ROS_WARN("[STEP_BACKWARD] nTimeDelayCounter = %d " ,nTimeDelayCounter); //nTimeDelayCounter++; float vx,vy; vx = (fMoveTargetX - pose_diff.x)/2; vy = (fMoveTargetY - pose_diff.y)/2; VelCmd(vx,vy,0); //ROS_INFO("[MOVE] T(%.2f %.2f) od(%.2f , %.2f) v(%.2f,%.2f)" ,fMoveTargetX, fMoveTargetY, pose_diff.x ,pose_diff.y,vx,vy); if(fabs(vx) < 0.01 && fabs(vy) < 0.01) { VelCmd(0,0,0); ctrl_msg.data = "pose_diff reset"; odom_ctrl_pub.publish(ctrl_msg); nTimeDelayCounter = 0; ROS_WARN("[STEP_DONE]"); nStep = STEP_DONE; } result_msg.data = "backward"; result_pub.publish(result_msg); } //10、抓取任务完毕 if(nStep == STEP_DONE) { if(nTimeDelayCounter < 10) { VelCmd(0,0,0); nTimeDelayCounter ++; } result_msg.data = "done"; result_pub.publish(result_msg); } ros::spinOnce(); r.sleep(); } return 0; }
34.744635
144
0.609907
6-dl
b84f19544b6a50fa5fb96d9988fad2844e6fc888
12,832
cpp
C++
Synergy Editor TGC/Synergy Editor/UpdateFtpCore.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
231
2018-01-28T00:06:56.000Z
2022-03-31T21:39:56.000Z
Synergy Editor TGC/Synergy Editor/UpdateFtpCore.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
9
2016-02-10T10:46:16.000Z
2017-12-06T17:27:51.000Z
Synergy Editor TGC/Synergy Editor/UpdateFtpCore.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
66
2018-01-28T21:54:52.000Z
2022-02-16T22:50:57.000Z
#include "StdAfx.h" #include "UpdateFtpCore.h" #include "Utilities.h" #include "Settings.h" #include "UpdateGlobal.h" #ifdef _DEBUG #define new DEBUG_NEW #endif UpdateTool *CUpdateFtpCore::m_Tool; bool CUpdateFtpCore::cancel; void CUpdateFtpCore::InitSession(UpdateTool *tool) { m_Tool = tool; cancel = false; } int CUpdateFtpCore::CheckForUpdate() { CString updateVersion = GetFileContents(_T("update.txt")); if(updateVersion.GetLength() == 0) { return 2; } CString lineToken; int curLine = 0; CString resToken; int curPos = 0; int mode = 1; CString Name, Type, Version, Size, Help, File, GUID; UINT i; bool canAdd; lineToken = updateVersion.Tokenize(_T("\n"),curLine); while (lineToken != "") { mode = 1; curPos = 0; if(cancel) { break; } resToken = lineToken.Tokenize(_T("|"),curPos); while (resToken != "") { switch(mode) { case 1: Name = resToken; break; case 2: Type = resToken; break; case 3: Version = resToken; break; case 4: Size = resToken; break; case 5: if(resToken.Right(3) == _T("txt")) { Help = GetFileContents(resToken); } else { Help = resToken; } break; case 6: File = resToken; break; case 7: GUID = resToken; break; } resToken= lineToken.Tokenize(_T("|"),curPos); mode++; }; canAdd = true; for(i=0; i < m_Tool->m_GUIDs.size(); i++) { if(m_Tool->m_GUIDs.at(i) == GUID) { canAdd = false; break; } } if(canAdd && !cancel) { m_Tool->AddItem(Name, Type, Version, Size, Help, File, GUID); } lineToken = updateVersion.Tokenize(_T("\n"),curLine); }; return cancel; } void CUpdateFtpCore::DownloadSelected(CString file) { int size = file.GetLength() + 1; TCHAR *newfile = new TCHAR[size]; wcscpy_s(newfile, size, file); AfxBeginThread(DownloadSelectedThread, newfile); } UINT CUpdateFtpCore::DownloadSelectedThread(LPVOID pParam) { bool success = true; CString file((TCHAR*)pParam); delete [] pParam; TCHAR path[MAX_PATH]; GetTempPath(MAX_PATH, path); CString exeName; CString directory = path; CString newLocation; CString resToken; int curPos = 0; resToken = file.Tokenize(_T(","),curPos); while (resToken != "") { newLocation = Settings::DBPLocation + resToken; exeName = Utilities::ExtractFilename(resToken); // Download the updated file //CString URL = exeName; // leefix - 011008 - location of file can be in a subfolder on FTP (better organised) CString URL = file; CString updateFileLocation = directory + exeName; // Delete temp file if it already exists if(Utilities::CheckFileExists(updateFileLocation)) { ::DeleteFile(updateFileLocation); } // Proceed with the update bool bTransferSuccess = DownloadFile(URL, updateFileLocation); if (!bTransferSuccess) { success = false; break; } if(cancel) // If cancelled during download then we may have a corrupt download, return { break; } // If cancelled here then we continue doing what we are doing if (!UpdateGlobal::Switch(newLocation, updateFileLocation, false)) { success = false; break; } // Check if it is a sfx if(newLocation.Right(11) == _T("_update.exe") && !cancel) { STARTUPINFO siStartupInfo; PROCESS_INFORMATION piProcessInfo; memset(&siStartupInfo, 0, sizeof(siStartupInfo)); memset(&piProcessInfo, 0, sizeof(piProcessInfo)); siStartupInfo.cb = sizeof(siStartupInfo); CreateProcess(newLocation, _T(" x -y"), 0, 0, FALSE, CREATE_DEFAULT_ERROR_MODE, 0, NULL, &siStartupInfo, &piProcessInfo); WaitForSingleObject(piProcessInfo.hProcess, INFINITE); ::CloseHandle(piProcessInfo.hThread); ::CloseHandle(piProcessInfo.hProcess); ::DeleteFile(newLocation); } resToken= file.Tokenize(_T(","),curPos); }; if(cancel) // Might have hit cancel during file copy, so cancel next operation { ::SendMessage(m_Tool->GetSafeHwnd(), WM_USER + 3, 0, 0); // Fail } else if(success) { ::SendMessage(m_Tool->GetSafeHwnd(), WM_USER + 1, 0, 0); // Next } else { ::SendMessage(m_Tool->GetSafeHwnd(), WM_USER + 3, 1, 0); // Fail } return 0; } CString CUpdateFtpCore::GetFileContents(CString filename) { // vars HINTERNET hInet, hInetConnect, hFtpFile; CString ret = _T(""); // access FTP try { // internet handle hInet = InternetOpen( _T("InternetConnection"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 ); if ( !hInet ) throw 1; // connection handle hInetConnect = InternetConnect( hInet, _T("ftp.thegamecreators.com"), INTERNET_DEFAULT_FTP_PORT, _T("anonymous"), NULL, INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0 ); if ( !hInetConnect ) throw 2; // go to folder in FTP if ( !FtpSetCurrentDirectory( hInetConnect, _T("dbpro_updates") ) ) throw 21; // get file handle hFtpFile = FtpOpenFile( hInetConnect, _T("update.txt"), GENERIC_READ, FTP_TRANSFER_TYPE_ASCII, 0 ); if ( !hFtpFile ) { TCHAR error [ 256 ]; DWORD dwError, dwLen; InternetGetLastResponseInfo( &dwError, error, &dwLen ); throw 3; } // get the file itself DWORD dwSizeHigh = 0; DWORD dwSizeLow = FtpGetFileSize( hFtpFile, &dwSizeHigh ); float fSize = (float) dwSizeLow; // download file vars bool bFinished = false; char pBuffer [ 20481 ]; memset ( pBuffer, 0, 20481 ); DWORD dwReceived = 0; DWORD dwTotalReceived = 0; // while not finished and not cancelled, download while ( !bFinished ) { BOOL bResult = InternetReadFile( hFtpFile, pBuffer, 20480, &dwReceived ); if ( !bResult ) { TCHAR error [ 256 ]; DWORD dwError, dwLen; InternetGetLastResponseInfo( &dwError, error, &dwLen ); throw 4; } // when stopped receiving, finish if ( dwReceived == 0 ) bFinished = true; dwTotalReceived += dwReceived; // while receiving, write to local file from FTP file handle if ( dwReceived > 0 ) { //fwrite( pBuffer, 1, dwReceived, pLocalFile ); pBuffer [ dwReceived ] = 0; TCHAR* pTString = new TCHAR[dwReceived+1]; MultiByteToWideChar ( CP_ACP, 0, ( const char* )pBuffer, -1, pTString, strlen ( ( const char* ) pBuffer ) + 1 ); ret.Append(pTString); if(pTString) delete pTString; } } // end connection InternetCloseHandle( hFtpFile ); InternetCloseHandle( hInetConnect ); InternetCloseHandle( hInet ); } catch(...) { if ( hFtpFile ) InternetCloseHandle( hFtpFile ); if ( hInetConnect ) InternetCloseHandle( hInetConnect ); if ( hInet ) InternetCloseHandle( hInet ); } /* CInternetSession sess(_T("SynergyEditor/1.0")); CFtpConnection* pConnect = NULL; CInternetFile* read = NULL; CString ret = _T(""); BYTE pBufT[4096]; BYTE *pBuf = NULL; try { pConnect = sess.GetFtpConnection(_T("ftp.thegamecreators.com")); pConnect->SetCurrentDirectory(_T("dbpro_updates")); read = pConnect->OpenFile(filename, GENERIC_READ, FTP_TRANSFER_TYPE_ASCII, 1); ULONGLONG SIZE_READ = read->GetLength(); pBuf = new BYTE[(size_t)SIZE_READ]; memset(pBuf, NULL, (size_t)SIZE_READ); ULONGLONG total = 0; do { memset(pBufT, NULL, 4096); UINT amount = read->Read(pBufT, 4096); if(amount > (size_t)SIZE_READ) { amount = (UINT)SIZE_READ; } if(amount > 0) { for(UINT i=0; i < amount; i++) { pBuf[i+total] = pBufT[i]; } total += amount; } else { read->Close(); break; } } while (true); for(int j=0; j<total; j++) { ret.AppendChar((TCHAR)pBuf[j]); } } catch (CInternetException* pEx) { TCHAR sz[1024]; pEx->GetErrorMessage(sz, 1024); printf_s("ERROR! %s\n", sz); // U70 - added to inform user what is really going on (firewall block says 'up to date') MessageBox ( NULL, sz, _T("Internet Connection Error"), MB_OK ); pEx->Delete(); } // If the buffer is used delete it's contents if(pBuf != NULL) { delete[] pBuf; } // If the file is open close it if(read != NULL) { read->Close(); delete read; } // if the connection is open, close it if (pConnect != NULL) { pConnect->Close(); delete pConnect; } sess.Close(); */ return ret; } // Download a file to a specified location bool CUpdateFtpCore::DownloadFile(CString remoteFile, CString localFile) { // vars HINTERNET hInet, hInetConnect, hFtpFile; HANDLE hOutFile; DWORD dwNumWritten; bool res = true; hOutFile = CreateFile(localFile, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hOutFile == INVALID_HANDLE_VALUE) return false; // access FTP try { // internet handle hInet = InternetOpen( _T("InternetConnection"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 ); if ( !hInet ) throw 1; // connection handle hInetConnect = InternetConnect( hInet, _T("ftp.thegamecreators.com"), INTERNET_DEFAULT_FTP_PORT, _T("anonymous"), NULL, INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0 ); if ( !hInetConnect ) throw 2; // go to folder in FTP if ( !FtpSetCurrentDirectory( hInetConnect, _T("dbpro_updates") ) ) throw 21; // leeadd - 011008 - navigate through folders of remoteFile on FTP CString remoteEXE = Utilities::ExtractFilename ( remoteFile ); CString remotePath = Utilities::ExtractPath ( remoteFile ); while ( remotePath.Find(_T("\\"))!=-1 ) { int iFindFolderPos = remotePath.Find(_T("\\")); CString oneFOLDER = remotePath.Left(iFindFolderPos); FtpSetCurrentDirectory( hInetConnect, oneFOLDER ); remotePath = remotePath.Right(remotePath.GetLength()-(iFindFolderPos+1)); } // get file handle hFtpFile = FtpOpenFile( hInetConnect, remoteEXE, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY, 0 ); if ( !hFtpFile ) { TCHAR error [ 256 ]; DWORD dwError, dwLen; InternetGetLastResponseInfo( &dwError, error, &dwLen ); throw 3; } // get the file itself DWORD dwSizeHigh = 0; DWORD dwSizeLow = FtpGetFileSize( hFtpFile, &dwSizeHigh ); float fSize = (float) dwSizeLow; // download file vars bool bFinished = false; char pBuffer [ 20481 ]; memset ( pBuffer, 0, 20481 ); DWORD dwReceived = 0; DWORD dwTotalReceived = 0; // while not finished and not cancelled, download while ( !bFinished && !cancel ) { BOOL bResult = InternetReadFile( hFtpFile, pBuffer, 20480, &dwReceived ); if ( !bResult ) { TCHAR error [ 256 ]; DWORD dwError, dwLen; InternetGetLastResponseInfo( &dwError, error, &dwLen ); throw 4; } // when stopped receiving, finish if ( dwReceived == 0 ) bFinished = true; dwTotalReceived += dwReceived; // while receiving, write to local file from FTP file handle if ( dwReceived > 0 ) { WriteFile(hOutFile, pBuffer, dwReceived, &dwNumWritten, NULL); if (dwReceived != dwNumWritten) { res = false; break; } ::SendMessage(m_Tool->GetSafeHwnd(), WM_USER + 2, dwReceived, 0); // Update GUI } else { break; } } // finish off local file if ( hOutFile ) { CloseHandle( hOutFile ); hOutFile=NULL; } // end connection InternetCloseHandle( hFtpFile ); InternetCloseHandle( hInetConnect ); InternetCloseHandle( hInet ); } catch(...) { if ( hOutFile ) CloseHandle( hOutFile ); if ( hFtpFile ) InternetCloseHandle( hFtpFile ); if ( hInetConnect ) InternetCloseHandle( hInetConnect ); if ( hInet ) InternetCloseHandle( hInet ); } /* CInternetSession sess(_T("SynergyEditor/1.0")); CFtpConnection* pConnect = NULL; CInternetFile* read = NULL; DWORD dwWriteSize, dwNumWritten; try { pConnect = sess.GetFtpConnection(_T("ftp.thegamecreators.com")); pConnect->SetCurrentDirectory(_T("dbpro_updates")); read = pConnect->OpenFile(remoteFile, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY, 1); do { dwReadSizeOut = read->Read(pBuf, TRANSFER_SIZE); dwWriteSize = dwReadSizeOut; if (dwReadSizeOut > 0) { ::SendMessage(m_Tool->GetSafeHwnd(), WM_USER + 2, dwReadSizeOut, 0); // Update GUI WriteFile(hOutFile, pBuf, dwWriteSize, &dwNumWritten, NULL); // File write error if (dwWriteSize != dwNumWritten) { res = false; break; } } else { break; } } while(!cancel); } catch (CInternetException* pEx) { TCHAR sz[1024]; pEx->GetErrorMessage(sz, 1024); printf_s("ERROR! %s\n", sz); pEx->Delete(); } // If the file is open close it if(read != NULL) { read->Close(); delete read; } CloseHandle(hOutFile); // if the connection is open, close it if (pConnect != NULL) { pConnect->Close(); delete pConnect; } sess.Close(); */ return res; } void CUpdateFtpCore::Cancel() { cancel = true; }
23.373406
171
0.652198
domydev
b85aea8357d43b4f6ad78c282e1936deba979b2f
579
hpp
C++
include/x/cba/addons/diagnostic/script_component.hpp
Task-Force-Dagger/Dagger
56b9ffe3387f74830419a987eed5a0f386674331
[ "MIT" ]
null
null
null
include/x/cba/addons/diagnostic/script_component.hpp
Task-Force-Dagger/Dagger
56b9ffe3387f74830419a987eed5a0f386674331
[ "MIT" ]
7
2021-11-22T04:36:52.000Z
2021-12-13T18:55:24.000Z
include/x/cba/addons/diagnostic/script_component.hpp
Task-Force-Dagger/Dagger
56b9ffe3387f74830419a987eed5a0f386674331
[ "MIT" ]
null
null
null
#define COMPONENT diagnostic #include "\x\cba\addons\main\script_mod.hpp" #ifdef DEBUG_ENABLED_DIAGNOSTIC #define DEBUG_MODE_FULL #endif #ifdef DEBUG_SETTINGS_DIAGNOSTIC #define DEBUG_SETTINGS DEBUG_SETTINGS_DIAGNOSTIC #endif #include "\x\cba\addons\main\script_macros.hpp" #include "\a3\ui_f\hpp\defineDIKCodes.inc" #include "\a3\ui_f\hpp\defineCommonGrids.inc" #include "\a3\ui_f\hpp\defineResincl.inc" // #include "\a3\ui_f\hpp\defineResinclDesign.inc" // moved to sqf to handle undef error #define IDC_DEBUGCONSOLE_PREV 90110 #define IDC_DEBUGCONSOLE_NEXT 90111
27.571429
88
0.797927
Task-Force-Dagger
b86180f5ca42045a722a356f64fff9149434edfd
6,757
cpp
C++
GA_EAX_1.0/Normal/env.cpp
ozeasx/GA-EAX
c6841f25e510680b896734acd1fe8fdfd7611653
[ "MIT" ]
3
2021-10-31T14:24:51.000Z
2022-03-17T02:56:04.000Z
GA_EAX_1.0/Normal/env.cpp
ozeasx/GA-EAX
c6841f25e510680b896734acd1fe8fdfd7611653
[ "MIT" ]
null
null
null
GA_EAX_1.0/Normal/env.cpp
ozeasx/GA-EAX
c6841f25e510680b896734acd1fe8fdfd7611653
[ "MIT" ]
2
2022-03-17T04:40:28.000Z
2022-03-17T05:56:39.000Z
#ifndef __ENVIRONMENT__ #include "env.h" #endif #include <math.h> void MakeRandSol( TEvaluator* eval , TIndi& indi ); void Make2optSol( TEvaluator* eval , TIndi& indi ); TEnvironment::TEnvironment() { fEvaluator = new TEvaluator(); } TEnvironment::~TEnvironment() { delete [] fIndexForMating; delete [] tCurPop; delete fEvaluator; delete tCross; int N = fEvaluator->Ncity; for( int i = 0; i < N; ++i ) delete [] fEdgeFreq[ i ]; delete [] fEdgeFreq; } void TEnvironment::Define() { fEvaluator->SetInstance( fFileNameTSP ); int N = fEvaluator->Ncity; fIndexForMating = new int [ fNumOfPop + 1 ]; tCurPop = new TIndi [ fNumOfPop ]; for ( int i = 0; i < fNumOfPop; ++i ) tCurPop[i].Define( N ); tBest.Define( N ); tCross = new TCross( N ); tCross->eval = fEvaluator; tCross->fNumOfPop = fNumOfPop; tKopt = new TKopt( N ); tKopt->eval = fEvaluator; tKopt->SetInvNearList(); fEdgeFreq = new int* [ N ]; for( int i = 0; i < N; ++i ) fEdgeFreq[ i ] = new int [ N ]; } void TEnvironment::DoIt() { this->fTimeStart = clock(); if( fFileNameInitPop == NULL ) this->InitPop(); else this->ReadPop( fFileNameInitPop ); this->fTimeInit = clock(); this->Init(); this->GetEdgeFreq(); while( 1 ) { this->SetAverageBest(); printf( "%d: %d %lf\n", fCurNumOfGen, fBestValue, fAverageValue ); if( this->TerminationCondition() ) break; this->SelectForMating(); for( int s =0; s < fNumOfPop; ++s ) { this->GenerateKids( s ); this->SelectForSurvival( s ); } ++fCurNumOfGen; } this->fTimeEnd = clock(); } void TEnvironment::Init() { fAccumurateNumCh = 0; fCurNumOfGen = 0; fStagBest = 0; fMaxStagBest = 0; fStage = 1; /* Stage I */ fFlagC[ 0 ] = 4; /* Diversity preservation: 1:Greedy, 2:--- , 3:Distance, 4:Entropy (see Section 4) */ fFlagC[ 1 ] = 1; /* Eset Type: 1:Single-AB, 2:Block2 (see Section 3) */ } bool TEnvironment::TerminationCondition() { if ( fAverageValue - fBestValue < 0.001 ) return true; if( fStage == 1 ) /* Stage I */ { if( fStagBest == int(1500/fNumOfKids) && fMaxStagBest == 0 ){ /* 1500/N_ch (See Section 2.2) */ fMaxStagBest =int( fCurNumOfGen / 10 ); /* fMaxStagBest = G/10 (See Section 2.2) */ } else if( fMaxStagBest != 0 && fMaxStagBest <= fStagBest ){ /* Terminate Stage I (proceed to Stage II) */ fStagBest = 0; fMaxStagBest = 0; fCurNumOfGen1 = fCurNumOfGen; fFlagC[ 1 ] = 2; fStage = 2; } return false; } if( fStage == 2 ){ /* Stage II */ if( fStagBest == int(1500/fNumOfKids) && fMaxStagBest == 0 ){ /* 1500/N_ch */ fMaxStagBest = int( (fCurNumOfGen - fCurNumOfGen1) / 10 ); /* fMaxStagBest = G/10 (See Section 2.2) */ } else if( fMaxStagBest != 0 && fMaxStagBest <= fStagBest ){ /* Terminate Stage II and GA */ return true; } return false; } } void TEnvironment::SetAverageBest() { int stockBest = tBest.fEvaluationValue; fAverageValue = 0.0; fBestIndex = 0; fBestValue = tCurPop[0].fEvaluationValue; for(int i = 0; i < fNumOfPop; ++i ){ fAverageValue += tCurPop[i].fEvaluationValue; if( tCurPop[i].fEvaluationValue < fBestValue ){ fBestIndex = i; fBestValue = tCurPop[i].fEvaluationValue; } } tBest = tCurPop[ fBestIndex ]; fAverageValue /= (double)fNumOfPop; if( tBest.fEvaluationValue < stockBest ){ fStagBest = 0; fBestNumOfGen = fCurNumOfGen; fBestAccumeratedNumCh = fAccumurateNumCh; } else ++fStagBest; } void TEnvironment::InitPop() { for ( int i = 0; i < fNumOfPop; ++i ){ tKopt->MakeRandSol( tCurPop[ i ] ); /* Make a random tour */ tKopt->DoIt( tCurPop[ i ] ); /* Apply the local search with the 2-opt neighborhood */ } } void TEnvironment::SelectForMating() { /* fIndexForMating[] <-- a random permutation of 0, ..., fNumOfPop-1 */ tRand->Permutation( fIndexForMating, fNumOfPop, fNumOfPop ); fIndexForMating[ fNumOfPop ] = fIndexForMating[ 0 ]; } void TEnvironment::SelectForSurvival( int s ) { } void TEnvironment::GenerateKids( int s ) { tCross->SetParents( tCurPop[fIndexForMating[s]], tCurPop[fIndexForMating[s+1]], fFlagC, fNumOfKids ); /* Note: tCurPop[fIndexForMating[s]] is replaced with a best offspring solutions in tCorss->DoIt(). fEegeFreq[][] is also updated there. */ tCross->DoIt( tCurPop[fIndexForMating[s]], tCurPop[fIndexForMating[s+1]], fNumOfKids, 1, fFlagC, fEdgeFreq ); fAccumurateNumCh += tCross->fNumOfGeneratedCh; } void TEnvironment::GetEdgeFreq() { int N = fEvaluator->Ncity; int k0, k1; for( int j1 = 0; j1 < N; ++j1 ) for( int j2 = 0; j2 < N; ++j2 ) fEdgeFreq[ j1 ][ j2 ] = 0; for( int i = 0; i < fNumOfPop; ++i ) { for(int j = 0; j < N; ++j ) { k0 = tCurPop[ i ].fLink[ j ][ 0 ]; k1 = tCurPop[ i ].fLink[ j ][ 1 ]; ++fEdgeFreq[ j ][ k0 ]; ++fEdgeFreq[ j ][ k1 ]; } } } void TEnvironment::PrintOn( int n, char* dstFile ) { printf( "n = %d val = %d Gen = %d Time = %d %d\n" , n, tBest.fEvaluationValue, fCurNumOfGen, (int)((double)(this->fTimeInit - this->fTimeStart)/(double)CLOCKS_PER_SEC), (int)((double)(this->fTimeEnd - this->fTimeStart)/(double)CLOCKS_PER_SEC) ); fflush(stdout); FILE *fp; char filename[ 80 ]; sprintf( filename, "%s_Result", dstFile ); fp = fopen( filename, "a"); fprintf( fp, "%d %d %d %d %d\n" , n, tBest.fEvaluationValue, fCurNumOfGen, (int)((double)(this->fTimeInit - this->fTimeStart)/(double)CLOCKS_PER_SEC), (int)((double)(this->fTimeEnd - this->fTimeStart)/(double)CLOCKS_PER_SEC) ); fclose( fp ); } void TEnvironment::WriteBest( char* dstFile ) { FILE *fp; char filename[ 80 ]; sprintf( filename, "%s_BestSol", dstFile ); fp = fopen( filename, "a"); fEvaluator->WriteTo( fp, tBest ); fclose( fp ); } void TEnvironment::WritePop( int n, char* dstFile ) { FILE *fp; char filename[ 80 ]; sprintf( filename, "%s_POP_%d", dstFile, n ); fp = fopen( filename, "w"); for( int s = 0; s < fNumOfPop; ++s ) fEvaluator->WriteTo( fp, tCurPop[ s ] ); fclose( fp ); } void TEnvironment::ReadPop( char* fileName ) { FILE* fp; if( ( fp = fopen( fileName, "r" ) ) == NULL ){ printf( "Read Error1\n"); fflush( stdout ); exit( 1 ); } for ( int i = 0; i < fNumOfPop; ++i ){ if( fEvaluator->ReadFrom( fp, tCurPop[ i ] ) == false ){ printf( "Read Error2\n"); fflush( stdout ); exit( 1 ); } } fclose( fp ); }
22.905085
111
0.590647
ozeasx
b8668ca924e116c748694cf5d83e60c22889dd35
62,302
cpp
C++
AGM/Resource.cpp
tvrusso/soral
bc4a27e4330458934d3224e8bdaf4cfcb189752b
[ "MIT" ]
null
null
null
AGM/Resource.cpp
tvrusso/soral
bc4a27e4330458934d3224e8bdaf4cfcb189752b
[ "MIT" ]
null
null
null
AGM/Resource.cpp
tvrusso/soral
bc4a27e4330458934d3224e8bdaf4cfcb189752b
[ "MIT" ]
null
null
null
/***************************************************************************** * -- AGM SAR -- * -------------------------------------------------------------------- * Copyright (C) 2001-2008 AGM, a team comprising Andre Oboler, Gareth * Thompson and Michael Eldridge. * -------------------------------------------------------------------- * This file is part of AGM SAR. * * AGM SAR is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3, * as published by the Free Software Foundation. However, this * notice must be retained. * * AGM SAR uses the SORAL library, available separately under the GNU * General Public License, and distributed here in compliance with * that license. * * AGM SAR 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. Use is at your * own risk. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AGM SAR (see license.txt). If not, see * <http://www.gnu.org/licenses/>. * * We are willing to offer alternative licensing arrangements if * necessary. Our contact details are in readme.txt. * -------------------------------------------------------------------- * -------------------------------------------------------------------- * Resource.cpp * * Resources stores details of all available SRUs (including their assignments * to search areas). It is possible to add, delete, modify and view SRUs; * add, view and clear assignments to areas; and add and delete correction * factors. Resources also provides necessary data about the SRUs stored to * other modules in the program. * *-----+----------+-----+----------------------------------------------------- * Who | When | Ver | What *-----+----------+-----+----------------------------------------------------- * GT | 02/04/01 | 1 | Created. *---------------------------------------------------------------------------- * GT | 21/04/01 | 2 | Updated. Major changes in functionality for stage * | | | 2. Type of POD changed to double. Many functions * | | | modified to better interact with user. *---------------------------------------------------------------------------- * GT | 27/04/01 | 3 | Updated. Now stores assignments using class * | | | Assignment. *---------------------------------------------------------------------------- * GT | 07/05/01 | 4 | Updated. Now stores only one assignment to each * | | | Area for each SRU. Does not store assignments * | | | with Resource Hours 0. *---------------------------------------------------------------------------- * GT | 25/05/01 | 5 | Updated. Now handles correction factors. *---------------------------------------------------------------------------- * GT | 28/05/01 | 6 | Updated. Error handling and input/output fixed. *---------------------------------------------------------------------------- * AO | 07/03/08 | 6.1 | Gareth altered copyright notice etc for release, * | | | Andre updated version info and (c) date *---------------------------------------------------------------------------- */ //#include <string> #include <iomanip> #include <iostream> #include <sstream> #include <algorithm> #include <vector> #include <stdlib.h> #include <stdio.h> #include "global.h" #include "Err_mngr.h" #include "InputFil.h" #include "Assignmt.h" #include "Resource.h" using namespace std; /****************************************************************************** * getResourceNumList() * * Returns a vector<int> containing the set of Resource * Numbers of SRUs in SRUlist, in ascending order. * Because all functions of Resources access SRUs via * Resource Number, this list is needed to enable external * parts of the program to access the SRUs that are * stored in this Resources object. * Note that the number of SRUs is equal to the size of * this list. * * Author : Gareth Thompson */ vector<int> Resources::getResourceNumList(void) { if (testmode) cout << "entering Resources::getResourceNumList()\n"; /* Sort SRUlist into ascending order by Resource Number */ sortResNum(); vector<int> list; vector<SRU>::iterator current; for (current = SRUlist.begin(); current != SRUlist.end(); current++) { list.push_back(current->getResourceNum()); } return list; } /****************************************************************************** * loadSRUs() * * Obtains SRUs from a datafile with a specified filename * and appends them to SRUlist. * * If a file with the specified filename cannot be opened, * a warning is posted. * * If the file can be opened, each record is read from the * file in turn. If this record is of the correct format, * and there is no existing SRU with the specified Resource * Number, an SRU with the given data is appended to SRUlist. * * If an SRU with the specified Resource Number already exists, * a warning is posted and no SRU is added. * * If the data read is of the incorrect format, all or part of * the data is ignored, a warning is posted and no SRU is added. * * Returns true if 1 or more SRUs are added to SRUlist, * false otherwise. * * Author : Gareth Thompson */ bool Resources::loadSRUs(string filename) { if (testmode) cout << "entering Resources::loadSRUs(" << filename << ")\n"; InputFile in; string record; if (!in.open(filename)) { error_manager->PostError(WARNING_OPTION, "File "+filename+" could not be opened. No Resources data loaded.", "Resources::loadSRUs() - File could not be opened"); return false; } bool added = false; // no SRUs have been added while (in.getRecord(record)) { if (testmode) cout << "LINE: " << in.lastRecLine() << " RECORD: " << record << endl; /* Tokenise record read from file at commas */ vector<string> data = Tokenise(record, ','); /* Strip leading and trailing whitespace from each token */ data = StripWhite(data); if (testmode) { cout << "SPLIT RECORD: "; PrintStringVector(data); } /* * Having extracted the pieces of data from the * record, we now create a new SRU in SRUlist * using this data. */ if (data.size() != 7) { /* Incorrect number of tokens in this record */ error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - This line does not have 7 pieces of data specified. SRU ignored.", "Resources::loadSRUs() - Less or more than 7 comma-separated tokens on line of file."); } else { /* Correct number of tokens in this record. */ /* Create new SRU object to insert into SRUlist */ SRU sruTemp; /* Check if first piece of data is a valid Resource Number */ if (!IsInt(data[0])) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Resource Number "+data[0]+" is not a valid integer. SRU ignored.", "Resources::loadSRUs() - data[0] does not contain a valid integer."); continue; } int resourceNum = atoi(data[0].c_str()); if (!sruTemp.setResourceNum(resourceNum)) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Resource Number "+data[0]+" is not between "+ConvertToStr((int)DataLimits::resourceNum_min)+" and "+ConvertToStr((int)DataLimits::resourceNum_max)+". SRU ignored.", "Resources::loadSRUs() - data[0] does not contain a valid Resource Number."); continue; } /* No checking necessary for Resource Type */ sruTemp.setResourceType(data[1]); /* Check if third piece of data is a valid POD */ if (!IsFloat(data[2])) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - POD "+data[2]+" is not a valid floating point number. SRU ignored.", "Resources::loadSRUs() - data[2] does not contain a valid floating point number."); continue; } double POD = atof(data[2].c_str()); if (!sruTemp.setPOD(POD)) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - POD "+data[2]+" is not between "+ConvertToStr(DataLimits::POD_min)+" and "+ConvertToStr(DataLimits::POD_max)+". SRU ignored.", "Resources::loadSRUs() - data[2] does not contain a valid POD."); continue; } /* Check if fourth piece of data is a valid ESW */ if (!IsFloat(data[3])) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - ESW "+data[3]+" is not a valid floating point number. SRU ignored.", "Resources::loadSRUs() - data[3] does not contain a valid floating point number."); continue; } double ESW = atof(data[3].c_str()); if (!sruTemp.setESW(ESW)) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - ESW "+data[3]+" is not between "+ConvertToStr(DataLimits::ESW_min)+" and "+ConvertToStr(DataLimits::ESW_max)+". SRU ignored.", "Resources::loadSRUs() - data[3] does not contain a valid ESW."); continue; } /* Check if fifth piece of data is a valid Speed */ if (!IsFloat(data[4])) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Speed "+data[4]+" is not a valid floating point number. SRU ignored.", "Resources::loadSRUs() - data[4] does not contain a valid floating point number."); continue; } double speed = atof(data[4].c_str()); if (!sruTemp.setSpeed(speed)) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Speed "+data[4]+" is not between "+ConvertToStr(DataLimits::speed_min)+" and "+ConvertToStr(DataLimits::speed_max)+". SRU ignored.", "Resources::loadSRUs() - data[4] does not contain a valid Speed."); continue; } /* Check if sixth piece of data is a valid number of Hours Available */ if (!IsInt(data[5])) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Hours Available "+data[5]+" is not a valid integer. SRU ignored.", "Resources::loadSRUs() - data[5] does not contain a valid integer."); continue; } int hoursAvail = atoi(data[5].c_str()); if (!sruTemp.setHoursAvail(hoursAvail)) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Hours Available "+data[5]+" is not between "+ConvertToStr((int)DataLimits::hoursAvailable_min)+" and "+ConvertToStr((int)DataLimits::hoursAvailable_max)+". SRU ignored.", "Resources::loadSRUs() - data[5] does not contain a valid Hours Available value."); continue; } /* Check if SRU can be added */ if (!addSRU(sruTemp)) { /* SRU could not be added because there is already an SRU with the specified Resource Number. */ error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - An SRU with Resource Number "+ConvertToStr(resourceNum)+" already exists. SRU ignored.", "Resources::loadSRUs() - addSRU(sruTemp) returned false; SRU could not be added."); continue; } added = true; //SRU added /* Obtain iterator which points to this SRU */ vector<SRU>::iterator SRUiter = findSRU(resourceNum); /* Now add correction factors */ /* Check that correction factor string has leading/trailing brackets, and remove them */ string correctionString; if (data[6][0] == '(' && data[6][data[6].size()-1] == ')') { correctionString = data[6].substr(1, data[6].size()-2); if (testmode) cout << "Correction factor string: " << correctionString << "\n"; } else { /* Correction factor string does not have leading/trailing brackets */ error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Correction factors string is not correctly parenthesised. All correction factors for this SRU ignored.", "Resources::loadSRUs() - data[6] does not have leading and trailing brackets."); continue; } if (testmode) cout << "Correction factor string: " << correctionString << "\n"; /* Tokenise correction factor string at '(' to obtain a separate string for each correction factor. */ vector<string> correctionData = Tokenise(correctionString, '('); if (testmode) { cout << "Split Correction factor string: "; PrintStringVector(correctionData); } /* Strip leading and trailing whitespace from each token */ correctionData = StripWhite(correctionData); /* Check if first element (the part of the correction String before the first '(') is blank */ if (correctionData[0].size() != 0) { /* First element is an error */ error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Correction factor "+correctionData[0]+" does not have a leading bracket. Correction factor ignored.", "Resources::loadSRUs() - correctionsData[0] is not blank"); } /* Ignore first element */ correctionData.erase(correctionData.begin()); if (testmode) { cout << "Correction factor string without first element: "; PrintStringVector(correctionData); } /* Add each correction factor to SRU in turn */ vector<string>::iterator current; for (current = correctionData.begin(); current != correctionData.end(); current++) { /* Check that correction factor also has a trailing bracket, and remove it */ string correctionFactor; if ((*current)[current->size()-1] == ')') { correctionFactor = current->substr(0, current->size()-1); } else { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Correction factor ("+(*current)+" does not have a trailing bracket. Correction factor ignored.", "Resources::loadSRUs() - (*current)[current->size()-1] is not ')'"); continue; } /* * Tokenise correctionFactor at '/' to obtain separate terrain/vegetation/factor * values for this correction factor. */ vector<string> correctionNumbers = Tokenise(correctionFactor, '/'); if (testmode) { cout << "Data for correction factor: "; PrintStringVector(correctionNumbers); } /* Strip leading/trailing whitespace from each number */ correctionNumbers = StripWhite(correctionNumbers); /* Check that we have correct number of pieces of data for this correction factor (3). */ if (correctionNumbers.size() != 3) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Correction factor ("+(*current)+" does not have 3 pieces of data. Correction factor ignored.", "Resources::loadSRUs() - Less or more than 3 / separated tokens in a correction factor."); continue; } /* Check that first piece of data for this correction factor is a valid terrain value. */ if (!IsInt(correctionNumbers[0])) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Terrain "+correctionNumbers[0]+" for correction factor ("+(*current)+" is not a valid integer. Correction factor ignored.", "Resources::loadSRUs() - correctionNumbers[0] is not a valid integer."); continue; } int terrain = atoi(correctionNumbers[0].c_str()); if (!DataLimits::isValidTerrain(terrain)) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Terrain "+correctionNumbers[0]+" for Correction factor ("+(*current)+" is not between "+ConvertToStr((int)DataLimits::terrain_min)+" and "+ConvertToStr((int)DataLimits::terrain_max)+". Correction factor ignored.", "Resources::loadSRUs() - correctionNumbers[0] does not contain a valid terrain value."); continue; } /* Check that second piece of data for correction factor is a valid vegetation value. */ if (!IsInt(correctionNumbers[1])) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Vegetation "+correctionNumbers[1]+" for correction factor ("+(*current)+" is not a valid integer. Correction factor ignored.", "Resources::loadSRUs() - correctionNumbers[1] is not a valid integer."); continue; } int vegetation = atoi(correctionNumbers[1].c_str()); if (!DataLimits::isValidVegetation(vegetation)) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Vegetation "+correctionNumbers[1]+" for Correction factor ("+(*current)+" is not between "+ConvertToStr((int)DataLimits::vegetation_min)+" and "+ConvertToStr((int)DataLimits::vegetation_max)+". Correction Factor ignored.", "Resources::loadSRUs() - correctionNumbers[1] does not contain a valid vegetation value."); continue; } /* Check that third piece of data for correction factor is a valid correction factor value. */ if (!IsFloat(correctionNumbers[2])) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Factor "+correctionNumbers[2]+" for correction factor ("+(*current)+" is not a valid floating point number. Correction factor ignored.", "Resources::loadSRUs() - correctionNumbers[2] is not a valid floating point number."); continue; } double factor = atof(correctionNumbers[2].c_str()); if (!SRU::isValidCorrectionFactor(factor)) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Factor "+correctionNumbers[2]+" for Correction factor ("+(*current)+" is not between "+ConvertToStr(DataLimits::correctionFactor_min)+" and "+ConvertToStr(DataLimits::correctionFactor_max)+". Correction Factor ignored.", "Resources::loadSRUs() - correctionNumbers[2] does not contain a valid correction factor value."); continue; } /* * Check that a correction factor has not already been loaded * for this combination of terrain and vegetation. */ if (SRUiter->isCorrectionFactorSet(terrain, vegetation)) { error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Duplicate correction factors specified for terrain = "+correctionNumbers[0]+" and vegetation = "+correctionNumbers[1]+". Second correction factor ignored.", "Resources::loadSRUs() - isCorrectionFactorSet(terrain, vegetation) returns true for specified terrain and vegetation values"); continue; } /* Correction factor is correct and should be stored */ if (!SRUiter->setCorrectionFactor(terrain, vegetation, factor)) { /* Should never be executed, but include error-checking code in case */ error_manager->PostError(WARNING, "File "+filename+" line "+ConvertToStr(in.lastRecLine())+" - Miscellaneous error with correction factor ("+(*current)+". Correction factor could not be loaded.", "Resources::loadSRUs() - SRUiter->setCorrectionFactor(terrain, vegetation, factor) returned false for valid values of terrain/vegetation/factor."); } } } } in.close(); if (testmode) cout << "Data loaded from file." << "\n"; return added; } /****************************************************************************** * addSRU() * * Adds the specified SRU to SRUlist. * * If an SRU with the same Resource Number is not present in SRUlist, sru * is added and true is returned. * * If an SRU with the same Resource Number is already present, sru is * not added and false is returned. * * Author : Gareth Thompson */ bool Resources::addSRU(const SRU& sru) { if (testmode) cout << "entering Resources::addSRU()\n"; if (isSRU(sru.getResourceNum())) { return false; } else { SRUlist.push_back(sru); return true; } } /****************************************************************************** * deleteSRU() * * Removes the SRU with the specified Resource Number from SRUlist. * * If an SRU with the specified Resource Number exists, it is deleted and * true is returned. * * Otherwise, an error is posted and false is returned. * * Author : Gareth Thompson */ bool Resources::deleteSRU(int resourceNum) { if (testmode) cout << "entering Resources::deleteSRU(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter == SRUlist.end()) { /* SRU with specified Resource Number is not present */ error_manager->PostError(WARNING, "There is no SRU with Resource Number "+ConvertToStr(resourceNum)+". SRU could was not deleted.", "Resources::deleteSRU() - findSRU(resourceNum) returned SRUlist.end()"); return false; } else { /* SRU with specified Resource Number is present. */ SRUlist.erase(SRUiter); return true; } } /****************************************************************************** * userEnterSRU() * * Allows the user to specify details of a new SRU via standard input. * * If the user selects an unused Resource Number, they are then prompted * to enter the remaining data, the SRU is added to SRUlist, * and true is returned. * If any piece of data entered is invalid, the user is re-prompted to * enter that data. * * If the user selects a Resource Number which is already used, no data is * accepted, no SRU is added, an error is posted and false is returned. * * Author : Gareth Thompson */ bool Resources::userEnterSRU(void) { if (testmode) cout << "entering Resources::userEnterSRU()\n"; cout << "Please enter the details for the new SRU:\n\n"; /* Create SRU object to add to SRUlist */ SRU sruTemp; /* Get and check resource Number */ int resourceNum = GetValidInputInteger("Resource Number (integer "+ConvertToStr((int)DataLimits::resourceNum_min)+" to "+ConvertToStr((int)DataLimits::resourceNum_max)+"): ", "Invalid entry!", DataLimits::resourceNum_min, DataLimits::resourceNum_max); /* Resource number is correct and should be stored */ if (!sruTemp.setResourceNum(resourceNum)) { /* Should never be executed, but include error-checking code in case */ error_manager->PostError(WARNING, "Miscellaneous error with resource Number "+ConvertToStr(resourceNum)+". SRU could not be added.", "Resources::userEnterSRU() - setResourceNum(resourceNum) returned false for valid resourceNum"); return false; } /* Check if an SRU with this Resource Number exists */ if (isSRU(resourceNum)) { error_manager->PostError(WARNING, "An SRU with Resource Number "+ConvertToStr(resourceNum)+" already exists. SRU could not be added.", "Resource::userEnterSRU() - isSRU(resourceNum) returned true"); return false; } /* No checking necessary for Resource Type */ cout << "Resource Type (text string): "; sruTemp.setResourceType(GetInputString(cin)); /* Get and check POD */ double POD = GetValidInputFloat("POD (floating point number "+ConvertToStr(DataLimits::POD_min)+" to "+ConvertToStr(DataLimits::POD_max)+")% : ", "Invalid entry!", DataLimits::POD_min, DataLimits::POD_max); /* POD is correct and should be stored */ if (!sruTemp.setPOD(POD)) { /* Should never be executed, but include error-checking code in case */ error_manager->PostError(WARNING, "Miscellaneous error with POD "+ConvertToStr(POD)+". SRU could not be added.", "Resources::userEnterSRU() - setPOD(POD) returned false for valid POD"); return false; } /* Get and check ESW */ double ESW = GetValidInputFloat("ESW (floating point number "+ConvertToStr(DataLimits::ESW_min)+" to "+ConvertToStr(DataLimits::ESW_max)+")m : ", "Invalid entry!", DataLimits::ESW_min, DataLimits::ESW_max); /* ESW is correct and should be stored */ if (!sruTemp.setESW(ESW)) { /* Should never be executed, but include error-checking code in case */ error_manager->PostError(WARNING, "Miscellaneous error with ESW "+ConvertToStr(ESW)+". SRU could not be added.", "Resources::userEnterSRU() - setESW(ESW) returned false for valid ESW"); return false; } /* Get and check Speed */ double speed = GetValidInputFloat("Speed (floating point number "+ConvertToStr(DataLimits::speed_min)+" to "+ConvertToStr(DataLimits::speed_max)+")km/hr : ", "Invalid entry!", DataLimits::speed_min, DataLimits::speed_max); /* Speed is correct and should be stored */ if (!sruTemp.setSpeed(speed)) { /* Should never be executed, but include error-checking code in case */ error_manager->PostError(WARNING, "Miscellaneous error with Speed "+ConvertToStr(speed)+". SRU could not be added.", "Resources::userEnterSRU() - setSpeed(speed) returned false for valid speed"); return false; } /* Get and check Hours Available */ int hoursAvail = GetValidInputInteger("Resource-hours Available (integer "+ConvertToStr((int)DataLimits::hoursAvailable_min)+" to "+ConvertToStr((int)DataLimits::hoursAvailable_max)+"): ", "Invalid entry!", DataLimits::hoursAvailable_min, DataLimits::hoursAvailable_max); /* Hours Available is correct and should be stored */ if (!sruTemp.setHoursAvail(hoursAvail)) { /* Should never be executed, but include error-checking code in case */ error_manager->PostError(WARNING, "Miscellaneous error with Resource-Hours Available "+ConvertToStr(hoursAvail)+". SRU could not be added.", "Resources::userEnterSRU() - setHoursAvail(hoursAvail) returned false for valid hoursAvail"); return false; } /* SRU should now be added */ if (!addSRU(sruTemp)) { /* Should never be executed, but include error-checking code in case */ error_manager->PostError(WARNING, "Miscellaneous error when adding SRU. SRU not added.", "Resources::userEnterSRU() - addSRU(sruTemp) returned false for sruTemp with a unique Resource Number"); return false; } return true; } /****************************************************************************** * userModifySRU() * * Allows the user to modify details of an SRU with a specified Resource * Number. * * If an SRU with the specified Resource Number exists, the user is prompted * for the new details, the SRU is modified and true is returned. * If any piece of data is invalid (including if the Resource Number * specified is already used by another SRU), the user is reprompted to * enter that data. * * If there is no SRU with the specified Resource Number, no data is accepted, * no modification is made, an error is posted and and true is returned. * * Author : Gareth Thompson */ bool Resources::userModifySRU(int resourceNum) { if (testmode) cout << "entering Resources::userModifySRU(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter == SRUlist.end()) { /* SRU with specified Resource Number is not present */ error_manager->PostError(WARNING, "There is no SRU with Resource Number "+ConvertToStr(resourceNum)+". SRU could not be modified.", "Resources::userModifySRU() - findSRU(resourceNum) returned SRUlist.end()"); return false; } /* Get and check resource Number */ int newResourceNum; do { newResourceNum = GetValidInputInteger("New Resource Number (integer "+ConvertToStr((int)DataLimits::resourceNum_min)+" to "+ConvertToStr((int)DataLimits::resourceNum_max)+"): ", "Invalid entry!", DataLimits::resourceNum_min, DataLimits::resourceNum_max); if (newResourceNum != resourceNum && isSRU(newResourceNum)) { /* Attempting to change Resource Number to that of another existing SRU */ cout << "There is already an SRU with Resource Number " << newResourceNum << "\n"; } } while (newResourceNum != resourceNum && isSRU(newResourceNum)); /* Resource number is correct and should be stored */ if (!SRUiter->setResourceNum(newResourceNum)) { /* Should never be executed, but include error-checking code in case */ error_manager->PostError(WARNING, "Miscellaneous error with resource Number "+ConvertToStr(newResourceNum)+". SRU could not be correctly modified.", "Resources::userModifySRU() - setResourceNum(newResourceNum) returned false for valid newResourceNum"); return false; } /* No checking necessary for Resource Type */ cout << "New Resource Type (text string) : "; SRUiter->setResourceType(GetInputString(cin)); /* Get and check POD */ double POD = GetValidInputFloat("New POD (floating point number "+ConvertToStr(DataLimits::POD_min)+" to "+ConvertToStr(DataLimits::POD_max)+")% : ", "Invalid entry!", DataLimits::POD_min, DataLimits::POD_max); /* POD is correct and should be stored */ if (!SRUiter->setPOD(POD)) { /* Should never be executed, but include error-checking code in case */ error_manager->PostError(WARNING, "Miscellaneous error with POD "+ConvertToStr(POD)+". SRU could not be correctly modified.", "Resources::userModifySRU() - setPOD(POD) returned false for valid POD"); return false; } /* Get and check ESW */ double ESW = GetValidInputFloat("New ESW (floating point number "+ConvertToStr(DataLimits::ESW_min)+" to "+ConvertToStr(DataLimits::ESW_max)+")m : ", "Invalid entry!", DataLimits::ESW_min, DataLimits::ESW_max); /* ESW is correct and should be stored */ if (!SRUiter->setESW(ESW)) { /* Should never be executed, but include error-checking code in case */ error_manager->PostError(WARNING, "Miscellaneous error with ESW "+ConvertToStr(ESW)+". SRU could not correctly modified.", "Resources::userModifySRU() - setESW(ESW) returned false for valid ESW"); return false; } /* Get and check Speed */ double speed = GetValidInputFloat("New Speed (floating point number "+ConvertToStr(DataLimits::speed_min)+" to "+ConvertToStr(DataLimits::speed_max)+")km/hr : ", "Invalid entry!", DataLimits::speed_min, DataLimits::speed_max); /* Speed is correct and should be stored */ if (!SRUiter->setSpeed(speed)) { /* Should never be executed, but include error-checking code in case */ error_manager->PostError(WARNING, "Miscellaneous error with Speed "+ConvertToStr(speed)+". SRU could not be correctly modified.", "Resources::userModifySRU() - setSpeed(speed) returned false for valid speed"); return false; } /* Get and check Hours Available */ int hoursAvail = GetValidInputInteger("New Resource-hours Available (integer "+ConvertToStr((int)DataLimits::hoursAvailable_min)+" to "+ConvertToStr((int)DataLimits::hoursAvailable_max)+"): ", "Invalid entry!", DataLimits::hoursAvailable_min, DataLimits::hoursAvailable_max); /* Hours Available is correct and should be stored */ if (!SRUiter->setHoursAvail(hoursAvail)) { /* Should never be executed, but include error-checking code in case */ error_manager->PostError(WARNING, "Miscellaneous error with Resource-Hours Available "+ConvertToStr(hoursAvail)+". SRU could not be correctly modified.", "Resources::userModifySRU() - setHoursAvail(hoursAvail) returned false for valid hoursAvail"); return false; } return true; } /****************************************************************************** * viewSRU() * * Prints the details of an SRU with a specified Resource Number to standard * output. An error is posted if there is no SRU with that Resource Number. * * Author : Gareth Thompson */ void Resources::viewSRU(int resourceNum) { if (testmode) cout << "entering Resources::viewSRU(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter == SRUlist.end()) { /* SRU with specified Resource Number is not present. */ error_manager->PostError(WARNING, "There is no SRU with Resource Number "+ConvertToStr(resourceNum)+". SRU could not be viewed.", "Resources::viewSRU() - findSRU(resourceNum) returned SRUlist.end()"); } else { /* SRU with specified Resource Number is present. */ cout << "Resource Type: " << SRUiter->getResourceType() << "\n"; printf("POD: %.2f%%\n", SRUiter->getPOD()); printf("ESW: %.2fm\n", SRUiter->getESW()); printf("Speed: %.2fkm/h\n", SRUiter->getSpeed()); cout << "Resource-hours available: " << SRUiter->getHoursAvail() << endl; } } /****************************************************************************** * viewAllSRUs() * * Prints details of all SRUs to standard output in a * table form. * * Author : Gareth Thompson */ void Resources::viewAllSRUs(void) { if (testmode) cout << "entering Resources::viewAllSRUs()\n"; /* Output headings for table */ cout << " Num Type POD ESW Speed Hours\n"; cout << " (%) (m) (km/h) Avail\n"; cout << "\n"; /* Sort SRUs by Resource Number */ sortResNum(); /* Output details of each SRU */ vector<SRU>::iterator current; for (current = SRUlist.begin(); current != SRUlist.end(); current++) { printf("%4d ", current->getResourceNum()); cout << ResizeString(current->getResourceType(), 30, 30) << " "; printf("%5.1f ", current->getPOD()); printf("%6.1f ", current->getESW()); printf("%6.1f ", current->getSpeed()); printf("%6d\n", current->getHoursAvail()); } } /****************************************************************************** * outputAllSRUs() * * Outputs all SRUs (in ascending order by Resource Number) * to an output stream in the Resources file format. This * is useful for output to files. * * Author : Gareth Thompson */ void Resources::outputAllSRUs(ostream& out) { if (testmode) cout << "entering Resources::outputAllSRUs()\n"; sortResNum(); vector<SRU>::iterator SRUCurrent; for (SRUCurrent = SRUlist.begin(); SRUCurrent != SRUlist.end(); SRUCurrent++) { out << SRUCurrent->getSRUString() << "\n"; } } /****************************************************************************** * Resources::userEnterCorrectionFactor() * * Allows the user to enter a correction factor for the specified SRU. * * If the specified SRU exists, the user is prompted for terrain, vegetation * and correction factor, the result is stored (overwriting any * previous correction factor) and true is returned. * If any piece of data entered is invalid, the user is re-prompted to * enter that data. * * If there is no SRU with the specified Resource Number, no data is accepted, * no correction factor is set, an error is posted, and false is returned. * * Author : Gareth Thompson */ bool Resources::userEnterCorrectionFactor(int resourceNum) { if (testmode) cout << "entering Resources::userEnterCorrectionFactor(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter == SRUlist.end()) { /* SRU with specified Resource Number is not present */ error_manager->PostError(WARNING, "There is no SRU with Resource Number "+ConvertToStr(resourceNum)+". Correction factor could not be entered.", "Resources::userEnterCorrectionFactor() - findSRU(resourceNum) returned SRUlist.end()"); return false; } int terrain = GetValidInputInteger("Terrain value (integer "+ConvertToStr((int)DataLimits::terrain_min)+" to "+ConvertToStr((int)DataLimits::terrain_max)+") : ", "Invalid entry!", DataLimits::terrain_min, DataLimits::terrain_max); int vegetation = GetValidInputInteger("Vegetation value (integer "+ConvertToStr((int)DataLimits::vegetation_min)+" to "+ConvertToStr((int)DataLimits::vegetation_max)+") : ", "Invalid entry!", DataLimits::vegetation_min, DataLimits::vegetation_max); double factor = GetValidInputFloat("Factor (floating point number "+ConvertToStr(DataLimits::correctionFactor_min)+" to "+ConvertToStr(DataLimits::correctionFactor_max)+") : ", "Invalid entry!", DataLimits::correctionFactor_min, DataLimits::correctionFactor_max); /* Correction Factor should now be set */ if (!SRUiter->setCorrectionFactor(terrain, vegetation, factor)) { /* Should never be executed, but include error-checking code in case */ error_manager->PostError(WARNING, "Miscellaneous error when adding correction factor. Correction factor not set.", "Resources::userEnterCorrectionFactor() - setCorrectionFactor(terrain, vegetation, factor) returned false for valid terrain / vegetation / factor"); return false; } return true; } /****************************************************************************** * Resources::userDeleteCorrectionFactor() * * Allows the user to delete a correction factor for the specified SRU. * * If the specified SRU exists, the user is prompted for terrain and vegetation * values. If any piece of data is invalid, the user is re-prompted to enter * that data. * * If the SRU has a correction factor for that combination of terrain and * vegetation, it is deleted and true is returned. Otherwise, no change is * made, an error is posted and false is returned. * * If the specified SRU does not exist, no data is accepted, no change is made, * an error is posted and false is returned. * * Author : Gareth Thompson */ bool Resources::userDeleteCorrectionFactor(int resourceNum) { if (testmode) cout << "entering Resources::userDeleteCorrectionFactor(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter == SRUlist.end()) { /* SRU with specified Resource Number is not present */ error_manager->PostError(WARNING, "There is no SRU with Resource Number "+ConvertToStr(resourceNum)+". Correction factor could not be deleted.", "Resources::userDeleteCorrectionFactor() - findSRU(resourceNum) returned SRUlist.end()"); return false; } int terrain = GetValidInputInteger("Terrain value (integer "+ConvertToStr((int)DataLimits::terrain_min)+" to "+ConvertToStr((int)DataLimits::terrain_max)+") : ", "Invalid entry!", DataLimits::terrain_min, DataLimits::terrain_max); int vegetation = GetValidInputInteger("Vegetation value (integer "+ConvertToStr((int)DataLimits::vegetation_min)+" to "+ConvertToStr((int)DataLimits::vegetation_max)+") : ", "Invalid entry!", DataLimits::vegetation_min, DataLimits::vegetation_max); if (!SRUiter->isCorrectionFactorSet(terrain, vegetation)) { /* There is no current correction factor to delete */ error_manager->PostError(WARNING, "SRU "+ConvertToStr(resourceNum)+" does not have a correction factor for terrain = "+ConvertToStr(terrain)+" and vegetation = "+ConvertToStr(vegetation)+". Correction factor could not be deleted.", "Resources::userDeleteCorrectionFactor() - isCorrectionFactorSet(terrain, vegetation) returned false"); return false; } /* Correction Factor should now be deleted */ if (!SRUiter->deleteCorrectionFactor(terrain, vegetation)) { /* Should never be executed, but include error-checking code in case */ error_manager->PostError(WARNING, "Miscellaneous error when deleting correction factor. Correction factor not deleted.", "Resources::userDeleteCorrectionFactor() - deleteCorrectionFactor(terrain, vegetation) returned false when a correction factor was initially set for those terrain / vegetation values"); return false; } return true; } /****************************************************************************** * Resources::deleteCorrectionFactors() * * Allows the user to delete all correction factor for the specified SRU. * If the specified SRU exists, its correction factors are all deleted * and true is returned. * * If the SRU does not exist, no change is made, an error is posted, and false * is returned. * * Author : Gareth Thompson */ bool Resources::deleteCorrectionFactors(int resourceNum) { if (testmode) cout << "entering Resources::deleteCorrectionFactors(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter == SRUlist.end()) { /* SRU with specified Resource Number is not present */ error_manager->PostError(WARNING, "There is no SRU with Resource Number "+ConvertToStr(resourceNum)+". Correction factors could not be deleted.", "Resources::userDeleteCorrectionFactors() - findSRU(resourceNum) returned SRUlist.end()"); return false; } SRUiter->deleteCorrectionFactors(); return true; } /****************************************************************************** * Resources::viewCorrectionFactors() * * Prints the correction factors for the SRU with the * specified Resource Number. * If the SRU exists, its correction factors are printed * to standard output in table form. * If the SRU does not exist, an error is posted. * * Author : Gareth Thompson */ void Resources::viewCorrectionFactors(int resourceNum) { if (testmode) cout << "entering Resources::viewCorrectionFactors(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter != SRUlist.end()) { /* SRU with specified Resource Number is present */ SRUiter->viewCorrectionFactors(); } else { /* SRU with specified Resource Number is not present. */ error_manager->PostError(WARNING, "There is no SRU with Resource Number "+ConvertToStr(resourceNum)+". Correction Factors could not be viewed.", "Resources::viewCorrectionFactors() - findSRU(resourceNum) returned SRUlist.end()"); } } /****************************************************************************** * Resources::addAssignment() * * Adds theAssignment to the assignments of the SRU with the specified * Resource Number. * * If an SRU with the specified Resource Number exists, and * theAssignment.getResourceHours() is non-negative and not greater than the * number of resource-hours remaining for the SRU, theAssignment is added * to those for that SRU and true is returned. * * Otherwise, it is not possible for the SRU to have the assignment: * theAssignment is not added, and false is returned. * * Author : Gareth Thompson */ bool Resources::addAssignment(int resourceNum, const Assignment& theAssignment) { if (testmode) cout << "entering Resources::addAssignment(" << resourceNum << ", " << theAssignment.getAreaNum() << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter != SRUlist.end()) { /* SRU with specified Resource Number is present */ return SRUiter->addAssignment(theAssignment); } else { /* SRU with specified Resource Number is not present. */ return false; } } /****************************************************************************** * Resources::deleteAssignment() * * Removes the assignment with the specified Area Number from the * SRU with the specified Resource Number. * * If an SRU with the specified Resource Number exists, and has * an assignment with the specified Area Number, it is deleted and * true is returned. * * If the SRU does not exist, or has no assignment with the specified * Area Number, no change is made and false is returned. * * Author : Gareth Thompson */ bool Resources::deleteAssignment(int resourceNum, int areaNum) { if (testmode) cout << "entering Resources::deleteAssignment(" << resourceNum << ", " << areaNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter == SRUlist.end()) { /* SRU with specified Resource Number is not present. */ return false; } else { /* SRU with specified Resource Number is present. */ return SRUiter->deleteAssignment(areaNum); } } /****************************************************************************** * Resources::deleteAssignments() * * Deletes all Assignments for the SRU with the specified Resource Number. * * If an SRU with the specified Resource Number exists, its assignments are * deleted and true is returned. * * Otherwise, false is returned. * * Author : Gareth Thompson */ bool Resources::deleteAssignments(int resourceNum) { if (testmode) cout << "entering Resources::deleteAssignments(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter != SRUlist.end()) { /* SRU with specified Resource Number is present */ SRUiter->deleteAssignments(); return true; } else { /* SRU with specified Resource Number is not present. */ return false; } } /****************************************************************************** * Resources::getAssignments() * * Returns a vector<Assignment> containing the assignments * for the SRU with the specified Resource Number. * * If an SRU with the specified Resource Number does not * exist, the return value is undefined. * * Author : Gareth Thompson */ vector<Assignment> Resources::getAssignments(int resourceNum) { if (testmode) cout << "entering Resources::getAssignments(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter != SRUlist.end()) { /* SRU with specified Resource Number is present */ return SRUiter->getAssignments(); } else { /* SRU with specified Resource Number is not present. */ vector<Assignment> empty_assignments; return empty_assignments; //undefined return value } } /****************************************************************************** * viewAssignments() * * Prints the assignments for the SRU with the specified Resource Number to * standard output. An error is posted if there is no SRU with the specified * Resource Number. * * Author : Gareth Thompson */ void Resources::viewAssignments(int resourceNum) { if (testmode) cout << "entering Resources::viewAssignments(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter == SRUlist.end()) { /* SRU with specified Resource Number is not present. */ error_manager->PostError(WARNING, "There is no SRU with Resource Number "+ConvertToStr(resourceNum)+". Assignments could not be viewed.", "Resources::viewAssignments() - findSRU(resourceNum) returned SRUlist.end()"); } else { /* SRU with specified Resource Number is present. */ /* Sort Assignments into ascending order by Area Number, and print. */ SRUiter->sortAssignAreaNum(); vector<Assignment> temp; temp = getAssignments(resourceNum); PrintAssignmentVector(temp); } } /****************************************************************************** * deleteAllAssignments() * * Deletes the assignments for every SRU in SRUlist. * * Author : Gareth Thompson */ void Resources::deleteAllAssignments(void) { if (testmode) cout << "entering Resources::deleteAllAssignments()\n"; vector<SRU>::iterator current; for (current = SRUlist.begin(); current != SRUlist.end(); current++) { current->deleteAssignments(); } } /****************************************************************************** * viewAllAssignments() * * Prints the assignments of SRUs to areas (for searching) * to standard output in a table form, that is useful for * users to view. * * SRUs are sorted into ascending order by Resource Number. * Their Assignments are sorted into ascending order by * Area Number. * * Author : Gareth Thompson */ void Resources::viewAllAssignments(void) { if (testmode) cout << "entering Resources::viewAllAssignments()\n"; /* Output headings for table */ cout << " Res Hours Hours Area Hours\n"; cout << " Num Avail Used Num Assigned\n"; cout << "==================================================\n"; /* Sort SRUs by Resource Number */ sortResNum(); /* Output details of each SRU */ vector<SRU>::iterator current; for (current = SRUlist.begin(); current != SRUlist.end(); current++) { printf("%4d ", current->getResourceNum()); printf("%6d ", current->getHoursAvail()); printf("%9.2f ", current->getHoursAssigned()); /* Output the assignments for the SRU */ current->sortAssignAreaNum(); vector<Assignment> assignments = current->getAssignments(); if (assignments.size() == 0) { /* No assignments - output dashes */ cout << " - -\n"; } else { /* Output first assignment on current line */ printf("%4d ", assignments[0].getAreaNum()); printf("%9.2f\n", assignments[0].getResourceHours()); /* Output any remaining assignments on following lines */ int i; for (i=1; i<assignments.size(); i++) { printf(" %4d ", assignments[i].getAreaNum()); printf("%9.2f\n", assignments[i].getResourceHours()); } } /* Output line separating SRUs */ cout << "==================================================\n"; } } /****************************************************************************** * outputAllAssignments() * * Outputs all assignments to an output stream in the * Assignment file format. This is useful for output * to files. * * Assignments are sorted into ascending order by Resource * Number and then Area Number. * * Author : Gareth Thompson */ void Resources::outputAllAssignments(ostream& out) { if (testmode) cout << "entering Resources::outputAllAssignments()\n"; /* Sort SRUs by Resource Number */ sortResNum(); vector<SRU>::iterator SRUCurrent; for (SRUCurrent = SRUlist.begin(); SRUCurrent != SRUlist.end(); SRUCurrent++) { /* Sort Assignments by Area Number */ SRUCurrent->sortAssignAreaNum(); vector<Assignment> assignments = SRUCurrent->getAssignments(); vector<Assignment>::iterator assCurrent; for (assCurrent = assignments.begin(); assCurrent != assignments.end(); assCurrent++) { out << SRUCurrent->getResourceNum() << ", "; out << assCurrent->getAreaNum() << ", "; /* Output Resource Hours with 2 digits after decimal point */ char str[20]; sprintf(str, "%-9.2f", assCurrent->getResourceHours()); out << str << "\n"; } } } /****************************************************************************** * getHoursRemaining() * * Returns the number of resource-hours available for the SRU * with the specified Resource Number that have not yet been * assigned for searching. * * This value may be slightly negative, because of the * non-zero floating-point precision defined by FloatLess(). * (It is possible to assign more hours to a resource than * are available, provided that the assignments do not exceed * the hours available by more than the defined precision.) * * The return value is undefined if there is no SRU with the * specified Resource Number. * * It is best to call hoursRemaining() first to check that there * are hours remaining, before calling getHoursRemaining to * determine the actual number remaining. * * Author : Gareth Thompson */ double Resources::getHoursRemaining(int resourceNum) { if (testmode) cout << "entering Resources::getHoursRemaining(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter != SRUlist.end()) { /* SRU with specified Resource Number is present */ return SRUiter->getHoursRemaining(); } else { /* SRU with specified Resource Number is not present. */ return 0.0; //undefined return value } } /****************************************************************************** * Resources::getESW() * * Returns the ESW of the SRU with the specified Resource Number (IGNORING * CORRECTION FACTORS). * * The return value is undefined if there is no SRU with the * specified Resource Number. * * Author : Gareth Thompson */ double Resources::getESW(int resourceNum) { if (testmode) cout << "entering Resources::getESW(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter != SRUlist.end()) { /* SRU with specified Resource Number is present */ return SRUiter->getESW(); } else { /* SRU with specified Resource Number is not present. */ return 0.0; //undefined return value } } int Resources::getNumResources(void) { return SRUlist.size(); } /****************************************************************************** * Resources::getSpeed() * * Returns the Speed of the SRU with the specified Resource Number (IGNORING * CORRECTION FACTORS). * * The return value is undefined if there is no SRU with the * specified Resource Number. * * Author : Gareth Thompson */ double Resources::getSpeed(int resourceNum) { if (testmode) cout << "entering Resources::getSpeed(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter != SRUlist.end()) { /* SRU with specified Resource Number is present */ return SRUiter->getSpeed(); } else { /* SRU with specified Resource Number is not present. */ return 0.0; } } /****************************************************************************** * Resources::getCorrectionFactor() * * Returns the Correction Factor for the SRU with the specified Resource * Number, in an area with the specified terrain and vegetation. * * If the SRU exists, and the terrain and vegetation values are * valid the correction factor for the SRU is returned: * - If a correction factor has been defined for this combination * of terrain and vegetation values, it is returned. * - Otherwise, default correction factor 1.0 is returned. * * If there is no SRU with the specified Resource Number, or the * terrain/vegetation values are invalid, the return value is undefined. * * Author : Gareth Thompson */ double Resources::getCorrectionFactor(int resourceNum, int terrain, int vegetation) { if (testmode) cout << "entering Resources::getCorrectionFactor(" << resourceNum << ", " << terrain << ", " << vegetation << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter != SRUlist.end()) { /* SRU with specified Resource Number is present */ return SRUiter->getCorrectionFactor(terrain, vegetation); } else { /* SRU with specified Resource Number is not present. */ return -1.0; //undefined return value } } /****************************************************************************** * Resources::getEffectiveSweepRate() * * Returns the Effective Sweep Rate of the SRU with the * specified Resource Number (in km^2/hr). * * If an SRU with the specified Resource Number exists, its Effective Sweep * Rate is returned: * - If terrain and vegetation arguments are given, and they are valid values * the effective sweep rate of the SRU for that combination of terrain and * vegetation is returned. (This is the product of ESW, speed, and the * correction factor for that terrain.) * If the SRU does not have a correction factor for that combination of * vegetation and terrain, it is assued to be 1. * - If terrain and vegetation arguments are not given, or either is an * invalid value, then the effective sweep rate of the SRU, ignoring * correction factors, is returned. This is the product of ESW and speed. * * * If an SRU with the specified Resource Number does not exist, the return * value is undefined. * * Author : Gareth Thompson */ double Resources::getEffectiveSweepRate(int resourceNum, int terrain, int vegetation) { if (testmode) cout << "entering Resources::getEffectiveSweepRate(" << resourceNum << ", " << terrain << ", " << vegetation << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter != SRUlist.end()) { /* SRU with specified Resource Number is present */ return SRUiter->getEffectiveSweepRate(terrain, vegetation); } else { /* SRU with specified Resource Number is not present. */ return 0.0; //undefined return value } } /****************************************************************************** * Resources::hoursRemaining() * * Returns true if an SRU with the specified Resource * Number exists and has resource-hours that have not yet * been assigned for searching. * * Returns false if an SRU with the specified Resource Number * does not exist or does not have resource-hours remaining * to be assigned. * * Author : Gareth Thompson */ bool Resources::hoursRemaining(int resourceNum) { if (testmode) cout << "entering Resources::hoursRemaining(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = findSRU(resourceNum); if (SRUiter != SRUlist.end()) { /* SRU with specified Resource Number is present */ return SRUiter->hoursRemaining(); } else { /* SRU with specified Resource Number is not present. */ return false; } } /****************************************************************************** * anyHoursRemaining() * * Returns true if there any SRUs in SRUlist which have * Resource-hours available that have not yet been assigned * for searching. Otherwise, returns false. * * Author : Gareth Thompson */ bool Resources::anyHoursRemaining(void) { if (testmode) cout << "entering Resources::anyHoursRemaining()\n"; vector<SRU>::iterator current; for (current = SRUlist.begin(); current != SRUlist.end(); current++) { if (current->hoursRemaining()) { return true; } } return false; } /****************************************************************************** * getAreaEffectivelySweptRemaining() * * Returns the maximum Area Effectively Swept that can be achieved with the * Resource-hours that are available but that have not yet been assigned * to SRUs (ignoring correction factors for vegetation and terrain). * * The Area Effectively Swept Remaining for a given SRU is the product of * its Effective Sweep Rate (here, correction factors are ignored) and * hours remaining for searching. The value returned by this function is * the sum of the Area Effectively Swept Remaining values for all SRUs. * * Author : Gareth Thompson */ double Resources::getAreaEffectivelySweptRemaining(void) { if (testmode) cout << "entering Resources::getAreaEffectivelySweptRemaining()\n"; double areaEffecSweptRem = 0.0; vector<SRU>::iterator current; for (current = SRUlist.begin(); current != SRUlist.end(); current++) { areaEffecSweptRem += current->getEffectiveSweepRate() * current->getHoursRemaining(); } return areaEffecSweptRem; } /****************************************************************************** * menu() * * Menu which provides users with options for modifying * the SRUs stored in this Resources object. * * Returns true if any SRUs are modified. * Returns false if no SRUs are modified. * * Author : Gareth Thompson */ bool Resources::menu(void) { if (testmode) cout << "entering Resources::menu()\n"; int choice; bool modified = false; // no SRUs have been modified const int maxchoice = 11; do { cout << "\n"; cout << "********************" << endl; cout << "** Resources Menu **" << endl; cout << "********************" << endl; cout << "1. Enter a new SRU\n"; cout << "2. Load SRUs from a file\n"; cout << "3. Delete an SRU\n"; cout << "4. Delete all current SRUs\n"; cout << "5. Modify details of an SRU\n"; cout << "6. View details of an SRU\n"; cout << "7. View details of all SRUs\n"; cout << "8. View Correction factors for an SRU\n"; cout << "9. Enter a correction factor for an SRU\n"; cout << "10. Delete a correction factor for an SRU\n"; cout << "11. Delete all correction factors for an SRU\n"; cout << "0. Main Menu" << endl; if (testmode) cout << "MODIFIED: " << modified << "\n\n"; do { cout << "\nChoice: "; cin >> choice; if (choice < 0 || choice > maxchoice) { cout << "Invalid choice. Please enter 1-7 or 0!" << endl; } } while (choice < 0 || choice > maxchoice); if (choice == 1) /* Enter a new SRU */ { if (userEnterSRU()) modified = true; } else if (choice == 2) /* Load SRUs from a file */ { string filename; cout << "Enter filename to load SRUs from: "; filename = GetInputString(cin); if (loadSRUs(filename)) modified = true; } else if (choice == 3) /* Delete an SRU */ { int resourceNum; cout << "Enter the Resource Number for the SRU: "; cin >> resourceNum; if (deleteSRU(resourceNum)) modified = true; } else if (choice == 4) /* Delete all current SRUs */ { /* Only delete SRUs if there are some present, * so that we know if a modification has * been made. */ if (SRUlist.size() != 0) { deleteAllSRUs(); modified = true; } } else if (choice == 5) /* Modify details of an SRU */ { int resourceNum; cout << "Enter the Resource Number for the SRU: "; cin >> resourceNum; if (userModifySRU(resourceNum)) modified = true; } else if (choice == 6) /* View details of an SRU */ { int resourceNum; cout << "Enter the Resource Number for the SRU: "; cin >> resourceNum; viewSRU(resourceNum); } else if (choice == 7) /* View details of all SRU */ { viewAllSRUs(); } else if (choice == 8) { int resourceNum; bool success; do { cout << "Enter the Resource Number for the SRU: "; success = GetInputInteger(cin, resourceNum); if (!success) cout << "Invalid entry!\n"; } while (!success); cout << "\n"; viewCorrectionFactors(resourceNum); } else if (choice == 9) { int resourceNum = GetValidInputInteger("Enter the Resource Number of the SRU: ", "Invalid entry!"); userEnterCorrectionFactor(resourceNum); } else if (choice == 10) { int resourceNum = GetValidInputInteger("Enter the Resource Number of the SRU: ", "Invalid entry!"); userDeleteCorrectionFactor(resourceNum); } else if (choice == 11) { int resourceNum = GetValidInputInteger("Enter the Resource Number of the SRU: ", "Invalid entry!"); deleteCorrectionFactors(resourceNum); } } while (choice != 0); return modified; } /****************************************************************************** * findSRU() * * Finds the SRU with a specified Resource Number. * If an SRU with the specified Resource Number is * present, findSRU() returns an iterator to the * first SRU in the SRUlist which has that Resource Number. * If an SRU with the specified Resource Number is not * present, findSRU() returns an iterator equal to SRUlist.end(). * * Author : Gareth Thompson */ vector<Resources::SRU>::iterator Resources::findSRU(int resourceNum) { if (testmode) cout << "entering Resources::findSRU(" << resourceNum << ")\n"; vector<SRU>::iterator SRUiter = SRUlist.begin(); while (SRUiter != SRUlist.end()) { if (SRUiter->getResourceNum() == resourceNum) { return SRUiter; } SRUiter++; } return SRUiter; } /****************************************************************************** * sortResNum() * * Sorts SRUlist into ascending order by Resource Number. * * Author : Gareth Thompson */ void Resources::sortResNum(void) { if (testmode) cout << "entering Resources::sortResNum()\n"; /* * ltResNum compares SRUs using Resource Number. * The standard sort() function sorts SRUs using * ltResNum to compare SRUs. */ sort(SRUlist.begin(), SRUlist.end(), SRU::ltResNum()); }
41.562375
420
0.65831
tvrusso